src/HOL/Tools/function_package/fundef_package.ML
author krauss
Fri Jun 01 15:57:45 2007 +0200 (2007-06-01)
changeset 23189 4574ab8f3b21
parent 22846 fb79144af9a3
child 23203 a5026e73cfcf
permissions -rw-r--r--
simplified interfaces, some restructuring
     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 
    14                       -> FundefCommon.fundef_config
    15                       -> local_theory
    16                       -> Proof.state
    17 
    18     val add_fundef_i:  (string * typ option * mixfix) list
    19                        -> ((bstring * Attrib.src list) * (term * bool)) list
    20                        -> FundefCommon.fundef_config
    21                        -> local_theory
    22                        -> 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 
    46 (* Check for all sorts of errors in the input *)
    47 fun check_def ctxt fixes eqs =
    48     let
    49       val fnames = map (fst o fst) fixes
    50                                 
    51       fun check geq = 
    52           let
    53             fun input_error msg = cat_lines [msg, ProofContext.string_of_term ctxt geq]
    54                                   
    55             val fqgar as (fname, qs, gs, args, rhs) = split_def geq
    56                                  
    57             val _ = fname mem fnames 
    58                     orelse error (input_error ("Head symbol of left hand side must be " ^ plural "" "one out of " fnames 
    59                                                ^ commas_quote fnames))
    60                                             
    61             fun add_bvs t is = add_loose_bnos (t, 0, is)
    62             val rvs = (add_bvs rhs [] \\ fold add_bvs args [])
    63                         |> map (fst o nth (rev qs))
    64                       
    65             val _ = null rvs orelse error (input_error ("Variable" ^ plural " " "s " rvs ^ commas_quote rvs
    66                                                         ^ " occur" ^ plural "s" "" rvs ^ " on right hand side only:"))
    67                                     
    68             val _ = forall (forall_aterms (fn Free (n, _) => not (n mem fnames) | _ => true)) gs orelse
    69                     error (input_error "Recursive Calls not allowed in premises")
    70           in
    71             fqgar
    72           end
    73     in
    74       (mk_arities (map check eqs); ())
    75       handle ArgumentCount fname => 
    76              error ("Function " ^ quote fname ^ " has different numbers of arguments in different equations")
    77     end
    78 
    79 
    80 fun mk_catchall fixes arities =
    81     let
    82       fun mk_eqn ((fname, fT), _) =
    83           let 
    84             val n = the (Symtab.lookup arities fname)
    85             val (argTs, rT) = chop n (binder_types fT)
    86                                    |> apsnd (fn Ts => Ts ---> body_type fT) 
    87                               
    88             val qs = map Free (Name.invent_list [] "a" n ~~ argTs)
    89           in
    90             HOLogic.mk_eq(list_comb (Free (fname, fT), qs),
    91                           Const ("HOL.undefined", rT))
    92               |> HOLogic.mk_Trueprop
    93               |> fold_rev mk_forall qs
    94           end
    95     in
    96       map mk_eqn fixes
    97     end
    98 
    99 fun add_catchall fixes spec =
   100     let 
   101       val catchalls = mk_catchall fixes (mk_arities (map split_def (map (snd o snd) spec)))
   102     in
   103       spec @ map (pair ("",[]) o pair true) catchalls
   104     end
   105 
   106 fun burrow_snd f ps = (* ('a list -> 'b list) -> ('c * 'a) list -> ('c * 'b) list *)
   107     let val (xs, ys) = split_list ps
   108     in xs ~~ f ys end
   109 
   110 fun restore_spec_structure reps spec =
   111     (burrow_snd o burrow o K) reps spec
   112 
   113 fun add_simps fixes spec sort label moreatts simps lthy =
   114     let
   115       val fnames = map (fst o fst) fixes
   116 
   117       val (saved_spec_simps, lthy) =
   118         fold_map note_theorem (restore_spec_structure simps spec) lthy
   119       val saved_simps = flat (map snd saved_spec_simps)
   120 
   121       val simps_by_f = sort saved_simps
   122 
   123       fun add_for_f fname simps =
   124         note_theorem
   125           ((NameSpace.qualified fname label, Attrib.internal (K Simplifier.simp_add) :: moreatts),
   126             simps) #> snd
   127     in
   128       (saved_simps,
   129        fold2 add_for_f fnames simps_by_f lthy)
   130     end
   131 
   132 fun fundef_afterqed config fixes spec defname cont sort_cont [[proof]] lthy =
   133     let
   134       val FundefResult {fs, R, psimps, trsimps, subset_pinducts, simple_pinducts, termination, domintros, cases, ...} = 
   135           cont (Goal.close_result proof)
   136 
   137       val qualify = NameSpace.qualified defname
   138       val addsmps = add_simps fixes spec sort_cont
   139 
   140       val (((psimps', pinducts'), (_, [termination'])), lthy) =
   141           lthy
   142             |> addsmps "psimps" [] psimps
   143             ||> fold_option (snd oo addsmps "simps" []) trsimps
   144             ||>> note_theorem ((qualify "pinduct",
   145                                 [Attrib.internal (K (InductAttrib.induct_set ""))]), simple_pinducts)
   146             ||>> note_theorem ((qualify "termination", []), [termination])
   147             ||> (snd o note_theorem ((qualify "cases", []), [cases]))
   148             ||> fold_option (snd oo curry note_theorem (qualify "domintros", [])) domintros
   149 
   150       val cdata = FundefCtxData { add_simps=addsmps, psimps=psimps',
   151                                   pinducts=snd pinducts', termination=termination', fs=fs, R=R, defname=defname }
   152       val cdata' = cdata |> morph_fundef_data (LocalTheory.target_morphism lthy);  (* FIXME !? *)
   153     in
   154       lthy 
   155         |> LocalTheory.declaration (fn phi => add_fundef_data (morph_fundef_data phi cdata)) (* save in target *)
   156         |> Context.proof_map (add_fundef_data cdata') (* also save in local context *)
   157     end (* FIXME: Add cases for induct and cases thm *)
   158 
   159 
   160 
   161 fun prep_with_flags prep fixspec eqnss_flags global_flag lthy =
   162     let
   163       val flags = map (fn x => global_flag orelse (snd (snd x))) eqnss_flags
   164       val eqns = map (apsnd (single o fst)) eqnss_flags
   165 
   166       val ((fixes, _), ctxt') = prep fixspec [] lthy
   167 
   168       fun prep_eqn e = the_single (snd (fst (prep [] [e] ctxt')))
   169                          |> apsnd the_single
   170 
   171       val raw_spec = map prep_eqn eqns
   172                      |> map (apsnd (fn t => fold_rev (mk_forall o Free) (frees_in_term ctxt' t) t)) (* Add quantifiers *)
   173 
   174       val _ = check_def ctxt' fixes (map snd raw_spec)
   175 
   176       val spec = raw_spec
   177                      |> burrow_snd (fn ts => flags ~~ ts)
   178                      (*|> (if global_flag then add_catchall fixes else I) *) (* Completion: still disabled *)
   179                      |> burrow_snd (FundefSplit.split_some_equations ctxt')
   180 
   181     in
   182       ((fixes, spec), ctxt')
   183     end
   184 
   185 fun gen_add_fundef prep_spec fixspec eqnss_flags config lthy =
   186     let
   187       val FundefConfig {sequential, ...} = config
   188 
   189       val ((fixes, spec), ctxt') = prep_with_flags prep_spec fixspec eqnss_flags sequential lthy
   190 
   191       val defname = mk_defname fixes
   192 
   193       val t_eqns = spec |> map snd |> flat (* flatten external structure *)
   194 
   195       val ((goalstate, cont, sort_cont), lthy) =
   196           FundefMutual.prepare_fundef_mutual config defname fixes t_eqns lthy
   197 
   198       val afterqed = fundef_afterqed config fixes spec defname cont sort_cont
   199     in
   200       lthy
   201         |> Proof.theorem_i NONE afterqed [[(Logic.unprotect (concl_of goalstate), [])]]
   202         |> Proof.refine (Method.primitive_text (fn _ => goalstate)) |> Seq.hd
   203     end
   204 
   205 
   206 fun total_termination_afterqed data [[totality]] lthy =
   207     let
   208       val FundefCtxData { add_simps, psimps, pinducts, defname, ... } = data
   209 
   210       val totality = Goal.close_result totality
   211 
   212       val remove_domain_condition = full_simplify (HOL_basic_ss addsimps [totality, True_implies_equals])
   213 
   214       val tsimps = map remove_domain_condition psimps
   215       val tinduct = map remove_domain_condition pinducts
   216 
   217         (* FIXME: How to generate code from (possibly) local contexts*)
   218       val has_guards = exists ((fn (Const ("Trueprop", _) $ _) => false | _ => true) o prop_of) tsimps
   219       val allatts = if has_guards then [] else [Attrib.internal (K (RecfunCodegen.add NONE))]
   220 
   221       val qualify = NameSpace.qualified defname;
   222     in
   223       lthy
   224         |> add_simps "simps" allatts tsimps |> snd
   225         |> note_theorem ((qualify "induct", []), tinduct) |> snd
   226     end
   227 
   228 
   229 fun setup_termination_proof term_opt lthy =
   230     let
   231       val data = the (case term_opt of
   232                         SOME t => import_fundef_data (ProofContext.read_term lthy t) (Context.Proof lthy)
   233                       | NONE => import_last_fundef (Context.Proof lthy))
   234           handle Option.Option => raise ERROR ("Not a function: " ^ quote (the_default "" term_opt))
   235 
   236         val FundefCtxData {termination, R, ...} = data
   237         val domT = domain_type (fastype_of R)
   238         val goal = HOLogic.mk_Trueprop (HOLogic.mk_all ("x", domT, mk_acc domT R $ Free ("x", domT)))
   239     in
   240       lthy
   241         |> ProofContext.note_thmss_i "" [(("", [ContextRules.rule_del]), [([allI], [])])] |> snd
   242         |> ProofContext.note_thmss_i "" [(("", [ContextRules.intro_bang (SOME 1)]), [([allI], [])])] |> snd
   243         |> ProofContext.note_thmss_i ""
   244           [(("termination", [ContextRules.intro_bang (SOME 0)]),
   245             [([Goal.norm_result termination], [])])] |> snd
   246         |> Proof.theorem_i NONE (total_termination_afterqed data) [[(goal, [])]]
   247     end
   248 
   249 
   250 val add_fundef = gen_add_fundef Specification.read_specification
   251 val add_fundef_i = gen_add_fundef Specification.cert_specification
   252 
   253 
   254 
   255 (* congruence rules *)
   256 
   257 val cong_add = Thm.declaration_attribute (map_fundef_congs o Drule.add_rule o safe_mk_meta_eq);
   258 val cong_del = Thm.declaration_attribute (map_fundef_congs o Drule.del_rule o safe_mk_meta_eq);
   259 
   260 (* Datatype hook to declare datatype congs as "fundef_congs" *)
   261 
   262 
   263 fun add_case_cong n thy =
   264     Context.theory_map (map_fundef_congs (Drule.add_rule
   265                           (DatatypePackage.get_datatype thy n |> the
   266                            |> #case_cong
   267                            |> safe_mk_meta_eq)))
   268                        thy
   269 
   270 val case_cong_hook = fold add_case_cong
   271 
   272 val setup_case_cong_hook =
   273     DatatypeHooks.add case_cong_hook
   274     #> (fn thy => case_cong_hook (Symtab.keys (DatatypePackage.get_datatypes thy)) thy)
   275 
   276 (* setup *)
   277 
   278 val setup =
   279   Attrib.add_attributes
   280     [("fundef_cong", Attrib.add_del_args cong_add cong_del,
   281       "declaration of congruence rule for function definitions")]
   282   #> setup_case_cong_hook
   283   #> FundefRelation.setup
   284 
   285 val get_congs = FundefCommon.get_fundef_congs o Context.Theory
   286 
   287 
   288 
   289 (* outer syntax *)
   290 
   291 local structure P = OuterParse and K = OuterKeyword in
   292 
   293 val functionP =
   294   OuterSyntax.command "function" "define general recursive functions" K.thy_goal
   295   (fundef_parser default_config
   296      >> (fn ((config, fixes), statements) =>
   297             Toplevel.local_theory_to_proof (target_of config) (add_fundef fixes statements config)
   298             #> Toplevel.print));
   299 
   300 val terminationP =
   301   OuterSyntax.command "termination" "prove termination of a recursive function" K.thy_goal
   302   (P.opt_target -- Scan.option P.term
   303     >> (fn (target, name) =>
   304            Toplevel.print o
   305            Toplevel.local_theory_to_proof target (setup_termination_proof name)));
   306 
   307 val _ = OuterSyntax.add_parsers [functionP];
   308 val _ = OuterSyntax.add_parsers [terminationP];
   309 val _ = OuterSyntax.add_keywords ["sequential", "otherwise"];
   310 
   311 end;
   312 
   313 
   314 end