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