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