src/HOL/Tools/function_package/fundef_package.ML
author krauss
Sat Jun 02 15:28:38 2007 +0200 (2007-06-02)
changeset 23203 a5026e73cfcf
parent 23189 4574ab8f3b21
child 23473 997bca36d4fe
permissions -rw-r--r--
"function (sequential)" and "fun" now handle incomplete patterns silently by adding "undefined" cases.
more cleanup.
     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 
    14                       -> FundefCommon.fundef_config
    15                       -> bool list
    16                       -> local_theory
    17                       -> Proof.state
    18 
    19     val add_fundef_i:  (string * typ option * mixfix) list
    20                        -> ((bstring * Attrib.src list) * term) list
    21                        -> FundefCommon.fundef_config
    22                        -> bool list
    23                        -> local_theory
    24                        -> Proof.state
    25 
    26     val setup_termination_proof : string option -> local_theory -> Proof.state
    27 
    28     val cong_add: attribute
    29     val cong_del: attribute
    30 
    31     val setup : theory -> theory
    32     val setup_case_cong_hook : theory -> theory
    33     val get_congs : theory -> thm list
    34 end
    35 
    36 
    37 structure FundefPackage : FUNDEF_PACKAGE =
    38 struct
    39 
    40 open FundefLib
    41 open FundefCommon
    42 
    43 val note_theorem = LocalTheory.note Thm.theoremK
    44 
    45 fun mk_defname fixes = fixes |> map (fst o fst) |> space_implode "_" 
    46 
    47 fun add_simps fixes post sort label moreatts simps lthy =
    48     let
    49       val fnames = map (fst o fst) fixes
    50 
    51       val (saved_spec_simps, lthy) =
    52         fold_map note_theorem (post simps) lthy
    53       val saved_simps = flat (map snd saved_spec_simps)
    54 
    55       val simps_by_f = sort saved_simps
    56 
    57       fun add_for_f fname simps =
    58         note_theorem
    59           ((NameSpace.qualified fname label, Attrib.internal (K Simplifier.simp_add) :: moreatts),
    60             simps) #> snd
    61     in
    62       (saved_simps,
    63        fold2 add_for_f fnames simps_by_f lthy)
    64     end
    65 
    66 fun fundef_afterqed config fixes post defname cont sort_cont [[proof]] lthy =
    67     let
    68       val FundefResult {fs, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
    69           cont (Goal.close_result proof)
    70 
    71       val qualify = NameSpace.qualified defname
    72       val addsmps = add_simps fixes post sort_cont
    73 
    74       val (((psimps', pinducts'), (_, [termination'])), lthy) =
    75           lthy
    76             |> addsmps "psimps" [] psimps
    77             ||> fold_option (snd oo addsmps "simps" []) trsimps
    78             ||>> note_theorem ((qualify "pinduct",
    79                                 [Attrib.internal (K (InductAttrib.induct_set ""))]), simple_pinducts)
    80             ||>> note_theorem ((qualify "termination", []), [termination])
    81             ||> (snd o note_theorem ((qualify "cases", []), [cases]))
    82             ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
    83 
    84       val cdata = FundefCtxData { add_simps=addsmps, psimps=psimps',
    85                                   pinducts=snd pinducts', termination=termination', fs=fs, R=R, defname=defname }
    86       val cdata' = cdata |> morph_fundef_data (LocalTheory.target_morphism lthy);  (* FIXME !? *)
    87     in
    88       lthy 
    89         |> LocalTheory.declaration (fn phi => add_fundef_data (morph_fundef_data phi cdata)) (* save in target *)
    90         |> Context.proof_map (add_fundef_data cdata') (* also save in local context *)
    91     end (* FIXME: Add cases for induct and cases thm *)
    92 
    93 
    94 fun prepare_spec prep fixspec eqnss lthy = (* FIXME: obsolete when "read_specification" etc. is there *)
    95     let
    96       val eqns = map (apsnd single) eqnss
    97 
    98       val ((fixes, _), ctxt') = prep fixspec [] lthy             
    99       fun prep_eqn e = the_single (snd (fst (prep [] [e] ctxt')))
   100 
   101       val spec = map prep_eqn eqns
   102                  |> map (apsnd (map (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t))) (* Add quantifiers *)
   103     in
   104       ((fixes, spec), ctxt')
   105     end
   106 
   107 fun gen_add_fundef prep fixspec eqnss config flags lthy =
   108     let
   109       val ((fixes, spec), ctxt') = prepare_spec prep fixspec eqnss lthy
   110       val (eqs, post) = FundefCommon.get_preproc lthy config flags ctxt' fixes spec
   111 
   112       val defname = mk_defname fixes
   113 
   114       val ((goalstate, cont, sort_cont), lthy) =
   115           FundefMutual.prepare_fundef_mutual config defname fixes eqs lthy
   116 
   117       val afterqed = fundef_afterqed config fixes post defname cont sort_cont
   118     in
   119       lthy
   120         |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
   121         |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd
   122     end
   123 
   124 fun total_termination_afterqed data [[totality]] lthy =
   125     let
   126       val FundefCtxData { add_simps, psimps, pinducts, defname, ... } = data
   127 
   128       val totality = Goal.close_result totality
   129 
   130       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   131 
   132       val tsimps = map remove_domain_condition psimps
   133       val tinduct = map remove_domain_condition pinducts
   134 
   135       val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   136       val allatts = if has_guards then [] else [Attrib.internal (K (RecfunCodegen.add NONE))]
   137 
   138       val qualify = NameSpace.qualified defname;
   139     in
   140       lthy
   141         |> add_simps "simps" allatts tsimps |> snd
   142         |> note_theorem ((qualify "induct", []), tinduct) |> snd
   143     end
   144 
   145 
   146 fun setup_termination_proof term_opt lthy =
   147     let
   148       val data = the (case term_opt of
   149                         SOME t => import_fundef_data (ProofContext.read_term lthy t) (Context.Proof lthy)
   150                       | NONE => import_last_fundef (Context.Proof lthy))
   151           handle Option.Option => raise ERROR ("Not a function: " ^ quote (the_default "" term_opt))
   152 
   153         val FundefCtxData {termination, R, ...} = data
   154         val domT = domain_type (fastype_of R)
   155         val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
   156     in
   157       lthy
   158         |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
   159         |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
   160         |> ProofContext.note_thmss_i ""
   161           [(("termination", [ContextRules.intro_bang (SOME 0)]),
   162             [([Goal.norm_result termination], [])])] |> snd
   163         |> Proof.theorem_i NONE (total_termination_afterqed data) [[(goal, [])]]
   164     end
   165 
   166 
   167 val add_fundef = gen_add_fundef Specification.read_specification
   168 val add_fundef_i = gen_add_fundef Specification.cert_specification
   169 
   170 
   171 
   172 (* congruence rules *)
   173 
   174 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   175 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   176 
   177 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   178 
   179 
   180 fun add_case_cong n thy =
   181     Context.theory_map (map_fundef_congs (Drule.add_rule
   182                           (DatatypePackage.get_datatype thy n |> the
   183                            |> #case_cong
   184                            |> safe_mk_meta_eq)))
   185                        thy
   186 
   187 val case_cong_hook = fold add_case_cong
   188 
   189 val setup_case_cong_hook =
   190     DatatypeHooks.add case_cong_hook
   191     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   192 
   193 (* setup *)
   194 
   195 val setup =
   196   Attrib.add_attributes
   197     [("fundef_cong", Attrib.add_del_args cong_add cong_del,
   198       "declaration of congruence rule for function definitions")]
   199   #> setup_case_cong_hook
   200   #> FundefRelation.setup
   201 
   202 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   203 
   204 
   205 
   206 (* outer syntax *)
   207 
   208 local structure P = OuterParse and K = OuterKeyword in
   209 
   210 val functionP =
   211   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   212   (fundef_parser default_config
   213      >> (fn ((config, fixes), (flags, statements)) =>
   214             Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config flags)
   215             #> Toplevel.print));
   216 
   217 val terminationP =
   218   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   219   (P.opt_target -- Scan.option P.term
   220     >> (fn (target, name) =>
   221            Toplevel.print o
   222            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   223 
   224 val _ = OuterSyntax.add_parsers [functionP];
   225 val _ = OuterSyntax.add_parsers [terminationP];
   226 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   227 
   228 end;
   229 
   230 
   231 end