src/HOL/Tools/function_package/fundef_package.ML
author krauss
Wed Nov 08 09:08:54 2006 +0100 (2006-11-08)
changeset 21240 8e75fb38522c
parent 21237 b803f9870e97
child 21255 617fdb08abe9
permissions -rw-r--r--
Made "termination by lexicographic_order" the default for "fun" definitions.
     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 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 list) list list
    20                        -> bool
    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  =
    36 struct
    37 
    38 open FundefLib
    39 open FundefCommon
    40 
    41 (*fn (ctxt,s) => Variable.importT_terms (fst (ProofContext.read_termTs ctxt (K false) (K NONE) (K NONE) [] [s])) ctxt;*)
    42 
    43 fun burrow_snd f ps = (* ('a list -> 'b list) -> ('c * 'a) list -> ('c * 'b) list *)
    44     let val (xs, ys) = split_list ps
    45     in xs ~~ f ys end
    46 
    47 fun restore_spec_structure reps spec =
    48     (burrow o burrow_snd o burrow o K) reps spec
    49 
    50 fun add_simps label moreatts mutual_info fixes psimps spec lthy =
    51     let
    52       val fnames = map (fst o fst) fixes
    53       val psimps_by_f = FundefMutual.sort_by_function mutual_info fnames psimps
    54 
    55       fun add_for_f fname psimps =
    56           LocalTheory.note ((NameSpace.append fname label, Attrib.internal Simplifier.simp_add :: moreatts), psimps) #> snd
    57     in
    58       lthy
    59         |> fold_map (fold_map LocalTheory.note) (restore_spec_structure psimps spec) |> snd
    60         |> fold2 add_for_f fnames psimps_by_f
    61     end
    62 
    63 
    64 fun fundef_afterqed fixes spec mutual_info defname data [[result]] lthy =
    65     let
    66         val fundef_data = FundefMutual.mk_partial_rules_mutual lthy mutual_info data result
    67         val FundefMResult {psimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = fundef_data
    68         val qualify = NameSpace.append defname;
    69     in
    70       lthy
    71         |> add_simps "psimps" [] mutual_info fixes psimps spec
    72         |> LocalTheory.note ((qualify "domintros", []), domintros) |> snd
    73         |> LocalTheory.note ((qualify "termination", []), [termination]) |> snd
    74         |> LocalTheory.note ((qualify "cases", []), [cases]) |> snd
    75         |> LocalTheory.note ((qualify "pinduct", [Attrib.internal (InductAttrib.induct_set "")]), simple_pinducts) |> snd
    76         |> LocalTheory.declaration (add_fundef_data defname (fundef_data, mutual_info, (fixes,spec))) (* save in target *)
    77         |> Context.proof_map (add_fundef_data defname (fundef_data, mutual_info, (fixes,spec))) (* also save in local context *)
    78     end (* FIXME: Add cases for induct and cases thm *)
    79 
    80 
    81 
    82 fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
    83     let
    84       val eqnss = map (map (apsnd (map fst))) eqnss_flags
    85       val flags = map (map (map (fn (_, f) => global_flag orelse f) o snd)) eqnss_flags
    86 
    87       val ((fixes, _), ctxt') = prep fixspec [] lthy
    88       val spec = map (fn eqns => snd (fst (prep [] eqns ctxt'))) eqnss
    89                      |> map (map (apsnd (map (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)))) (* Add quantifiers *)
    90                      |> map2 (map2 (fn fs => fn (r, thms) => (r, fs ~~ thms))) flags
    91                      |> (burrow o burrow_snd o burrow)
    92                           (FundefSplit.split_some_equations lthy)
    93                      |> map (map (apsnd flat))
    94     in
    95       ((fixes, spec), ctxt')
    96     end
    97 
    98 
    99 fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
   100     let
   101       val FundefConfig {sequential, default, ...} = config
   102 
   103       val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
   104       val t_eqns = spec
   105                      |> flat |> map snd |> flat (* flatten external structure *)
   106 
   107       val ((mutual_info, name, prep_result as Prep {goal, goalI, ...}), lthy) =
   108           FundefMutual.prepare_fundef_mutual fixes t_eqns default lthy
   109 
   110       val afterqed = fundef_afterqed fixes spec mutual_info name prep_result
   111     in
   112       (name, lthy
   113          |> Proof.theorem_i PureThy.internalK NONE afterqed NONE ("", []) [(("", []), [(goal, [])])]
   114          |> Proof.refine (Method.primitive_text (fn _ => goalI)) |> Seq.hd)
   115     end
   116 
   117 
   118 fun total_termination_afterqed defname data [[totality]] lthy =
   119     let
   120         val (FundefMResult {psimps, simple_pinducts, ... }, mutual_info, (fixes, stmts)) = data
   121 
   122         val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   123 
   124         val tsimps = map remove_domain_condition psimps
   125         val tinduct = map remove_domain_condition simple_pinducts
   126 
   127         (* FIXME: How to generate code from (possibly) local contexts
   128         val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   129         val allatts = if has_guards then [] else [Attrib.internal (RecfunCodegen.add NONE)]
   130         *)
   131         val qualify = NameSpace.append defname;
   132     in
   133         lthy
   134           |> add_simps "simps" [] mutual_info fixes tsimps stmts
   135           |> LocalTheory.note ((qualify "induct", []), tinduct) |> snd
   136     end
   137 
   138 
   139 fun setup_termination_proof name_opt lthy =
   140     let
   141         val name = the_default (get_last_fundef (Context.Proof lthy)) name_opt
   142         val data = the (get_fundef_data name (Context.Proof lthy))
   143                    handle Option.Option => raise ERROR ("No such function definition: " ^ name)
   144 
   145         val (res as FundefMResult {termination, ...}, _, _) = data
   146         val goal = FundefTermination.mk_total_termination_goal data
   147     in
   148       lthy
   149         |> ProofContext.note_thmss_i [(("termination",
   150                                         [ContextRules.intro_query NONE]), [(ProofContext.standard lthy [termination], [])])] |> snd
   151         |> Proof.theorem_i PureThy.internalK NONE
   152                            (total_termination_afterqed name data) NONE ("", [])
   153                            [(("", []), [(goal, [])])]
   154     end
   155 
   156 
   157 val add_fundef = gen_add_fundef Specification.read_specification
   158 val add_fundef_i = gen_add_fundef Specification.cert_specification
   159 
   160 
   161 
   162 (* congruence rules *)
   163 
   164 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   165 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   166 
   167 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   168 
   169 
   170 fun add_case_cong n thy = 
   171     Context.theory_map (map_fundef_congs (Drule.add_rule 
   172                           (DatatypePackage.get_datatype thy n |> the
   173                            |> #case_cong
   174                            |> safe_mk_meta_eq))) 
   175                        thy
   176 
   177 val case_cong_hook = fold add_case_cong
   178 
   179 val setup_case_cong_hook = 
   180     DatatypeHooks.add case_cong_hook
   181     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   182 
   183 (* setup *)
   184 
   185 val setup = 
   186     FundefData.init 
   187       #> FundefCongs.init
   188       #>  Attrib.add_attributes
   189             [("fundef_cong", Attrib.add_del_args cong_add cong_del, "declaration of congruence rule for function definitions")]
   190       #> setup_case_cong_hook
   191 
   192 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   193 
   194 
   195 
   196 (* outer syntax *)
   197 
   198 local structure P = OuterParse and K = OuterKeyword in
   199 
   200 
   201 
   202 fun or_list1 s = P.enum1 "|" s
   203 
   204 val opt_sequential = Scan.optional ((P.$$$ "(" |-- P.$$$ "sequential" --| P.$$$ ")") >> K true) false
   205 
   206 val otherwise = P.$$$ "(" |-- P.$$$ "otherwise" --| P.$$$ ")"
   207 val statement_ow = P.and_list1 (P.opt_thm_name ":" -- Scan.repeat1 (P.prop -- Scan.optional (otherwise >> K true) false))
   208 val statements_ow = or_list1 statement_ow
   209 
   210 
   211 val functionP =
   212   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   213   ((config_parser default_config -- P.opt_locale_target -- P.fixes --| P.$$$ "where" -- statements_ow)
   214      >> (fn (((config, target), fixes), statements) =>
   215             Toplevel.local_theory_to_proof target (add_fundef fixes statements config #> snd)
   216             #> Toplevel.print));
   217 
   218 
   219 
   220 val terminationP =
   221   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   222   (P.opt_locale_target -- Scan.option P.name
   223     >> (fn (target, name) =>
   224            Toplevel.print o
   225            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   226 
   227 
   228 val _ = OuterSyntax.add_parsers [functionP];
   229 val _ = OuterSyntax.add_parsers [terminationP];
   230 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   231 
   232 end;
   233 
   234 
   235 end