src/HOL/Tools/function_package/fundef_package.ML
author krauss
Tue Jan 23 20:29:03 2007 +0100 (2007-01-23)
changeset 22170 5682eeaefaf4
parent 22166 0a50d4db234a
child 22325 be61bd159a99
permissions -rw-r--r--
fixes smlnj-related problem, updated signature
     1 (*  Title:      HOL/Tools/function_package/fundef_package.ML
     2     ID:         $Id$
     3     Author:     Alexander Krauss, TU Muenchen
     4 
     5 A package for general recursive function definitions.
     6 Isar commands.
     7 
     8 *)
     9 
    10 signature FUNDEF_PACKAGE =
    11 sig
    12     val add_fundef :  (string * string option * mixfix) list
    13                       -> ((bstring * Attrib.src list) * (string * bool) list) list list
    14                       -> FundefCommon.fundef_config
    15                       -> local_theory
    16                       -> string * Proof.state
    17 
    18     val add_fundef_i:  (string * typ option * mixfix) list
    19                        -> ((bstring * Attrib.src list) * (term * bool) list) list list
    20                        -> FundefCommon.fundef_config
    21                        -> local_theory
    22                        -> string * Proof.state
    23 
    24     val setup_termination_proof : string option -> local_theory -> Proof.state
    25 
    26     val cong_add: attribute
    27     val cong_del: attribute
    28 
    29     val setup : theory -> theory
    30     val setup_case_cong_hook : theory -> theory
    31     val get_congs : theory -> thm list
    32 end
    33 
    34 
    35 structure FundefPackage : FUNDEF_PACKAGE =
    36 struct
    37 
    38 open FundefLib
    39 open FundefCommon
    40 
    41 val note_theorem = LocalTheory.note Thm.theoremK
    42 
    43 fun mk_defname fixes = fixes |> map (fst o fst) |> space_implode "_" 
    44 
    45 fun burrow_snd f ps = (* ('a list -> 'b list) -> ('c * 'a) list -> ('c * 'b) list *)
    46     let val (xs, ys) = split_list ps
    47     in xs ~~ f ys end
    48 
    49 fun restore_spec_structure reps spec =
    50     (burrow o burrow_snd o burrow o K) reps spec
    51 
    52 fun add_simps fixes spec sort label moreatts simps lthy =
    53     let
    54       val fnames = map (fst o fst) fixes
    55 
    56       val (saved_spec_simps, lthy) =
    57         fold_map (fold_map note_theorem) (restore_spec_structure simps spec) lthy
    58       val saved_simps = flat (map snd (flat saved_spec_simps))
    59 
    60       val simps_by_f = sort saved_simps
    61 
    62       fun add_for_f fname simps =
    63         note_theorem
    64           ((NameSpace.qualified fname label, Attrib.internal (K Simplifier.simp_add) :: moreatts),
    65             simps) #> snd
    66     in
    67       (saved_simps,
    68        fold2 add_for_f fnames simps_by_f lthy)
    69     end
    70 
    71 
    72 fun fundef_afterqed config fixes spec defname cont sort_cont [[proof]] lthy =
    73     let
    74       val FundefResult {f, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
    75           cont (Goal.close_result proof)
    76 
    77       val qualify = NameSpace.qualified defname
    78       val addsmps = add_simps fixes spec sort_cont
    79 
    80       val (((psimps', pinducts'), (_, [termination'])), lthy) =
    81           lthy
    82             |> addsmps "psimps" [] psimps
    83             ||> fold_option (snd oo addsmps "simps" []) trsimps
    84             ||>> note_theorem ((qualify "pinduct",
    85                                 [Attrib.internal (K (InductAttrib.induct_set ""))]), simple_pinducts)
    86             ||>> note_theorem ((qualify "termination", []), [termination])
    87             ||> (snd o note_theorem ((qualify "cases", []), [cases]))
    88             ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
    89 
    90       val cdata = FundefCtxData { add_simps=addsmps, psimps=psimps',
    91                                   pinducts=snd pinducts', termination=termination', f=f, R=R }
    92     in
    93       lthy  (* FIXME proper handling of morphism *)
    94         |> LocalTheory.declaration (fn phi => add_fundef_data defname cdata) (* save in target *)
    95         |> Context.proof_map (add_fundef_data defname cdata) (* also save in local context *)
    96     end (* FIXME: Add cases for induct and cases thm *)
    97 
    98 
    99 
   100 fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
   101     let
   102       val eqnss = map (map (apsnd (map fst))) eqnss_flags
   103       val flags = map (map (map (fn (_, f) => global_flag orelse f) o snd)) eqnss_flags
   104 
   105       val ((fixes, _), ctxt') = prep fixspec [] lthy
   106       val spec = map (fn eqns => snd (fst (prep [] eqns ctxt'))) eqnss
   107                      |> map (map (apsnd (map (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)))) (* Add quantifiers *)
   108                      |> map2 (map2 (fn fs => fn (r, thms) => (r, fs ~~ thms))) flags
   109                      |> (burrow o burrow_snd o burrow)
   110                           (FundefSplit.split_some_equations lthy)
   111                      |> map (map (apsnd flat))
   112     in
   113       ((fixes, spec), ctxt')
   114     end
   115 
   116 
   117 fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
   118     let
   119       val FundefConfig {sequential, default, tailrec, ...} = config
   120 
   121       val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
   122 
   123       val defname = mk_defname fixes
   124 
   125       val t_eqns = spec
   126                      |> flat |> map snd |> flat (* flatten external structure *)
   127 
   128       val ((goalstate, cont, sort_cont), lthy) =
   129           FundefMutual.prepare_fundef_mutual config defname fixes t_eqns default lthy
   130 
   131       val afterqed = fundef_afterqed config fixes spec defname cont sort_cont
   132     in
   133       (defname, lthy
   134          |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
   135          |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd)
   136     end
   137 
   138 
   139 fun total_termination_afterqed defname data [[totality]] lthy =
   140     let
   141       val FundefCtxData { add_simps, psimps, pinducts, ... } = data
   142 
   143       val totality = Goal.close_result totality
   144 
   145       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   146 
   147       val tsimps = map remove_domain_condition psimps
   148       val tinduct = map remove_domain_condition pinducts
   149 
   150         (* FIXME: How to generate code from (possibly) local contexts*)
   151       val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   152       val allatts = if has_guards then [] else [Attrib.internal (K (RecfunCodegen.add NONE))]
   153 
   154       val qualify = NameSpace.qualified defname;
   155     in
   156       lthy
   157         |> add_simps "simps" allatts tsimps |> snd
   158         |> note_theorem ((qualify "induct", []), tinduct) |> snd
   159     end
   160 
   161 
   162 fun setup_termination_proof name_opt lthy =
   163     let
   164         val defname = the_default (get_last_fundef (Context.Proof lthy)) name_opt
   165         val data = the (get_fundef_data defname (Context.Proof lthy))
   166                    handle Option.Option => raise ERROR ("No such function definition: " ^ defname)
   167 
   168         val FundefCtxData {termination, R, ...} = data
   169         val goal = FundefTermination.mk_total_termination_goal R
   170     in
   171       lthy
   172         |> ProofContext.note_thmss_i ""
   173           [(("termination", [ContextRules.intro_query NONE]),
   174             [([Goal.norm_result termination], [])])] |> snd
   175         |> set_termination_rule termination
   176         |> Proof.theorem_i NONE (total_termination_afterqed defname data) [[(goal, [])]]
   177     end
   178 
   179 
   180 val add_fundef = gen_add_fundef Specification.read_specification
   181 val add_fundef_i = gen_add_fundef Specification.cert_specification
   182 
   183 
   184 
   185 (* congruence rules *)
   186 
   187 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   188 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   189 
   190 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   191 
   192 
   193 fun add_case_cong n thy =
   194     Context.theory_map (map_fundef_congs (Drule.add_rule
   195                           (DatatypePackage.get_datatype thy n |> the
   196                            |> #case_cong
   197                            |> safe_mk_meta_eq)))
   198                        thy
   199 
   200 val case_cong_hook = fold add_case_cong
   201 
   202 val setup_case_cong_hook =
   203     DatatypeHooks.add case_cong_hook
   204     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   205 
   206 (* setup *)
   207 
   208 val setup =
   209     FundefData.init
   210       #> FundefCongs.init
   211       #> TerminationRule.init
   212       #>  Attrib.add_attributes
   213             [("fundef_cong", Attrib.add_del_args cong_add cong_del, "declaration of congruence rule for function definitions")]
   214       #> setup_case_cong_hook
   215       #> FundefRelation.setup
   216 
   217 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   218 
   219 
   220 
   221 (* outer syntax *)
   222 
   223 local structure P = OuterParse and K = OuterKeyword in
   224 
   225 
   226 
   227 fun or_list1 s = P.enum1 "|" s
   228 
   229 val opt_sequential = Scan.optional ((P.$$$ "(" |-- P.$$$ "sequential" --| P.$$$ ")") >> K true) false
   230 
   231 val otherwise = P.$$$ "(" |-- P.$$$ "otherwise" --| P.$$$ ")"
   232 val statement_ow = P.and_list1 (SpecParse.opt_thm_name ":" -- Scan.repeat1 (P.prop -- Scan.optional (otherwise >> K true) false))
   233 val statements_ow = or_list1 statement_ow
   234 
   235 
   236 val functionP =
   237   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   238   ((config_parser default_config -- P.opt_target -- P.fixes --| P.$$$ "where" -- statements_ow)
   239      >> (fn (((config, target), fixes), statements) =>
   240             Toplevel.local_theory_to_proof target (add_fundef fixes statements config #> snd)
   241             #> Toplevel.print));
   242 
   243 
   244 
   245 val terminationP =
   246   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   247   (P.opt_target -- Scan.option P.name
   248     >> (fn (target, name) =>
   249            Toplevel.print o
   250            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   251 
   252 
   253 val _ = OuterSyntax.add_parsers [functionP];
   254 val _ = OuterSyntax.add_parsers [terminationP];
   255 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   256 
   257 end;
   258 
   259 
   260 end