src/HOL/Tools/datatype_package.ML
author wenzelm
Thu Jun 19 20:48:01 2008 +0200 (2008-06-19)
changeset 27277 7b7ce2d7fafe
parent 27261 5b3101338f42
child 27300 4cb3101d2bf7
permissions -rw-r--r--
export read_typ/cert_typ -- version with regular context operations;
     1 (*  Title:      HOL/Tools/datatype_package.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4 
     5 Datatype package for Isabelle/HOL.
     6 *)
     7 
     8 signature DATATYPE_PACKAGE =
     9 sig
    10   val quiet_mode : bool ref
    11   val get_datatypes : theory -> DatatypeAux.datatype_info Symtab.table
    12   val print_datatypes : theory -> unit
    13   val get_datatype : theory -> string -> DatatypeAux.datatype_info option
    14   val the_datatype : theory -> string -> DatatypeAux.datatype_info
    15   val datatype_of_constr : theory -> string -> DatatypeAux.datatype_info option
    16   val datatype_of_case : theory -> string -> DatatypeAux.datatype_info option
    17   val the_datatype_spec : theory -> string -> (string * sort) list * (string * typ list) list
    18   val get_datatype_constrs : theory -> string -> (string * typ) list option
    19   val construction_interpretation : theory
    20     -> {atom : typ -> 'a, dtyp : string -> 'a, rtyp : string -> 'a list -> 'a}
    21     -> (string * sort) list -> string list
    22     -> (string * (string * 'a list) list) list
    23   val distinct_simproc : simproc
    24   val make_case :  Proof.context -> bool -> string list -> term ->
    25     (term * term) list -> term * (term * (int * bool)) list
    26   val strip_case : Proof.context -> bool -> term -> (term * (term * term) list) option
    27   val read_typ: theory ->
    28     (typ list * (string * sort) list) * string -> typ list * (string * sort) list
    29   val interpretation : (string list -> theory -> theory) -> theory -> theory
    30   val rep_datatype : ({distinct : thm list list,
    31        inject : thm list list,
    32        exhaustion : thm list,
    33        rec_thms : thm list,
    34        case_thms : thm list list,
    35        split_thms : (thm * thm) list,
    36        induction : thm,
    37        simps : thm list} -> Proof.context -> Proof.context) -> string list option -> term list
    38     -> theory -> Proof.state;
    39   val rep_datatype_cmd : string list option -> string list -> theory -> Proof.state;
    40   val add_datatype : bool -> bool -> string list -> (string list * bstring * mixfix *
    41     (bstring * typ list * mixfix) list) list -> theory ->
    42       {distinct : thm list list,
    43        inject : thm list list,
    44        exhaustion : thm list,
    45        rec_thms : thm list,
    46        case_thms : thm list list,
    47        split_thms : (thm * thm) list,
    48        induction : thm,
    49        simps : thm list} * theory
    50   val add_datatype_cmd : bool -> string list -> (string list * bstring * mixfix *
    51     (bstring * string list * mixfix) list) list -> theory ->
    52       {distinct : thm list list,
    53        inject : thm list list,
    54        exhaustion : thm list,
    55        rec_thms : thm list,
    56        case_thms : thm list list,
    57        split_thms : (thm * thm) list,
    58        induction : thm,
    59        simps : thm list} * theory
    60   val setup: theory -> theory
    61 end;
    62 
    63 structure DatatypePackage : DATATYPE_PACKAGE =
    64 struct
    65 
    66 open DatatypeAux;
    67 
    68 val quiet_mode = quiet_mode;
    69 
    70 
    71 (* theory data *)
    72 
    73 structure DatatypesData = TheoryDataFun
    74 (
    75   type T =
    76     {types: datatype_info Symtab.table,
    77      constrs: datatype_info Symtab.table,
    78      cases: datatype_info Symtab.table};
    79 
    80   val empty =
    81     {types = Symtab.empty, constrs = Symtab.empty, cases = Symtab.empty};
    82   val copy = I;
    83   val extend = I;
    84   fun merge _
    85     ({types = types1, constrs = constrs1, cases = cases1},
    86      {types = types2, constrs = constrs2, cases = cases2}) =
    87     {types = Symtab.merge (K true) (types1, types2),
    88      constrs = Symtab.merge (K true) (constrs1, constrs2),
    89      cases = Symtab.merge (K true) (cases1, cases2)};
    90 );
    91 
    92 val get_datatypes = #types o DatatypesData.get;
    93 val map_datatypes = DatatypesData.map;
    94 
    95 fun print_datatypes thy =
    96   Pretty.writeln (Pretty.strs ("datatypes:" ::
    97     map #1 (NameSpace.extern_table (Sign.type_space thy, get_datatypes thy))));
    98 
    99 
   100 (** theory information about datatypes **)
   101 
   102 fun put_dt_infos (dt_infos : (string * datatype_info) list) =
   103   map_datatypes (fn {types, constrs, cases} =>
   104     {types = fold Symtab.update dt_infos types,
   105      constrs = fold Symtab.update
   106        (maps (fn (_, info as {descr, index, ...}) => map (rpair info o fst)
   107           (#3 (the (AList.lookup op = descr index)))) dt_infos) constrs,
   108      cases = fold Symtab.update
   109        (map (fn (_, info as {case_name, ...}) => (case_name, info)) dt_infos)
   110        cases});
   111 
   112 val get_datatype = Symtab.lookup o get_datatypes;
   113 
   114 fun the_datatype thy name = (case get_datatype thy name of
   115       SOME info => info
   116     | NONE => error ("Unknown datatype " ^ quote name));
   117 
   118 val datatype_of_constr = Symtab.lookup o #constrs o DatatypesData.get;
   119 val datatype_of_case = Symtab.lookup o #cases o DatatypesData.get;
   120 
   121 fun get_datatype_descr thy dtco =
   122   get_datatype thy dtco
   123   |> Option.map (fn info as { descr, index, ... } =>
   124        (info, (((fn SOME (_, dtys, cos) => (dtys, cos)) o AList.lookup (op =) descr) index)));
   125 
   126 fun the_datatype_spec thy dtco =
   127   let
   128     val info as { descr, index, sorts = raw_sorts, ... } = the_datatype thy dtco;
   129     val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr index;
   130     val sorts = map ((fn v => (v, (the o AList.lookup (op =) raw_sorts) v))
   131       o DatatypeAux.dest_DtTFree) dtys;
   132     val cos = map
   133       (fn (co, tys) => (co, map (DatatypeAux.typ_of_dtyp descr sorts) tys)) raw_cos;
   134   in (sorts, cos) end;
   135 
   136 fun get_datatype_constrs thy dtco =
   137   case try (the_datatype_spec thy) dtco
   138    of SOME (sorts, cos) =>
   139         let
   140           fun subst (v, sort) = TVar ((v, 0), sort);
   141           fun subst_ty (TFree v) = subst v
   142             | subst_ty ty = ty;
   143           val dty = Type (dtco, map subst sorts);
   144           fun mk_co (co, tys) = (co, map (Term.map_atyps subst_ty) tys ---> dty);
   145         in SOME (map mk_co cos) end
   146     | NONE => NONE;
   147 
   148 fun construction_interpretation thy { atom, dtyp, rtyp } sorts tycos =
   149   let
   150     val descr = (#descr o the_datatype thy o hd) tycos;
   151     val k = length tycos;
   152     val descr_of = the o AList.lookup (op =) descr;
   153     fun interpT (T as DtTFree _) = atom (typ_of_dtyp descr sorts T)
   154       | interpT (T as DtType (tyco, Ts)) = if is_rec_type T
   155           then rtyp tyco (map interpT Ts)
   156           else atom (typ_of_dtyp descr sorts T)
   157       | interpT (DtRec l) = if l < k then (dtyp o #1 o descr_of) l
   158           else let val (tyco, Ts, _) = descr_of l
   159           in rtyp tyco (map interpT Ts) end;
   160     fun interpC (c, Ts) = (c, map interpT Ts);
   161     fun interpK (_, (tyco, _, cs)) = (tyco, map interpC cs);
   162   in map interpK (Library.take (k, descr)) end;
   163 
   164 
   165 
   166 (** induct method setup **)
   167 
   168 (* case names *)
   169 
   170 local
   171 
   172 fun dt_recs (DtTFree _) = []
   173   | dt_recs (DtType (_, dts)) = maps dt_recs dts
   174   | dt_recs (DtRec i) = [i];
   175 
   176 fun dt_cases (descr: descr) (_, args, constrs) =
   177   let
   178     fun the_bname i = Sign.base_name (#1 (the (AList.lookup (op =) descr i)));
   179     val bnames = map the_bname (distinct (op =) (maps dt_recs args));
   180   in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
   181 
   182 
   183 fun induct_cases descr =
   184   DatatypeProp.indexify_names (maps (dt_cases descr) (map #2 descr));
   185 
   186 fun exhaust_cases descr i = dt_cases descr (the (AList.lookup (op =) descr i));
   187 
   188 in
   189 
   190 fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
   191 
   192 fun mk_case_names_exhausts descr new =
   193   map (RuleCases.case_names o exhaust_cases descr o #1)
   194     (filter (fn ((_, (name, _, _))) => member (op =) new name) descr);
   195 
   196 end;
   197 
   198 fun add_rules simps case_thms rec_thms inject distinct
   199                   weak_case_congs cong_att =
   200   PureThy.add_thmss [(("simps", simps), []),
   201     (("", flat case_thms @
   202           flat distinct @ rec_thms), [Simplifier.simp_add]),
   203     (("", rec_thms), [RecfunCodegen.add_default]),
   204     (("", flat inject), [iff_add]),
   205     (("", map (fn th => th RS notE) (flat distinct)), [Classical.safe_elim NONE]),
   206     (("", weak_case_congs), [cong_att])]
   207   #> snd;
   208 
   209 
   210 (* add_cases_induct *)
   211 
   212 fun add_cases_induct infos induction thy =
   213   let
   214     val inducts = ProjectRule.projections (ProofContext.init thy) induction;
   215 
   216     fun named_rules (name, {index, exhaustion, ...}: datatype_info) =
   217       [(("", nth inducts index), [Induct.induct_type name]),
   218        (("", exhaustion), [Induct.cases_type name])];
   219     fun unnamed_rule i =
   220       (("", nth inducts i), [PureThy.kind_internal, Induct.induct_type ""]);
   221   in
   222     thy |> PureThy.add_thms
   223       (maps named_rules infos @
   224         map unnamed_rule (length infos upto length inducts - 1)) |> snd
   225     |> PureThy.add_thmss [(("inducts", inducts), [])] |> snd
   226   end;
   227 
   228 
   229 
   230 (**** simplification procedure for showing distinctness of constructors ****)
   231 
   232 fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
   233   | stripT p = p;
   234 
   235 fun stripC (i, f $ x) = stripC (i + 1, f)
   236   | stripC p = p;
   237 
   238 val distinctN = "constr_distinct";
   239 
   240 fun distinct_rule thy ss tname eq_t = case #distinct (the_datatype thy tname) of
   241     FewConstrs thms => Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
   242       (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
   243         atac 2, resolve_tac thms 1, etac FalseE 1]))
   244   | ManyConstrs (thm, simpset) =>
   245       let
   246         val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
   247           map (PureThy.get_thm (ThyInfo.the_theory "Datatype" thy))
   248             ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"];
   249       in
   250         Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
   251         (EVERY [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
   252           full_simp_tac (Simplifier.inherit_context ss simpset) 1,
   253           REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   254           eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
   255           etac FalseE 1]))
   256       end;
   257 
   258 fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
   259   (case (stripC (0, t1), stripC (0, t2)) of
   260      ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
   261          (case (stripT (0, T1), stripT (0, T2)) of
   262             ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
   263                 if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
   264                    (case (get_datatype_descr thy) tname1 of
   265                       SOME (_, (_, constrs)) => let val cnames = map fst constrs
   266                         in if cname1 mem cnames andalso cname2 mem cnames then
   267                              SOME (distinct_rule thy ss tname1
   268                                (Logic.mk_equals (t, Const ("False", HOLogic.boolT))))
   269                            else NONE
   270                         end
   271                     | NONE => NONE)
   272                 else NONE
   273           | _ => NONE)
   274    | _ => NONE)
   275   | distinct_proc _ _ _ = NONE;
   276 
   277 val distinct_simproc =
   278   Simplifier.simproc HOL.thy distinctN ["s = t"] distinct_proc;
   279 
   280 val dist_ss = HOL_ss addsimprocs [distinct_simproc];
   281 
   282 val simproc_setup =
   283   Simplifier.map_simpset (fn ss => ss addsimprocs [distinct_simproc]);
   284 
   285 
   286 (**** translation rules for case ****)
   287 
   288 fun make_case ctxt = DatatypeCase.make_case
   289   (datatype_of_constr (ProofContext.theory_of ctxt)) ctxt;
   290 
   291 fun strip_case ctxt = DatatypeCase.strip_case
   292   (datatype_of_case (ProofContext.theory_of ctxt));
   293 
   294 fun add_case_tr' case_names thy =
   295   Sign.add_advanced_trfuns ([], [],
   296     map (fn case_name =>
   297       let val case_name' = Sign.const_syntax_name thy case_name
   298       in (case_name', DatatypeCase.case_tr' datatype_of_case case_name')
   299       end) case_names, []) thy;
   300 
   301 val trfun_setup =
   302   Sign.add_advanced_trfuns ([],
   303     [("_case_syntax", DatatypeCase.case_tr true datatype_of_constr)],
   304     [], []);
   305 
   306 
   307 (* prepare types *)
   308 
   309 fun read_typ thy ((Ts, sorts), str) =
   310   let
   311     val ctxt = ProofContext.init thy
   312       |> fold (Variable.declare_typ o TFree) sorts;
   313     val T = Syntax.read_typ ctxt str;
   314   in (Ts @ [T], Term.add_tfreesT T sorts) end;
   315 
   316 fun cert_typ sign ((Ts, sorts), raw_T) =
   317   let
   318     val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
   319       TYPE (msg, _, _) => error msg;
   320     val sorts' = Term.add_tfreesT T sorts;
   321   in (Ts @ [T],
   322       case duplicates (op =) (map fst sorts') of
   323          [] => sorts'
   324        | dups => error ("Inconsistent sort constraints for " ^ commas dups))
   325   end;
   326 
   327 
   328 (**** make datatype info ****)
   329 
   330 fun make_dt_info alt_names descr sorts induct reccomb_names rec_thms
   331     (((((((((i, (_, (tname, _, _))), case_name), case_thms),
   332       exhaustion_thm), distinct_thm), inject), nchotomy), case_cong), weak_case_cong) =
   333   (tname,
   334    {index = i,
   335     alt_names = alt_names,
   336     descr = descr,
   337     sorts = sorts,
   338     rec_names = reccomb_names,
   339     rec_rewrites = rec_thms,
   340     case_name = case_name,
   341     case_rewrites = case_thms,
   342     induction = induct,
   343     exhaustion = exhaustion_thm,
   344     distinct = distinct_thm,
   345     inject = inject,
   346     nchotomy = nchotomy,
   347     case_cong = case_cong,
   348     weak_case_cong = weak_case_cong});
   349 
   350 structure DatatypeInterpretation = InterpretationFun(type T = string list val eq = op =);
   351 val interpretation = DatatypeInterpretation.interpretation;
   352 
   353 
   354 (******************* definitional introduction of datatypes *******************)
   355 
   356 fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
   357     case_names_induct case_names_exhausts thy =
   358   let
   359     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   360 
   361     val ((inject, distinct, dist_rewrites, simproc_dists, induct), thy2) = thy |>
   362       DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
   363         types_syntax constr_syntax case_names_induct;
   364 
   365     val (casedist_thms, thy3) = DatatypeAbsProofs.prove_casedist_thms new_type_names descr
   366       sorts induct case_names_exhausts thy2;
   367     val ((reccomb_names, rec_thms), thy4) = DatatypeAbsProofs.prove_primrec_thms
   368       flat_names new_type_names descr sorts dt_info inject dist_rewrites
   369       (Simplifier.theory_context thy3 dist_ss) induct thy3;
   370     val ((case_thms, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
   371       flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
   372     val (split_thms, thy7) = DatatypeAbsProofs.prove_split_thms new_type_names
   373       descr sorts inject dist_rewrites casedist_thms case_thms thy6;
   374     val (nchotomys, thy8) = DatatypeAbsProofs.prove_nchotomys new_type_names
   375       descr sorts casedist_thms thy7;
   376     val (case_congs, thy9) = DatatypeAbsProofs.prove_case_congs new_type_names
   377       descr sorts nchotomys case_thms thy8;
   378     val (weak_case_congs, thy10) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
   379       descr sorts thy9;
   380 
   381     val dt_infos = map (make_dt_info NONE (flat descr) sorts induct reccomb_names rec_thms)
   382       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
   383         casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
   384 
   385     val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
   386 
   387     val thy12 =
   388       thy10
   389       |> add_case_tr' case_names
   390       |> Sign.add_path (space_implode "_" new_type_names)
   391       |> add_rules simps case_thms rec_thms inject distinct
   392           weak_case_congs (Simplifier.attrib (op addcongs))
   393       |> put_dt_infos dt_infos
   394       |> add_cases_induct dt_infos induct
   395       |> Sign.parent_path
   396       |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms) |> snd
   397       |> DatatypeInterpretation.data (map fst dt_infos);
   398   in
   399     ({distinct = distinct,
   400       inject = inject,
   401       exhaustion = casedist_thms,
   402       rec_thms = rec_thms,
   403       case_thms = case_thms,
   404       split_thms = split_thms,
   405       induction = induct,
   406       simps = simps}, thy12)
   407   end;
   408 
   409 
   410 (*********************** declare existing type as datatype *********************)
   411 
   412 fun prove_rep_datatype alt_names new_type_names descr sorts induct inject distinct thy =
   413   let
   414     val ((_, [induct']), _) =
   415       Variable.importT_thms [induct] (Variable.thm_context induct);
   416 
   417     fun err t = error ("Ill-formed predicate in induction rule: " ^
   418       Syntax.string_of_term_global thy t);
   419 
   420     fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
   421           ((tname, map (fst o dest_TFree) Ts) handle TERM _ => err t)
   422       | get_typ t = err t;
   423     val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induct')));
   424 
   425     val dt_info = get_datatypes thy;
   426 
   427     val (case_names_induct, case_names_exhausts) =
   428       (mk_case_names_induct descr, mk_case_names_exhausts descr (map #1 dtnames));
   429 
   430     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   431 
   432     val (casedist_thms, thy2) = thy |>
   433       DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induct
   434         case_names_exhausts;
   435     val ((reccomb_names, rec_thms), thy3) = DatatypeAbsProofs.prove_primrec_thms
   436       false new_type_names [descr] sorts dt_info inject distinct
   437       (Simplifier.theory_context thy2 dist_ss) induct thy2;
   438     val ((case_thms, case_names), thy4) = DatatypeAbsProofs.prove_case_thms false
   439       new_type_names [descr] sorts reccomb_names rec_thms thy3;
   440     val (split_thms, thy5) = DatatypeAbsProofs.prove_split_thms
   441       new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
   442     val (nchotomys, thy6) = DatatypeAbsProofs.prove_nchotomys new_type_names
   443       [descr] sorts casedist_thms thy5;
   444     val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
   445       [descr] sorts nchotomys case_thms thy6;
   446     val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
   447       [descr] sorts thy7;
   448 
   449     val ((_, [induct']), thy10) =
   450       thy8
   451       |> store_thmss "inject" new_type_names inject
   452       ||>> store_thmss "distinct" new_type_names distinct
   453       ||> Sign.add_path (space_implode "_" new_type_names)
   454       ||>> PureThy.add_thms [(("induct", induct), [case_names_induct])];
   455 
   456     val dt_infos = map (make_dt_info alt_names descr sorts induct' reccomb_names rec_thms)
   457       ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
   458         map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
   459 
   460     val simps = flat (distinct @ inject @ case_thms) @ rec_thms;
   461 
   462     val thy11 =
   463       thy10
   464       |> add_case_tr' case_names
   465       |> add_rules simps case_thms rec_thms inject distinct
   466            weak_case_congs (Simplifier.attrib (op addcongs))
   467       |> put_dt_infos dt_infos
   468       |> add_cases_induct dt_infos induct'
   469       |> Sign.parent_path
   470       |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)
   471       |> snd
   472       |> DatatypeInterpretation.data (map fst dt_infos);
   473   in
   474     ({distinct = distinct,
   475       inject = inject,
   476       exhaustion = casedist_thms,
   477       rec_thms = rec_thms,
   478       case_thms = case_thms,
   479       split_thms = split_thms,
   480       induction = induct',
   481       simps = simps}, thy11)
   482   end;
   483 
   484 fun gen_rep_datatype prep_term after_qed alt_names raw_ts thy =
   485   let
   486     fun constr_of_term (Const (c, T)) = (c, T)
   487       | constr_of_term t =
   488           error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
   489     fun no_constr (c, T) = error ("Bad constructor: "
   490       ^ Sign.extern_const thy c ^ "::"
   491       ^ Syntax.string_of_typ_global thy T);
   492     fun type_of_constr (cT as (_, T)) =
   493       let
   494         val frees = typ_tfrees T;
   495         val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) T
   496           handle TYPE _ => no_constr cT
   497         val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
   498         val _ = if length frees <> length vs then no_constr cT else ();
   499       in (tyco, (vs, cT)) end;
   500 
   501     val raw_cs = AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
   502     val _ = case map_filter (fn (tyco, _) =>
   503         if Symtab.defined (get_datatypes thy) tyco then SOME tyco else NONE) raw_cs
   504      of [] => ()
   505       | tycos => error ("Type(s) " ^ commas (map quote tycos)
   506           ^ " already represented inductivly");
   507     val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
   508     val ms = case distinct (op =) (map length raw_vss)
   509      of [n] => 0 upto n - 1
   510       | _ => error ("Different types in given constructors");
   511     fun inter_sort m = map (fn xs => nth xs m) raw_vss
   512       |> Library.foldr1 (Sorts.inter_sort (Sign.classes_of thy))
   513     val sorts = map inter_sort ms;
   514     val vs = Name.names Name.context Name.aT sorts;
   515 
   516     fun norm_constr (raw_vs, (c, T)) = (c, map_atyps
   517       (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
   518 
   519     val cs = map (apsnd (map norm_constr)) raw_cs;
   520     val dtyps_of_typ = map (dtyp_of_typ (map (rpair (map fst vs) o fst) cs))
   521       o fst o strip_type;
   522     val new_type_names = map NameSpace.base (the_default (map fst cs) alt_names);
   523 
   524     fun mk_spec (i, (tyco, constr)) = (i, (tyco,
   525       map (DtTFree o fst) vs,
   526       (map o apsnd) dtyps_of_typ constr))
   527     val descr = map_index mk_spec cs;
   528     val injs = DatatypeProp.make_injs [descr] vs;
   529     val distincts = map snd (DatatypeProp.make_distincts [descr] vs);
   530     val ind = DatatypeProp.make_ind [descr] vs;
   531     val rules = (map o map o map) Logic.close_form [[[ind]], injs, distincts];
   532 
   533     fun after_qed' raw_thms =
   534       let
   535         val [[[induct]], injs, distincts] =
   536           unflat rules (map Drule.zero_var_indexes_list raw_thms);
   537             (*FIXME somehow dubious*)
   538       in
   539         ProofContext.theory_result
   540           (prove_rep_datatype alt_names new_type_names descr vs induct injs distincts)
   541         #-> after_qed
   542       end;
   543   in
   544     thy
   545     |> ProofContext.init
   546     |> Proof.theorem_i NONE after_qed' ((map o map) (rpair []) (flat rules))
   547   end;
   548 
   549 val rep_datatype = gen_rep_datatype Sign.cert_term;
   550 val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global (K I);
   551 
   552 
   553 
   554 (******************************** add datatype ********************************)
   555 
   556 fun gen_add_datatype prep_typ err flat_names new_type_names dts thy =
   557   let
   558     val _ = Theory.requires thy "Datatype" "datatype definitions";
   559 
   560     (* this theory is used just for parsing *)
   561 
   562     val tmp_thy = thy |>
   563       Theory.copy |>
   564       Sign.add_types (map (fn (tvs, tname, mx, _) =>
   565         (tname, length tvs, mx)) dts);
   566 
   567     val (tyvars, _, _, _)::_ = dts;
   568     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   569       let val full_tname = Sign.full_name tmp_thy (Syntax.type_name tname mx)
   570       in (case duplicates (op =) tvs of
   571             [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   572                   else error ("Mutually recursive datatypes must have same type parameters")
   573           | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
   574               " : " ^ commas dups))
   575       end) dts);
   576 
   577     val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
   578       [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
   579 
   580     fun prep_dt_spec (tvs, tname, mx, constrs) (dts', constr_syntax, sorts, i) =
   581       let
   582         fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
   583           let
   584             val (cargs', sorts'') = Library.foldl (prep_typ tmp_thy) (([], sorts'), cargs);
   585             val _ = (case fold (curry add_typ_tfree_names) cargs' [] \\ tvs of
   586                 [] => ()
   587               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   588           in (constrs @ [((if flat_names then Sign.full_name tmp_thy else
   589                 Sign.full_name_path tmp_thy tname) (Syntax.const_name cname mx'),
   590                    map (dtyp_of_typ new_dts) cargs')],
   591               constr_syntax' @ [(cname, mx')], sorts'')
   592           end handle ERROR msg =>
   593             cat_error msg ("The error above occured in constructor " ^ cname ^
   594               " of datatype " ^ tname);
   595 
   596         val (constrs', constr_syntax', sorts') =
   597           fold prep_constr constrs ([], [], sorts)
   598 
   599       in
   600         case duplicates (op =) (map fst constrs') of
   601            [] =>
   602              (dts' @ [(i, (Sign.full_name tmp_thy (Syntax.type_name tname mx),
   603                 map DtTFree tvs, constrs'))],
   604               constr_syntax @ [constr_syntax'], sorts', i + 1)
   605          | dups => error ("Duplicate constructors " ^ commas dups ^
   606              " in datatype " ^ tname)
   607       end;
   608 
   609     val (dts', constr_syntax, sorts', i) = fold prep_dt_spec dts ([], [], [], 0);
   610     val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (tyvars \\ map fst sorts'));
   611     val dt_info = get_datatypes thy;
   612     val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
   613     val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
   614       if err then error ("Nonemptiness check failed for datatype " ^ s)
   615       else raise exn;
   616 
   617     val descr' = flat descr;
   618     val case_names_induct = mk_case_names_induct descr';
   619     val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
   620   in
   621     add_datatype_def
   622       flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
   623       case_names_induct case_names_exhausts thy
   624   end;
   625 
   626 val add_datatype = gen_add_datatype cert_typ;
   627 val add_datatype_cmd = gen_add_datatype read_typ true;
   628 
   629 
   630 (** a datatype antiquotation **)
   631 
   632 local
   633 
   634 val sym_datatype = Pretty.str "\\isacommand{datatype}";
   635 val sym_binder = Pretty.str "{\\isacharequal}";
   636 val sym_of = Pretty.str "of";
   637 val sym_sep = Pretty.str "{\\isacharbar}";
   638 
   639 in
   640 
   641 fun args_datatype (ctxt, args) =
   642   let
   643     val (tyco, (ctxt', args')) = Args.tyname (ctxt, args);
   644     val thy = Context.theory_of ctxt';
   645     val spec = the_datatype_spec thy tyco;
   646   in ((tyco, spec), (ctxt', args')) end;
   647 
   648 fun pretty_datatype ctxt (dtco, (vs, cos)) =
   649   let
   650     val ty = Type (dtco, map TFree vs);
   651     fun pretty_typ_br ty =
   652       let
   653         val p = Syntax.pretty_typ ctxt ty;
   654         val s = explode (Pretty.str_of p);
   655       in if member (op =) s " " then Pretty.enclose "(" ")" [p]
   656         else p
   657       end;
   658     fun pretty_constr (co, []) =
   659           Syntax.pretty_term ctxt (Const (co, ty))
   660       | pretty_constr (co, [ty']) =
   661           (Pretty.block o Pretty.breaks)
   662             [Syntax.pretty_term ctxt (Const (co, ty' --> ty)),
   663               sym_of, Syntax.pretty_typ ctxt ty']
   664       | pretty_constr (co, tys) =
   665           (Pretty.block o Pretty.breaks)
   666             (Syntax.pretty_term ctxt (Const (co, tys ---> ty)) ::
   667               sym_of :: map pretty_typ_br tys);
   668   in (Pretty.block o Pretty.breaks) (
   669     sym_datatype
   670     :: Syntax.pretty_typ ctxt ty
   671     :: sym_binder
   672     :: separate sym_sep (map pretty_constr cos)
   673   ) end
   674 
   675 end;
   676 
   677 (** package setup **)
   678 
   679 (* setup theory *)
   680 
   681 val setup =
   682   DatatypeRepProofs.distinctness_limit_setup #>
   683   simproc_setup #>
   684   trfun_setup #>
   685   DatatypeInterpretation.init;
   686 
   687 
   688 (* outer syntax *)
   689 
   690 local structure P = OuterParse and K = OuterKeyword in
   691 
   692 val datatype_decl =
   693   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
   694     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
   695 
   696 fun mk_datatype args =
   697   let
   698     val names = map (fn ((((NONE, _), t), _), _) => t | ((((SOME t, _), _), _), _) => t) args;
   699     val specs = map (fn ((((_, vs), t), mx), cons) =>
   700       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   701   in snd o add_datatype_cmd false names specs end;
   702 
   703 val _ =
   704   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   705     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
   706 
   707 val _ =
   708   OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_goal
   709     (Scan.option (P.$$$ "(" |-- Scan.repeat1 P.name --| P.$$$ ")") -- Scan.repeat1 P.term
   710       >> (fn (alt_names, ts) => Toplevel.print
   711            o Toplevel.theory_to_proof (rep_datatype_cmd alt_names ts)));
   712 
   713 val _ =
   714   ThyOutput.add_commands [("datatype",
   715     ThyOutput.args args_datatype (ThyOutput.output pretty_datatype))];
   716 
   717 end;
   718 
   719 end;
   720