src/HOLCF/Tools/fixrec.ML
author huffman
Wed May 19 13:07:15 2010 -0700 (2010-05-19)
changeset 36996 63fadc0a33db
parent 36960 01594f816e3a
child 37079 0cd15d8c90a0
permissions -rw-r--r--
more informative error message for fixrec when continuity proof fails
     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: bool -> (binding * typ option * mixfix) list
    10     -> (Attrib.binding * term) list -> local_theory -> local_theory
    11   val add_fixrec_cmd: bool -> (binding * string option * mixfix) list
    12     -> (Attrib.binding * string) list -> local_theory -> local_theory
    13   val add_fixpat: Thm.binding * term list -> theory -> theory
    14   val add_fixpat_cmd: Attrib.binding * string list -> theory -> theory
    15   val add_matchers: (string * string) list -> theory -> theory
    16   val fixrec_simp_add: attribute
    17   val fixrec_simp_del: attribute
    18   val fixrec_simp_tac: Proof.context -> int -> tactic
    19   val setup: theory -> theory
    20 end;
    21 
    22 structure Fixrec :> FIXREC =
    23 struct
    24 
    25 open HOLCF_Library;
    26 
    27 infixr 6 ->>;
    28 infix -->>;
    29 infix 9 `;
    30 
    31 val def_cont_fix_eq = @{thm def_cont_fix_eq};
    32 val def_cont_fix_ind = @{thm def_cont_fix_ind};
    33 
    34 fun fixrec_err s = error ("fixrec definition error:\n" ^ s);
    35 fun fixrec_eq_err thy s eq =
    36   fixrec_err (s ^ "\nin\n" ^ quote (Syntax.string_of_term_global thy eq));
    37 
    38 (*************************************************************************)
    39 (***************************** building types ****************************)
    40 (*************************************************************************)
    41 
    42 local
    43 
    44 fun binder_cfun (Type(@{type_name cfun},[T, U])) = T :: binder_cfun U
    45   | binder_cfun (Type(@{type_name "fun"},[T, U])) = T :: binder_cfun U
    46   | binder_cfun _   =  [];
    47 
    48 fun body_cfun (Type(@{type_name cfun},[T, U])) = body_cfun U
    49   | body_cfun (Type(@{type_name "fun"},[T, U])) = body_cfun U
    50   | body_cfun T   =  T;
    51 
    52 fun strip_cfun T : typ list * typ =
    53   (binder_cfun T, body_cfun T);
    54 
    55 in
    56 
    57 fun matcherT (T, U) =
    58   body_cfun T ->> (binder_cfun T -->> U) ->> U;
    59 
    60 end
    61 
    62 (*************************************************************************)
    63 (***************************** building terms ****************************)
    64 (*************************************************************************)
    65 
    66 val mk_trp = HOLogic.mk_Trueprop;
    67 
    68 (* splits a cterm into the right and lefthand sides of equality *)
    69 fun dest_eqs t = HOLogic.dest_eq (HOLogic.dest_Trueprop t);
    70 
    71 (* similar to Thm.head_of, but for continuous application *)
    72 fun chead_of (Const(@{const_name Rep_CFun},_)$f$t) = chead_of f
    73   | chead_of u = u;
    74 
    75 infix 0 ==;  val (op ==) = Logic.mk_equals;
    76 infix 1 ===; val (op ===) = HOLogic.mk_eq;
    77 
    78 fun mk_mplus (t, u) =
    79   let val mT = Term.fastype_of t
    80   in Const(@{const_name Fixrec.mplus}, mT ->> mT ->> mT) ` t ` u end;
    81 
    82 fun mk_run t =
    83   let val mT = Term.fastype_of t
    84       val T = dest_matchT mT
    85   in Const(@{const_name Fixrec.run}, mT ->> T) ` t end;
    86 
    87 
    88 (*************************************************************************)
    89 (************* fixed-point definitions and unfolding theorems ************)
    90 (*************************************************************************)
    91 
    92 structure FixrecUnfoldData = Generic_Data
    93 (
    94   type T = thm Symtab.table;
    95   val empty = Symtab.empty;
    96   val extend = I;
    97   fun merge data : T = Symtab.merge (K true) data;
    98 );
    99 
   100 local
   101 
   102 fun name_of (Const (n, T)) = n
   103   | name_of (Free (n, T)) = n
   104   | name_of t = raise TERM ("Fixrec.add_unfold: lhs not a constant", [t]);
   105 
   106 val lhs_name =
   107   name_of o head_of o fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of;
   108 
   109 in
   110 
   111 val add_unfold : attribute =
   112   Thm.declaration_attribute
   113     (fn th => FixrecUnfoldData.map (Symtab.insert (K true) (lhs_name th, th)));
   114 
   115 end
   116 
   117 fun add_fixdefs
   118   (fixes : ((binding * typ) * mixfix) list)
   119   (spec : (Attrib.binding * term) list)
   120   (lthy : local_theory) =
   121   let
   122     val thy = ProofContext.theory_of lthy;
   123     val names = map (Binding.name_of o fst o fst) fixes;
   124     val all_names = space_implode "_" names;
   125     val (lhss, rhss) = ListPair.unzip (map (dest_eqs o snd) spec);
   126     val functional = lambda_tuple lhss (mk_tuple rhss);
   127     val fixpoint = mk_fix (mk_cabs functional);
   128 
   129     val cont_thm =
   130       let
   131         val prop = mk_trp (mk_cont functional);
   132         fun err () = error (
   133           "Continuity proof failed; please check that cont2cont rules\n" ^
   134           "are configured for all non-HOLCF constants.\n" ^
   135           "The error occurred for the goal statement:\n" ^
   136           Syntax.string_of_term lthy prop);
   137         fun check th = case Thm.nprems_of th of 0 => all_tac th | n => err ();
   138         val tac = simp_tac (simpset_of lthy) 1 THEN check;
   139       in
   140         Goal.prove lthy [] [] prop (K tac)
   141       end;
   142 
   143     fun one_def (l as Free(n,_)) r =
   144           let val b = Long_Name.base_name n
   145           in ((Binding.name (b^"_def"), []), r) end
   146       | one_def _ _ = fixrec_err "fixdefs: lhs not of correct form";
   147     fun defs [] _ = []
   148       | defs (l::[]) r = [one_def l r]
   149       | defs (l::ls) r = one_def l (mk_fst r) :: defs ls (mk_snd r);
   150     val fixdefs = defs lhss fixpoint;
   151     val (fixdef_thms : (term * (string * thm)) list, lthy) = lthy
   152       |> fold_map Local_Theory.define (map (apfst fst) fixes ~~ fixdefs);
   153     fun pair_equalI (thm1, thm2) = @{thm Pair_equalI} OF [thm1, thm2];
   154     val tuple_fixdef_thm = foldr1 pair_equalI (map (snd o snd) fixdef_thms);
   155     val P = Var (("P", 0), map Term.fastype_of lhss ---> HOLogic.boolT);
   156     val predicate = lambda_tuple lhss (list_comb (P, lhss));
   157     val tuple_induct_thm = (def_cont_fix_ind OF [tuple_fixdef_thm, cont_thm])
   158       |> Drule.instantiate' [] [SOME (Thm.cterm_of thy predicate)]
   159       |> Local_Defs.unfold lthy @{thms split_paired_all split_conv split_strict};
   160     val tuple_unfold_thm = (def_cont_fix_eq OF [tuple_fixdef_thm, cont_thm])
   161       |> Local_Defs.unfold lthy @{thms split_conv};
   162     fun unfolds [] thm = []
   163       | unfolds (n::[]) thm = [(n, thm)]
   164       | unfolds (n::ns) thm = let
   165           val thmL = thm RS @{thm Pair_eqD1};
   166           val thmR = thm RS @{thm Pair_eqD2};
   167         in (n, thmL) :: unfolds ns thmR end;
   168     val unfold_thms = unfolds names tuple_unfold_thm;
   169     val induct_note : Attrib.binding * Thm.thm list =
   170       let
   171         val thm_name = Binding.qualify true all_names (Binding.name "induct");
   172       in
   173         ((thm_name, []), [tuple_induct_thm])
   174       end;
   175     fun unfold_note (name, thm) : Attrib.binding * Thm.thm list =
   176       let
   177         val thm_name = Binding.qualify true name (Binding.name "unfold");
   178         val src = Attrib.internal (K add_unfold);
   179       in
   180         ((thm_name, [src]), [thm])
   181       end;
   182     val (thmss, lthy) = lthy
   183       |> fold_map Local_Theory.note (induct_note :: map unfold_note unfold_thms);
   184   in
   185     (lthy, names, fixdef_thms, map snd unfold_thms)
   186   end;
   187 
   188 (*************************************************************************)
   189 (*********** monadic notation and pattern matching compilation ***********)
   190 (*************************************************************************)
   191 
   192 structure FixrecMatchData = Theory_Data
   193 (
   194   type T = string Symtab.table;
   195   val empty = Symtab.empty;
   196   val extend = I;
   197   fun merge data = Symtab.merge (K true) data;
   198 );
   199 
   200 (* associate match functions with pattern constants *)
   201 fun add_matchers ms = FixrecMatchData.map (fold Symtab.update ms);
   202 
   203 fun taken_names (t : term) : bstring list =
   204   let
   205     fun taken (Const(a,_), bs) = insert (op =) (Long_Name.base_name a) bs
   206       | taken (Free(a,_) , bs) = insert (op =) a bs
   207       | taken (f $ u     , bs) = taken (f, taken (u, bs))
   208       | taken (Abs(a,_,t), bs) = taken (t, insert (op =) a bs)
   209       | taken (_         , bs) = bs;
   210   in
   211     taken (t, [])
   212   end;
   213 
   214 (* builds a monadic term for matching a constructor pattern *)
   215 fun pre_build match_name pat rhs vs taken =
   216   case pat of
   217     Const(@{const_name Rep_CFun},_)$f$(v as Free(n,T)) =>
   218       pre_build match_name f rhs (v::vs) taken
   219   | Const(@{const_name Rep_CFun},_)$f$x =>
   220       let val (rhs', v, taken') = pre_build match_name x rhs [] taken;
   221       in pre_build match_name f rhs' (v::vs) taken' end
   222   | f$(v as Free(n,T)) =>
   223       pre_build match_name f rhs (v::vs) taken
   224   | f$x =>
   225       let val (rhs', v, taken') = pre_build match_name x rhs [] taken;
   226       in pre_build match_name f rhs' (v::vs) taken' end
   227   | Const(c,T) =>
   228       let
   229         val n = Name.variant taken "v";
   230         fun result_type (Type(@{type_name cfun},[_,T])) (x::xs) = result_type T xs
   231           | result_type (Type (@{type_name "fun"},[_,T])) (x::xs) = result_type T xs
   232           | result_type T _ = T;
   233         val v = Free(n, result_type T vs);
   234         val m = Const(match_name c, matcherT (T, fastype_of rhs));
   235         val k = big_lambdas vs rhs;
   236       in
   237         (m`v`k, v, n::taken)
   238       end
   239   | Free(n,_) => fixrec_err ("expected constructor, found free variable " ^ quote n)
   240   | _ => fixrec_err "pre_build: invalid pattern";
   241 
   242 (* builds a monadic term for matching a function definition pattern *)
   243 (* returns (name, arity, matcher) *)
   244 fun building match_name pat rhs vs taken =
   245   case pat of
   246     Const(@{const_name Rep_CFun}, _)$f$(v as Free(n,T)) =>
   247       building match_name f rhs (v::vs) taken
   248   | Const(@{const_name Rep_CFun}, _)$f$x =>
   249       let val (rhs', v, taken') = pre_build match_name x rhs [] taken;
   250       in building match_name f rhs' (v::vs) taken' end
   251   | Free(_,_) => ((pat, length vs), big_lambdas vs rhs)
   252   | Const(_,_) => ((pat, length vs), big_lambdas vs rhs)
   253   | _ => fixrec_err ("function is not declared as constant in theory: "
   254                     ^ ML_Syntax.print_term pat);
   255 
   256 fun strip_alls t =
   257   if Logic.is_all t then strip_alls (snd (Logic.dest_all t)) else t;
   258 
   259 fun match_eq match_name eq =
   260   let
   261     val (lhs,rhs) = dest_eqs (Logic.strip_imp_concl (strip_alls eq));
   262   in
   263     building match_name lhs (mk_return rhs) [] (taken_names eq)
   264   end;
   265 
   266 (* returns the sum (using +++) of the terms in ms *)
   267 (* also applies "run" to the result! *)
   268 fun fatbar arity ms =
   269   let
   270     fun LAM_Ts 0 t = ([], Term.fastype_of t)
   271       | LAM_Ts n (_ $ Abs(_,T,t)) =
   272           let val (Ts, U) = LAM_Ts (n-1) t in (T::Ts, U) end
   273       | LAM_Ts _ _ = fixrec_err "fatbar: internal error, not enough LAMs";
   274     fun unLAM 0 t = t
   275       | unLAM n (_$Abs(_,_,t)) = unLAM (n-1) t
   276       | unLAM _ _ = fixrec_err "fatbar: internal error, not enough LAMs";
   277     fun reLAM ([], U) t = t
   278       | reLAM (T::Ts, U) t = reLAM (Ts, T ->> U) (cabs_const(T,U)$Abs("",T,t));
   279     val msum = foldr1 mk_mplus (map (unLAM arity) ms);
   280     val (Ts, U) = LAM_Ts arity (hd ms)
   281   in
   282     reLAM (rev Ts, dest_matchT U) (mk_run msum)
   283   end;
   284 
   285 (* this is the pattern-matching compiler function *)
   286 fun compile_pats match_name eqs =
   287   let
   288     val ((names, arities), mats) =
   289       apfst ListPair.unzip (ListPair.unzip (map (match_eq match_name) eqs));
   290     val cname =
   291         case distinct (op =) names of
   292           [n] => n
   293         | _ => fixrec_err "all equations in block must define the same function";
   294     val arity =
   295         case distinct (op =) arities of
   296           [a] => a
   297         | _ => fixrec_err "all equations in block must have the same arity";
   298     val rhs = fatbar arity mats;
   299   in
   300     mk_trp (cname === rhs)
   301   end;
   302 
   303 (*************************************************************************)
   304 (********************** Proving associated theorems **********************)
   305 (*************************************************************************)
   306 
   307 structure FixrecSimpData = Generic_Data
   308 (
   309   type T = simpset;
   310   val empty =
   311     HOL_basic_ss
   312       addsimps simp_thms
   313       addsimps [@{thm beta_cfun}]
   314       addsimprocs [@{simproc cont_proc}];
   315   val extend = I;
   316   val merge = merge_ss;
   317 );
   318 
   319 fun fixrec_simp_tac ctxt =
   320   let
   321     val tab = FixrecUnfoldData.get (Context.Proof ctxt);
   322     val ss = Simplifier.context ctxt (FixrecSimpData.get (Context.Proof ctxt));
   323     fun concl t =
   324       if Logic.is_all t then concl (snd (Logic.dest_all t))
   325       else HOLogic.dest_Trueprop (Logic.strip_imp_concl t);
   326     fun tac (t, i) =
   327       let
   328         val (c, T) =
   329             (dest_Const o head_of o chead_of o fst o HOLogic.dest_eq o concl) t;
   330         val unfold_thm = the (Symtab.lookup tab c);
   331         val rule = unfold_thm RS @{thm ssubst_lhs};
   332       in
   333         CHANGED (rtac rule i THEN asm_simp_tac ss i)
   334       end
   335   in
   336     SUBGOAL (fn ti => the_default no_tac (try tac ti))
   337   end;
   338 
   339 val fixrec_simp_add : attribute =
   340   Thm.declaration_attribute
   341     (fn th => FixrecSimpData.map (fn ss => ss addsimps [th]));
   342 
   343 val fixrec_simp_del : attribute =
   344   Thm.declaration_attribute
   345     (fn th => FixrecSimpData.map (fn ss => ss delsimps [th]));
   346 
   347 (* proves a block of pattern matching equations as theorems, using unfold *)
   348 fun make_simps ctxt (unfold_thm, eqns : (Attrib.binding * term) list) =
   349   let
   350     val ss = Simplifier.context ctxt (FixrecSimpData.get (Context.Proof ctxt));
   351     val rule = unfold_thm RS @{thm ssubst_lhs};
   352     val tac = rtac rule 1 THEN asm_simp_tac ss 1;
   353     fun prove_term t = Goal.prove ctxt [] [] t (K tac);
   354     fun prove_eqn (bind, eqn_t) = (bind, prove_term eqn_t);
   355   in
   356     map prove_eqn eqns
   357   end;
   358 
   359 (*************************************************************************)
   360 (************************* Main fixrec function **************************)
   361 (*************************************************************************)
   362 
   363 local
   364 (* code adapted from HOL/Tools/primrec.ML *)
   365 
   366 fun gen_fixrec
   367   prep_spec
   368   (strict : bool)
   369   raw_fixes
   370   raw_spec
   371   (lthy : local_theory) =
   372   let
   373     val (fixes : ((binding * typ) * mixfix) list,
   374          spec : (Attrib.binding * term) list) =
   375           fst (prep_spec raw_fixes raw_spec lthy);
   376     val chead_of_spec =
   377       chead_of o fst o dest_eqs o Logic.strip_imp_concl o strip_alls o snd;
   378     fun name_of (Free (n, _)) = n
   379       | name_of t = fixrec_err ("unknown term");
   380     val all_names = map (name_of o chead_of_spec) spec;
   381     val names = distinct (op =) all_names;
   382     fun block_of_name n =
   383       map_filter
   384         (fn (m,eq) => if m = n then SOME eq else NONE)
   385         (all_names ~~ spec);
   386     val blocks = map block_of_name names;
   387 
   388     val matcher_tab = FixrecMatchData.get (ProofContext.theory_of lthy);
   389     fun match_name c =
   390       case Symtab.lookup matcher_tab c of SOME m => m
   391         | NONE => fixrec_err ("unknown pattern constructor: " ^ c);
   392 
   393     val matches = map (compile_pats match_name) (map (map snd) blocks);
   394     val spec' = map (pair Attrib.empty_binding) matches;
   395     val (lthy, cnames, fixdef_thms, unfold_thms) =
   396       add_fixdefs fixes spec' lthy;
   397   in
   398     if strict then let (* only prove simp rules if strict = true *)
   399       val simps : (Attrib.binding * thm) list list =
   400         map (make_simps lthy) (unfold_thms ~~ blocks);
   401       fun mk_bind n : Attrib.binding =
   402        (Binding.qualify true n (Binding.name "simps"),
   403          [Attrib.internal (K Simplifier.simp_add)]);
   404       val simps1 : (Attrib.binding * thm list) list =
   405         map (fn (n,xs) => (mk_bind n, map snd xs)) (names ~~ simps);
   406       val simps2 : (Attrib.binding * thm list) list =
   407         map (apsnd (fn thm => [thm])) (flat simps);
   408       val (_, lthy) = lthy
   409         |> fold_map Local_Theory.note (simps1 @ simps2);
   410     in
   411       lthy
   412     end
   413     else lthy
   414   end;
   415 
   416 in
   417 
   418 val add_fixrec = gen_fixrec Specification.check_spec;
   419 val add_fixrec_cmd = gen_fixrec Specification.read_spec;
   420 
   421 end; (* local *)
   422 
   423 (*************************************************************************)
   424 (******************************** Fixpat *********************************)
   425 (*************************************************************************)
   426 
   427 fun fix_pat thy t = 
   428   let
   429     val T = fastype_of t;
   430     val eq = mk_trp (HOLogic.eq_const T $ t $ Var (("x",0),T));
   431     val cname = case chead_of t of Const(c,_) => c | _ =>
   432               fixrec_err "function is not declared as constant in theory";
   433     val unfold_thm = PureThy.get_thm thy (cname^".unfold");
   434     val simp = Goal.prove_global thy [] [] eq
   435           (fn _ => EVERY [stac unfold_thm 1, simp_tac (global_simpset_of thy) 1]);
   436   in simp end;
   437 
   438 fun gen_add_fixpat prep_term prep_attrib ((name, srcs), strings) thy =
   439   let
   440     val _ = legacy_feature "Old 'fixpat' command -- use \"fixrec_simp\" method instead";
   441     val atts = map (prep_attrib thy) srcs;
   442     val ts = map (prep_term thy) strings;
   443     val simps = map (fix_pat thy) ts;
   444   in
   445     (snd o PureThy.add_thmss [((name, simps), atts)]) thy
   446   end;
   447 
   448 val add_fixpat = gen_add_fixpat Sign.cert_term (K I);
   449 val add_fixpat_cmd = gen_add_fixpat Syntax.read_term_global Attrib.attribute;
   450 
   451 
   452 (*************************************************************************)
   453 (******************************** Parsers ********************************)
   454 (*************************************************************************)
   455 
   456 val _ =
   457   Outer_Syntax.local_theory "fixrec" "define recursive functions (HOLCF)" Keyword.thy_decl
   458     ((Parse.opt_keyword "permissive" >> not) -- Parse.fixes -- Parse_Spec.where_alt_specs
   459       >> (fn ((strict, fixes), specs) => add_fixrec_cmd strict fixes specs));
   460 
   461 val _ =
   462   Outer_Syntax.command "fixpat" "define rewrites for fixrec functions" Keyword.thy_decl
   463     (Parse_Spec.specs >> (Toplevel.theory o add_fixpat_cmd));
   464 
   465 val setup =
   466   Attrib.setup @{binding fixrec_simp}
   467                      (Attrib.add_del fixrec_simp_add fixrec_simp_del)
   468                      "declaration of fixrec simp rule"
   469   #> Method.setup @{binding fixrec_simp}
   470                      (Scan.succeed (SIMPLE_METHOD' o fixrec_simp_tac))
   471                      "pattern prover for fixrec constants";
   472 
   473 end;