src/ZF/Tools/datatype_package.ML
author wenzelm
Sat Jan 21 23:02:14 2006 +0100 (2006-01-21)
changeset 18728 6790126ab5f6
parent 18690 16a64bdc5485
child 20046 9c8909fc5865
permissions -rw-r--r--
simplified type attribute;
     1 (*  Title:      ZF/Tools/datatype_package.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1994  University of Cambridge
     5 
     6 Datatype/Codatatype Definitions
     7 
     8 The functor will be instantiated for normal sums/products (datatype defs)
     9                          and non-standard sums/products (codatatype defs)
    10 
    11 Sums are used only for mutual recursion;
    12 Products are used only to derive "streamlined" induction rules for relations
    13 *)
    14 
    15 type datatype_result =
    16    {con_defs   : thm list,             (*definitions made in thy*)
    17     case_eqns  : thm list,             (*equations for case operator*)
    18     recursor_eqns : thm list,          (*equations for the recursor*)
    19     free_iffs  : thm list,             (*freeness rewrite rules*)
    20     free_SEs   : thm list,             (*freeness destruct rules*)
    21     mk_free    : string -> thm};       (*function to make freeness theorems*)
    22 
    23 signature DATATYPE_ARG =
    24 sig
    25   val intrs : thm list
    26   val elims : thm list
    27 end;
    28 
    29 signature DATATYPE_PACKAGE =
    30 sig
    31   (*Insert definitions for the recursive sets, which
    32      must *already* be declared as constants in parent theory!*)
    33   val add_datatype_i: term * term list -> Ind_Syntax.constructor_spec list list ->
    34     thm list * thm list * thm list -> theory -> theory * inductive_result * datatype_result
    35   val add_datatype: string * string list -> (string * string list * mixfix) list list ->
    36     (thmref * Attrib.src list) list * (thmref * Attrib.src list) list *
    37     (thmref * Attrib.src list) list -> theory -> theory * inductive_result * datatype_result
    38 end;
    39 
    40 functor Add_datatype_def_Fun
    41  (structure Fp: FP and Pr : PR and CP: CARTPROD and Su : SU
    42   and Ind_Package : INDUCTIVE_PACKAGE
    43   and Datatype_Arg : DATATYPE_ARG
    44   val coind : bool): DATATYPE_PACKAGE =
    45 struct
    46 
    47 (*con_ty_lists specifies the constructors in the form (name, prems, mixfix) *)
    48 
    49 fun add_datatype_i (dom_sum, rec_tms) con_ty_lists (monos, type_intrs, type_elims) thy =
    50  let
    51   val dummy = (*has essential ancestors?*)
    52     Theory.requires thy "Datatype" "(co)datatype definitions";
    53 
    54   val rec_hds = map head_of rec_tms;
    55 
    56   val dummy = assert_all is_Const rec_hds
    57           (fn t => "Datatype set not previously declared as constant: " ^
    58                    Sign.string_of_term (sign_of thy) t);
    59 
    60   val rec_names = map (#1 o dest_Const) rec_hds
    61   val rec_base_names = map Sign.base_name rec_names
    62   val big_rec_base_name = space_implode "_" rec_base_names
    63 
    64   val thy_path = thy |> Theory.add_path big_rec_base_name
    65   val sign = sign_of thy_path
    66 
    67   val big_rec_name = Sign.intern_const sign big_rec_base_name;
    68 
    69   val intr_tms = Ind_Syntax.mk_all_intr_tms sign (rec_tms, con_ty_lists);
    70 
    71   val dummy =
    72     writeln ((if coind then "Codatatype" else "Datatype") ^ " definition " ^ quote big_rec_name);
    73 
    74   val case_varname = "f";                (*name for case variables*)
    75 
    76   (** Define the constructors **)
    77 
    78   (*The empty tuple is 0*)
    79   fun mk_tuple [] = Const("0",iT)
    80     | mk_tuple args = foldr1 (fn (t1, t2) => Pr.pair $ t1 $ t2) args;
    81 
    82   fun mk_inject n k u = access_bal (fn t => Su.inl $ t, fn t => Su.inr $ t, u) n k;
    83 
    84   val npart = length rec_names;  (*number of mutually recursive parts*)
    85 
    86 
    87   val full_name = Sign.full_name sign;
    88 
    89   (*Make constructor definition;
    90     kpart is the number of this mutually recursive part*)
    91   fun mk_con_defs (kpart, con_ty_list) =
    92     let val ncon = length con_ty_list    (*number of constructors*)
    93         fun mk_def (((id,T,syn), name, args, prems), kcon) =
    94               (*kcon is index of constructor*)
    95             Logic.mk_defpair (list_comb (Const (full_name name, T), args),
    96                         mk_inject npart kpart
    97                         (mk_inject ncon kcon (mk_tuple args)))
    98     in  ListPair.map mk_def (con_ty_list, 1 upto ncon)  end;
    99 
   100 
   101   (*** Define the case operator ***)
   102 
   103   (*Combine split terms using case; yields the case operator for one part*)
   104   fun call_case case_list =
   105     let fun call_f (free,[]) = Abs("null", iT, free)
   106           | call_f (free,args) =
   107                 CP.ap_split (foldr1 CP.mk_prod (map (#2 o dest_Free) args))
   108                             Ind_Syntax.iT
   109                             free
   110     in  fold_bal (fn (t1, t2) => Su.elim $ t1 $ t2) (map call_f case_list)  end;
   111 
   112   (** Generating function variables for the case definition
   113       Non-identifiers (e.g. infixes) get a name of the form f_op_nnn. **)
   114 
   115   (*The function variable for a single constructor*)
   116   fun add_case (((_, T, _), name, args, _), (opno, cases)) =
   117     if Syntax.is_identifier name then
   118       (opno, (Free (case_varname ^ "_" ^ name, T), args) :: cases)
   119     else
   120       (opno + 1, (Free (case_varname ^ "_op_" ^ string_of_int opno, T), args)
   121        :: cases);
   122 
   123   (*Treatment of a list of constructors, for one part
   124     Result adds a list of terms, each a function variable with arguments*)
   125   fun add_case_list (con_ty_list, (opno, case_lists)) =
   126     let val (opno', case_list) = foldr add_case (opno, []) con_ty_list
   127     in (opno', case_list :: case_lists) end;
   128 
   129   (*Treatment of all parts*)
   130   val (_, case_lists) = foldr add_case_list (1,[]) con_ty_lists;
   131 
   132   (*extract the types of all the variables*)
   133   val case_typ = List.concat (map (map (#2 o #1)) con_ty_lists) ---> (iT-->iT);
   134 
   135   val case_base_name = big_rec_base_name ^ "_case";
   136   val case_name = full_name case_base_name;
   137 
   138   (*The list of all the function variables*)
   139   val case_args = List.concat (map (map #1) case_lists);
   140 
   141   val case_const = Const (case_name, case_typ);
   142   val case_tm = list_comb (case_const, case_args);
   143 
   144   val case_def = Logic.mk_defpair
   145            (case_tm, fold_bal (fn (t1, t2) => Su.elim $ t1 $ t2) (map call_case case_lists));
   146 
   147 
   148   (** Generating function variables for the recursor definition
   149       Non-identifiers (e.g. infixes) get a name of the form f_op_nnn. **)
   150 
   151   (*a recursive call for x is the application rec`x  *)
   152   val rec_call = Ind_Syntax.apply_const $ Free ("rec", iT);
   153 
   154   (*look back down the "case args" (which have been reversed) to
   155     determine the de Bruijn index*)
   156   fun make_rec_call ([], _) arg = error
   157           "Internal error in datatype (variable name mismatch)"
   158     | make_rec_call (a::args, i) arg =
   159            if a = arg then rec_call $ Bound i
   160            else make_rec_call (args, i+1) arg;
   161 
   162   (*creates one case of the "X_case" definition of the recursor*)
   163   fun call_recursor ((case_var, case_args), (recursor_var, recursor_args)) =
   164       let fun add_abs (Free(a,T), u) = Abs(a,T,u)
   165           val ncase_args = length case_args
   166           val bound_args = map Bound ((ncase_args - 1) downto 0)
   167           val rec_args = map (make_rec_call (rev case_args,0))
   168                          (List.drop(recursor_args, ncase_args))
   169       in
   170           foldr add_abs
   171             (list_comb (recursor_var,
   172                         bound_args @ rec_args)) case_args
   173       end
   174 
   175   (*Find each recursive argument and add a recursive call for it*)
   176   fun rec_args [] = []
   177     | rec_args ((Const("op :",_)$arg$X)::prems) =
   178        (case head_of X of
   179             Const(a,_) => (*recursive occurrence?*)
   180                           if a mem_string rec_names
   181                               then arg :: rec_args prems
   182                           else rec_args prems
   183           | _ => rec_args prems)
   184     | rec_args (_::prems) = rec_args prems;
   185 
   186   (*Add an argument position for each occurrence of a recursive set.
   187     Strictly speaking, the recursive arguments are the LAST of the function
   188     variable, but they all have type "i" anyway*)
   189   fun add_rec_args args' T = (map (fn _ => iT) args') ---> T
   190 
   191   (*Plug in the function variable type needed for the recursor
   192     as well as the new arguments (recursive calls)*)
   193   fun rec_ty_elem ((id, T, syn), name, args, prems) =
   194       let val args' = rec_args prems
   195       in ((id, add_rec_args args' T, syn),
   196           name, args @ args', prems)
   197       end;
   198 
   199   val rec_ty_lists = (map (map rec_ty_elem) con_ty_lists);
   200 
   201   (*Treatment of all parts*)
   202   val (_, recursor_lists) = foldr add_case_list (1,[]) rec_ty_lists;
   203 
   204   (*extract the types of all the variables*)
   205   val recursor_typ = List.concat (map (map (#2 o #1)) rec_ty_lists)
   206                          ---> (iT-->iT);
   207 
   208   val recursor_base_name = big_rec_base_name ^ "_rec";
   209   val recursor_name = full_name recursor_base_name;
   210 
   211   (*The list of all the function variables*)
   212   val recursor_args = List.concat (map (map #1) recursor_lists);
   213 
   214   val recursor_tm =
   215     list_comb (Const (recursor_name, recursor_typ), recursor_args);
   216 
   217   val recursor_cases = map call_recursor
   218                          (List.concat case_lists ~~ List.concat recursor_lists)
   219 
   220   val recursor_def =
   221       Logic.mk_defpair
   222         (recursor_tm,
   223          Ind_Syntax.Vrecursor_const $
   224            absfree ("rec", iT, list_comb (case_const, recursor_cases)));
   225 
   226   (* Build the new theory *)
   227 
   228   val need_recursor = (not coind andalso recursor_typ <> case_typ);
   229 
   230   fun add_recursor thy =
   231       if need_recursor then
   232            thy |> Theory.add_consts_i
   233                     [(recursor_base_name, recursor_typ, NoSyn)]
   234                |> (snd o PureThy.add_defs_i false [Thm.no_attributes recursor_def])
   235       else thy;
   236 
   237   val (con_defs, thy0) = thy_path
   238              |> Theory.add_consts_i
   239                  ((case_base_name, case_typ, NoSyn) ::
   240                   map #1 (List.concat con_ty_lists))
   241              |> PureThy.add_defs_i false
   242                  (map Thm.no_attributes
   243                   (case_def ::
   244                    List.concat (ListPair.map mk_con_defs
   245                          (1 upto npart, con_ty_lists))))
   246              ||> add_recursor
   247              ||> Theory.parent_path
   248 
   249   val intr_names = map #2 (List.concat con_ty_lists);
   250   val (thy1, ind_result) =
   251     thy0 |> Ind_Package.add_inductive_i
   252       false (rec_tms, dom_sum) (map Thm.no_attributes (intr_names ~~ intr_tms))
   253       (monos, con_defs, type_intrs @ Datatype_Arg.intrs, type_elims @ Datatype_Arg.elims);
   254 
   255   (**** Now prove the datatype theorems in this theory ****)
   256 
   257 
   258   (*** Prove the case theorems ***)
   259 
   260   (*Each equation has the form
   261     case(f_con1,...,f_conn)(coni(args)) = f_coni(args) *)
   262   fun mk_case_eqn (((_,T,_), name, args, _), case_free) =
   263     FOLogic.mk_Trueprop
   264       (FOLogic.mk_eq
   265        (case_tm $
   266          (list_comb (Const (Sign.intern_const (sign_of thy1) name,T),
   267                      args)),
   268         list_comb (case_free, args)));
   269 
   270   val case_trans = hd con_defs RS Ind_Syntax.def_trans
   271   and split_trans = Pr.split_eq RS meta_eq_to_obj_eq RS trans;
   272 
   273   fun prove_case_eqn (arg, con_def) =
   274     standard (Goal.prove thy1 [] []
   275       (Ind_Syntax.traceIt "next case equation = " thy1 (mk_case_eqn arg))
   276       (*Proves a single case equation.  Could use simp_tac, but it's slower!*)
   277       (fn _ => EVERY
   278         [rewtac con_def,
   279          rtac case_trans 1,
   280          REPEAT (resolve_tac [refl, split_trans, Su.case_inl RS trans, Su.case_inr RS trans] 1)]));
   281 
   282   val free_iffs = map standard (con_defs RL [Ind_Syntax.def_swap_iff]);
   283 
   284   val case_eqns =
   285       map prove_case_eqn
   286          (List.concat con_ty_lists ~~ case_args ~~ tl con_defs);
   287 
   288   (*** Prove the recursor theorems ***)
   289 
   290   val recursor_eqns = case try (get_def thy1) recursor_base_name of
   291      NONE => (writeln "  [ No recursion operator ]";
   292               [])
   293    | SOME recursor_def =>
   294       let
   295         (*Replace subterms rec`x (where rec is a Free var) by recursor_tm(x) *)
   296         fun subst_rec (Const("op `",_) $ Free _ $ arg) = recursor_tm $ arg
   297           | subst_rec tm =
   298               let val (head, args) = strip_comb tm
   299               in  list_comb (head, map subst_rec args)  end;
   300 
   301         (*Each equation has the form
   302           REC(coni(args)) = f_coni(args, REC(rec_arg), ...)
   303           where REC = recursor(f_con1,...,f_conn) and rec_arg is a recursive
   304           constructor argument.*)
   305         fun mk_recursor_eqn (((_,T,_), name, args, _), recursor_case) =
   306           FOLogic.mk_Trueprop
   307            (FOLogic.mk_eq
   308             (recursor_tm $
   309              (list_comb (Const (Sign.intern_const (sign_of thy1) name,T),
   310                          args)),
   311              subst_rec (Term.betapplys (recursor_case, args))));
   312 
   313         val recursor_trans = recursor_def RS def_Vrecursor RS trans;
   314 
   315         fun prove_recursor_eqn arg =
   316           standard (Goal.prove thy1 [] []
   317             (Ind_Syntax.traceIt "next recursor equation = " thy1 (mk_recursor_eqn arg))
   318             (*Proves a single recursor equation.*)
   319             (fn _ => EVERY
   320               [rtac recursor_trans 1,
   321                simp_tac (rank_ss addsimps case_eqns) 1,
   322                IF_UNSOLVED (simp_tac (rank_ss addsimps tl con_defs) 1)]));
   323       in
   324          map prove_recursor_eqn (List.concat con_ty_lists ~~ recursor_cases)
   325       end
   326 
   327   val constructors =
   328       map (head_of o #1 o Logic.dest_equals o #prop o rep_thm) (tl con_defs);
   329 
   330   val free_SEs = map standard (Ind_Syntax.mk_free_SEs free_iffs);
   331 
   332   val {intrs, elim, induct, mutual_induct, ...} = ind_result
   333 
   334   (*Typical theorems have the form ~con1=con2, con1=con2==>False,
   335     con1(x)=con1(y) ==> x=y, con1(x)=con1(y) <-> x=y, etc.  *)
   336   fun mk_free s =
   337     let val thy = theory_of_thm elim in (*Don't use thy1: it will be stale*)
   338       standard (Goal.prove thy [] [] (Sign.read_prop thy s)
   339         (fn _ => EVERY
   340          [rewrite_goals_tac con_defs,
   341           fast_tac (ZF_cs addSEs free_SEs @ Su.free_SEs) 1]))
   342     end;
   343 
   344   val simps = case_eqns @ recursor_eqns;
   345 
   346   val dt_info =
   347         {inductive = true,
   348          constructors = constructors,
   349          rec_rewrites = recursor_eqns,
   350          case_rewrites = case_eqns,
   351          induct = induct,
   352          mutual_induct = mutual_induct,
   353          exhaustion = elim};
   354 
   355   val con_info =
   356         {big_rec_name = big_rec_name,
   357          constructors = constructors,
   358             (*let primrec handle definition by cases*)
   359          free_iffs = free_iffs,
   360          rec_rewrites = (case recursor_eqns of
   361                              [] => case_eqns | _ => recursor_eqns)};
   362 
   363   (*associate with each constructor the datatype name and rewrites*)
   364   val con_pairs = map (fn c => (#1 (dest_Const c), con_info)) constructors
   365 
   366  in
   367   (*Updating theory components: simprules and datatype info*)
   368   (thy1 |> Theory.add_path big_rec_base_name
   369         |> PureThy.add_thmss
   370          [(("simps", simps), [Simplifier.simp_add]),
   371           (("", intrs), [Classical.safe_intro NONE]),
   372           (("con_defs", con_defs), []),
   373           (("case_eqns", case_eqns), []),
   374           (("recursor_eqns", recursor_eqns), []),
   375           (("free_iffs", free_iffs), []),
   376           (("free_elims", free_SEs), [])] |> snd
   377         |> DatatypesData.map (Symtab.update (big_rec_name, dt_info))
   378         |> ConstructorsData.map (fold Symtab.update con_pairs)
   379         |> Theory.parent_path,
   380    ind_result,
   381    {con_defs = con_defs,
   382     case_eqns = case_eqns,
   383     recursor_eqns = recursor_eqns,
   384     free_iffs = free_iffs,
   385     free_SEs = free_SEs,
   386     mk_free = mk_free})
   387   end;
   388 
   389 fun add_datatype (sdom, srec_tms) scon_ty_lists (raw_monos, raw_type_intrs, raw_type_elims) thy =
   390   let
   391     val read_i = Sign.simple_read_term thy Ind_Syntax.iT;
   392     val rec_tms = map read_i srec_tms;
   393     val con_ty_lists = Ind_Syntax.read_constructs thy scon_ty_lists;
   394     val dom_sum =
   395       if sdom = "" then Ind_Syntax.data_domain coind (rec_tms, con_ty_lists)
   396       else read_i sdom;
   397   in
   398     thy
   399     |> IsarThy.apply_theorems raw_monos
   400     ||>> IsarThy.apply_theorems raw_type_intrs
   401     ||>> IsarThy.apply_theorems raw_type_elims
   402     |-> (fn ((monos, type_intrs), type_elims) =>
   403           add_datatype_i (dom_sum, rec_tms) con_ty_lists (monos, type_intrs, type_elims))
   404   end;
   405 
   406 (* outer syntax *)
   407 
   408 local structure P = OuterParse and K = OuterKeyword in
   409 
   410 fun mk_datatype ((((dom, dts), monos), type_intrs), type_elims) =
   411   #1 o add_datatype (dom, map fst dts) (map snd dts) (monos, type_intrs, type_elims);
   412 
   413 val con_decl =
   414   P.name -- Scan.optional (P.$$$ "(" |-- P.list1 P.term --| P.$$$ ")") [] -- P.opt_mixfix
   415   >> P.triple1;
   416 
   417 val datatype_decl =
   418   (Scan.optional ((P.$$$ "\\<subseteq>" || P.$$$ "<=") |-- P.!!! P.term) "") --
   419   P.and_list1 (P.term -- (P.$$$ "=" |-- P.enum1 "|" con_decl)) --
   420   Scan.optional (P.$$$ "monos" |-- P.!!! P.xthms1) [] --
   421   Scan.optional (P.$$$ "type_intros" |-- P.!!! P.xthms1) [] --
   422   Scan.optional (P.$$$ "type_elims" |-- P.!!! P.xthms1) []
   423   >> (Toplevel.theory o mk_datatype);
   424 
   425 val coind_prefix = if coind then "co" else "";
   426 
   427 val inductiveP = OuterSyntax.command (coind_prefix ^ "datatype")
   428   ("define " ^ coind_prefix ^ "datatype") K.thy_decl datatype_decl;
   429 
   430 val _ = OuterSyntax.add_parsers [inductiveP];
   431 
   432 end;
   433 
   434 end;
   435