src/HOL/HOLCF/Tools/fixrec.ML
author wenzelm
Tue Mar 13 11:22:39 2012 +0100 (2012-03-13)
changeset 46895 de5cfda8b2de
parent 45897 65cef0298158
child 46909 3c73a121a387
permissions -rw-r--r--
tuned strip_alls;
     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   (case try Logic.dest_all t of
   257     SOME (_, u) => strip_alls u
   258   | NONE => t)
   259 
   260 fun compile_eq match_name eq =
   261   let
   262     val (lhs,rhs) = dest_eqs (Logic.strip_imp_concl (strip_alls eq))
   263   in
   264     compile_lhs match_name lhs (mk_succeed rhs) [] (taken_names eq)
   265   end
   266 
   267 (* this is the pattern-matching compiler function *)
   268 fun compile_eqs match_name eqs =
   269   let
   270     val (consts, matchers) =
   271       ListPair.unzip (map (compile_eq match_name) eqs)
   272     val const =
   273         case distinct (op =) consts of
   274           [n] => n
   275         | [] => fixrec_err "no defining equations for function"
   276         | _ => fixrec_err "all equations in block must define the same function"
   277     val vars =
   278         case distinct (op = o pairself length) (map fst matchers) of
   279           [vars] => vars
   280         | _ => fixrec_err "all equations in block must have the same arity"
   281     (* rename so all matchers use same free variables *)
   282     fun rename (vs, t) = Term.subst_free (filter_out (op =) (vs ~~ vars)) t
   283     val rhs = big_lambdas vars (mk_run (foldr1 mk_mplus (map rename matchers)))
   284   in
   285     mk_trp (const === rhs)
   286   end
   287 
   288 (*************************************************************************)
   289 (********************** Proving associated theorems **********************)
   290 (*************************************************************************)
   291 
   292 fun eta_tac i = CONVERSION Thm.eta_conversion i
   293 
   294 fun fixrec_simp_tac ctxt =
   295   let
   296     val tab = FixrecUnfoldData.get (Context.Proof ctxt)
   297     val ss = Simplifier.simpset_of ctxt
   298     val concl = HOLogic.dest_Trueprop o Logic.strip_imp_concl o strip_alls
   299     fun tac (t, i) =
   300       let
   301         val (c, _) =
   302             (dest_Const o head_of o chead_of o fst o HOLogic.dest_eq o concl) t
   303         val unfold_thm = the (Symtab.lookup tab c)
   304         val rule = unfold_thm RS @{thm ssubst_lhs}
   305       in
   306         CHANGED (rtac rule i THEN eta_tac i THEN asm_simp_tac ss i)
   307       end
   308   in
   309     SUBGOAL (fn ti => the_default no_tac (try tac ti))
   310   end
   311 
   312 (* proves a block of pattern matching equations as theorems, using unfold *)
   313 fun make_simps ctxt (unfold_thm, eqns : (Attrib.binding * term) list) =
   314   let
   315     val ss = Simplifier.simpset_of ctxt
   316     val rule = unfold_thm RS @{thm ssubst_lhs}
   317     val tac = rtac rule 1 THEN eta_tac 1 THEN asm_simp_tac ss 1
   318     fun prove_term t = Goal.prove ctxt [] [] t (K tac)
   319     fun prove_eqn (bind, eqn_t) = (bind, prove_term eqn_t)
   320   in
   321     map prove_eqn eqns
   322   end
   323 
   324 (*************************************************************************)
   325 (************************* Main fixrec function **************************)
   326 (*************************************************************************)
   327 
   328 local
   329 (* code adapted from HOL/Tools/Datatype/primrec.ML *)
   330 
   331 fun gen_fixrec
   332   prep_spec
   333   (raw_fixes : (binding * 'a option * mixfix) list)
   334   (raw_spec' : (bool * (Attrib.binding * 'b)) list)
   335   (lthy : local_theory) =
   336   let
   337     val (skips, raw_spec) = ListPair.unzip raw_spec'
   338     val (fixes : ((binding * typ) * mixfix) list,
   339          spec : (Attrib.binding * term) list) =
   340           fst (prep_spec raw_fixes raw_spec lthy)
   341     val names = map (Binding.name_of o fst o fst) fixes
   342     fun check_head name =
   343         member (op =) names name orelse
   344         fixrec_err ("Illegal equation head. Expected " ^ commas_quote names)
   345     val chead_of_spec =
   346       chead_of o fst o dest_eqs o Logic.strip_imp_concl o strip_alls o snd
   347     fun name_of (Free (n, _)) = tap check_head n
   348       | name_of _ = fixrec_err ("unknown term")
   349     val all_names = map (name_of o chead_of_spec) spec
   350     fun block_of_name n =
   351       map_filter
   352         (fn (m,eq) => if m = n then SOME eq else NONE)
   353         (all_names ~~ (spec ~~ skips))
   354     val blocks = map block_of_name names
   355 
   356     val matcher_tab = FixrecMatchData.get (Proof_Context.theory_of lthy)
   357     fun match_name c =
   358       case Symtab.lookup matcher_tab c of SOME m => m
   359         | NONE => fixrec_err ("unknown pattern constructor: " ^ c)
   360 
   361     val matches = map (compile_eqs match_name) (map (map (snd o fst)) blocks)
   362     val spec' = map (pair Attrib.empty_binding) matches
   363     val (lthy, _, _, unfold_thms) =
   364       add_fixdefs fixes spec' lthy
   365 
   366     val blocks' = map (map fst o filter_out snd) blocks
   367     val simps : (Attrib.binding * thm) list list =
   368       map (make_simps lthy) (unfold_thms ~~ blocks')
   369     fun mk_bind n : Attrib.binding =
   370      (Binding.qualify true n (Binding.name "simps"), @{attributes [simp]})
   371     val simps1 : (Attrib.binding * thm list) list =
   372       map (fn (n,xs) => (mk_bind n, map snd xs)) (names ~~ simps)
   373     val simps2 : (Attrib.binding * thm list) list =
   374       map (apsnd (fn thm => [thm])) (flat simps)
   375     val (_, lthy) = lthy
   376       |> fold_map Local_Theory.note (simps1 @ simps2)
   377   in
   378     lthy
   379   end
   380 
   381 in
   382 
   383 val add_fixrec = gen_fixrec Specification.check_spec
   384 val add_fixrec_cmd = gen_fixrec Specification.read_spec
   385 
   386 end (* local *)
   387 
   388 
   389 (*************************************************************************)
   390 (******************************** Parsers ********************************)
   391 (*************************************************************************)
   392 
   393 val opt_thm_name' : (bool * Attrib.binding) parser =
   394   Parse.$$$ "(" -- Parse.$$$ "unchecked" -- Parse.$$$ ")" >> K (true, Attrib.empty_binding)
   395     || Parse_Spec.opt_thm_name ":" >> pair false
   396 
   397 val spec' : (bool * (Attrib.binding * string)) parser =
   398   opt_thm_name' -- Parse.prop >> (fn ((a, b), c) => (a, (b, c)))
   399 
   400 val alt_specs' : (bool * (Attrib.binding * string)) list parser =
   401   let val unexpected = Scan.ahead (Parse.name || Parse.$$$ "[" || Parse.$$$ "(")
   402   in Parse.enum1 "|" (spec' --| Scan.option (unexpected -- Parse.!!! (Parse.$$$ "|"))) end
   403 
   404 val _ =
   405   Outer_Syntax.local_theory "fixrec" "define recursive functions (HOLCF)" Keyword.thy_decl
   406     (Parse.fixes -- (Parse.where_ |-- Parse.!!! alt_specs')
   407       >> (fn (fixes, specs) => add_fixrec_cmd fixes specs))
   408 
   409 val setup =
   410   Method.setup @{binding fixrec_simp}
   411     (Scan.succeed (SIMPLE_METHOD' o fixrec_simp_tac))
   412     "pattern prover for fixrec constants"
   413 
   414 end