src/HOL/Tools/Datatype/datatype.ML
author haftmann
Thu Oct 08 19:33:03 2009 +0200 (2009-10-08)
changeset 32896 99cd75a18b78
parent 32731 f7ed14d60818
child 32900 dc883c6126d4
permissions -rw-r--r--
lookup for datatype constructors considers type annotations to resolve overloading
     1 (*  Title:      HOL/Tools/datatype.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Datatype package for Isabelle/HOL.
     5 *)
     6 
     7 signature DATATYPE =
     8 sig
     9   include DATATYPE_COMMON
    10   val add_datatype : config -> string list -> (string list * binding * mixfix *
    11     (binding * typ list * mixfix) list) list -> theory -> string list * theory
    12   val datatype_cmd : string list -> (string list * binding * mixfix *
    13     (binding * string list * mixfix) list) list -> theory -> theory
    14   val rep_datatype : config -> (string list -> Proof.context -> Proof.context)
    15     -> string list option -> term list -> theory -> Proof.state
    16   val rep_datatype_cmd : string list option -> string list -> theory -> Proof.state
    17   val get_info : theory -> string -> info option
    18   val the_info : theory -> string -> info
    19   val the_descr : theory -> string list
    20     -> descr * (string * sort) list * string list
    21       * string * (string list * string list) * (typ list * typ list)
    22   val the_spec : theory -> string -> (string * sort) list * (string * typ list) list
    23   val get_constrs : theory -> string -> (string * typ) list option
    24   val get_all : theory -> info Symtab.table
    25   val info_of_constr : theory -> string * typ -> info option
    26   val info_of_case : theory -> string -> info option
    27   val interpretation : (config -> string list -> theory -> theory) -> theory -> theory
    28   val distinct_simproc : simproc
    29   val make_case :  Proof.context -> DatatypeCase.config -> string list -> term ->
    30     (term * term) list -> term * (term * (int * bool)) list
    31   val strip_case : Proof.context -> bool -> term -> (term * (term * term) list) option
    32   val read_typ: theory ->
    33     (typ list * (string * sort) list) * string -> typ list * (string * sort) list
    34   val setup: theory -> theory
    35 end;
    36 
    37 structure Datatype : DATATYPE =
    38 struct
    39 
    40 open DatatypeAux;
    41 
    42 (** theory data **)
    43 
    44 (* data management *)
    45 
    46 structure DatatypesData = TheoryDataFun
    47 (
    48   type T =
    49     {types: info Symtab.table,
    50      constrs: (string * info) list Symtab.table,
    51      cases: info Symtab.table};
    52 
    53   val empty =
    54     {types = Symtab.empty, constrs = Symtab.empty, cases = Symtab.empty};
    55   val copy = I;
    56   val extend = I;
    57   fun merge _
    58     ({types = types1, constrs = constrs1, cases = cases1},
    59      {types = types2, constrs = constrs2, cases = cases2}) =
    60     {types = Symtab.merge (K true) (types1, types2),
    61      constrs = Symtab.join (K (AList.merge (op =) (K true))) (constrs1, constrs2),
    62      cases = Symtab.merge (K true) (cases1, cases2)};
    63 );
    64 
    65 val get_all = #types o DatatypesData.get;
    66 val get_info = Symtab.lookup o get_all;
    67 fun the_info thy name = (case get_info thy name of
    68       SOME info => info
    69     | NONE => error ("Unknown datatype " ^ quote name));
    70 
    71 fun info_of_constr thy (c, T) =
    72   let
    73     val tab = Symtab.lookup_list ((#constrs o DatatypesData.get) thy) c;
    74     val hint = case strip_type T of (_, Type (tyco, _)) => SOME tyco | _ => NONE;
    75     val default = if null tab then NONE
    76       else SOME (snd (Library.last_elem tab))
    77         (*conservative wrt. overloaded constructors*);
    78   in case hint
    79    of NONE => default
    80     | SOME tyco => case AList.lookup (op =) tab tyco
    81        of NONE => default (*permissive*)
    82         | SOME info => SOME info
    83   end;
    84 
    85 val info_of_case = Symtab.lookup o #cases o DatatypesData.get;
    86 
    87 fun register (dt_infos : (string * info) list) =
    88   DatatypesData.map (fn {types, constrs, cases} =>
    89     {types = types |> fold Symtab.update dt_infos,
    90      constrs = constrs |> fold (fn (constr, dtname_info) =>
    91          Symtab.map_default (constr, []) (cons dtname_info))
    92        (maps (fn (dtname, info as {descr, index, ...}) =>
    93           map (rpair (dtname, info) o fst)
    94             (#3 (the (AList.lookup op = descr index)))) dt_infos),
    95      cases = cases |> fold Symtab.update
    96        (map (fn (_, info as {case_name, ...}) => (case_name, info)) dt_infos)});
    97 
    98 (* complex queries *)
    99 
   100 fun the_spec thy dtco =
   101   let
   102     val info as { descr, index, sorts = raw_sorts, ... } = the_info thy dtco;
   103     val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr index;
   104     val sorts = map ((fn v => (v, (the o AList.lookup (op =) raw_sorts) v))
   105       o DatatypeAux.dest_DtTFree) dtys;
   106     val cos = map
   107       (fn (co, tys) => (co, map (DatatypeAux.typ_of_dtyp descr sorts) tys)) raw_cos;
   108   in (sorts, cos) end;
   109 
   110 fun the_descr thy (raw_tycos as raw_tyco :: _) =
   111   let
   112     val info = the_info thy raw_tyco;
   113     val descr = #descr info;
   114 
   115     val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr (#index info);
   116     val vs = map ((fn v => (v, (the o AList.lookup (op =) (#sorts info)) v))
   117       o dest_DtTFree) dtys;
   118 
   119     fun is_DtTFree (DtTFree _) = true
   120       | is_DtTFree _ = false
   121     val k = find_index (fn (_, (_, dTs, _)) => not (forall is_DtTFree dTs)) descr;
   122     val protoTs as (dataTs, _) = chop k descr
   123       |> (pairself o map) (fn (_, (tyco, dTs, _)) => (tyco, map (typ_of_dtyp descr vs) dTs));
   124     
   125     val tycos = map fst dataTs;
   126     val _ = if gen_eq_set (op =) (tycos, raw_tycos) then ()
   127       else error ("Type constructors " ^ commas (map quote raw_tycos)
   128         ^ " do not belong exhaustively to one mutual recursive datatype");
   129 
   130     val (Ts, Us) = (pairself o map) Type protoTs;
   131 
   132     val names = map Long_Name.base_name (the_default tycos (#alt_names info));
   133     val (auxnames, _) = Name.make_context names
   134       |> fold_map (yield_singleton Name.variants o name_of_typ) Us;
   135     val prefix = space_implode "_" names;
   136 
   137   in (descr, vs, tycos, prefix, (names, auxnames), (Ts, Us)) end;
   138 
   139 fun get_constrs thy dtco =
   140   case try (the_spec thy) dtco
   141    of SOME (sorts, cos) =>
   142         let
   143           fun subst (v, sort) = TVar ((v, 0), sort);
   144           fun subst_ty (TFree v) = subst v
   145             | subst_ty ty = ty;
   146           val dty = Type (dtco, map subst sorts);
   147           fun mk_co (co, tys) = (co, map (Term.map_atyps subst_ty) tys ---> dty);
   148         in SOME (map mk_co cos) end
   149     | NONE => NONE;
   150 
   151 
   152 (** various auxiliary **)
   153 
   154 (* simplification procedure for showing distinctness of constructors *)
   155 
   156 fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
   157   | stripT p = p;
   158 
   159 fun stripC (i, f $ x) = stripC (i + 1, f)
   160   | stripC p = p;
   161 
   162 val distinctN = "constr_distinct";
   163 
   164 fun distinct_rule thy ss tname eq_t = case #distinct (the_info thy tname) of
   165     FewConstrs thms => Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
   166       (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
   167         atac 2, resolve_tac thms 1, etac FalseE 1]))
   168   | ManyConstrs (thm, simpset) =>
   169       let
   170         val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
   171           map (PureThy.get_thm (ThyInfo.the_theory "Datatype" thy))
   172             ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"];
   173       in
   174         Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
   175         (EVERY [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
   176           full_simp_tac (Simplifier.inherit_context ss simpset) 1,
   177           REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   178           eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
   179           etac FalseE 1]))
   180       end;
   181 
   182 fun get_constr thy dtco =
   183   get_info thy dtco
   184   |> Option.map (fn { descr, index, ... } => (#3 o the o AList.lookup (op =) descr) index);
   185 
   186 fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
   187   (case (stripC (0, t1), stripC (0, t2)) of
   188      ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
   189          (case (stripT (0, T1), stripT (0, T2)) of
   190             ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
   191                 if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
   192                    (case get_constr thy tname1 of
   193                       SOME constrs => let val cnames = map fst constrs
   194                         in if cname1 mem cnames andalso cname2 mem cnames then
   195                              SOME (distinct_rule thy ss tname1
   196                                (Logic.mk_equals (t, HOLogic.false_const)))
   197                            else NONE
   198                         end
   199                     | NONE => NONE)
   200                 else NONE
   201           | _ => NONE)
   202    | _ => NONE)
   203   | distinct_proc _ _ _ = NONE;
   204 
   205 val distinct_simproc =
   206   Simplifier.simproc @{theory HOL} distinctN ["s = t"] distinct_proc;
   207 
   208 val dist_ss = HOL_ss addsimprocs [distinct_simproc];
   209 
   210 val simproc_setup =
   211   Simplifier.map_simpset (fn ss => ss addsimprocs [distinct_simproc]);
   212 
   213 (* prepare datatype specifications *)
   214 
   215 fun read_typ thy ((Ts, sorts), str) =
   216   let
   217     val ctxt = ProofContext.init thy
   218       |> fold (Variable.declare_typ o TFree) sorts;
   219     val T = Syntax.read_typ ctxt str;
   220   in (Ts @ [T], Term.add_tfreesT T sorts) end;
   221 
   222 fun cert_typ sign ((Ts, sorts), raw_T) =
   223   let
   224     val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
   225       TYPE (msg, _, _) => error msg;
   226     val sorts' = Term.add_tfreesT T sorts;
   227   in (Ts @ [T],
   228       case duplicates (op =) (map fst sorts') of
   229          [] => sorts'
   230        | dups => error ("Inconsistent sort constraints for " ^ commas dups))
   231   end;
   232 
   233 (* case names *)
   234 
   235 local
   236 
   237 fun dt_recs (DtTFree _) = []
   238   | dt_recs (DtType (_, dts)) = maps dt_recs dts
   239   | dt_recs (DtRec i) = [i];
   240 
   241 fun dt_cases (descr: descr) (_, args, constrs) =
   242   let
   243     fun the_bname i = Long_Name.base_name (#1 (the (AList.lookup (op =) descr i)));
   244     val bnames = map the_bname (distinct (op =) (maps dt_recs args));
   245   in map (fn (c, _) => space_implode "_" (Long_Name.base_name c :: bnames)) constrs end;
   246 
   247 fun induct_cases descr =
   248   DatatypeProp.indexify_names (maps (dt_cases descr) (map #2 descr));
   249 
   250 fun exhaust_cases descr i = dt_cases descr (the (AList.lookup (op =) descr i));
   251 
   252 in
   253 
   254 fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
   255 
   256 fun mk_case_names_exhausts descr new =
   257   map (RuleCases.case_names o exhaust_cases descr o #1)
   258     (filter (fn ((_, (name, _, _))) => member (op =) new name) descr);
   259 
   260 end;
   261 
   262 (* translation rules for case *)
   263 
   264 fun make_case ctxt = DatatypeCase.make_case
   265   (info_of_constr (ProofContext.theory_of ctxt)) ctxt;
   266 
   267 fun strip_case ctxt = DatatypeCase.strip_case
   268   (info_of_case (ProofContext.theory_of ctxt));
   269 
   270 fun add_case_tr' case_names thy =
   271   Sign.add_advanced_trfuns ([], [],
   272     map (fn case_name =>
   273       let val case_name' = Sign.const_syntax_name thy case_name
   274       in (case_name', DatatypeCase.case_tr' info_of_case case_name')
   275       end) case_names, []) thy;
   276 
   277 val trfun_setup =
   278   Sign.add_advanced_trfuns ([],
   279     [("_case_syntax", DatatypeCase.case_tr true info_of_constr)],
   280     [], []);
   281 
   282 (* document antiquotation *)
   283 
   284 val _ = ThyOutput.antiquotation "datatype" Args.tyname
   285   (fn {source = src, context = ctxt, ...} => fn dtco =>
   286     let
   287       val thy = ProofContext.theory_of ctxt;
   288       val (vs, cos) = the_spec thy dtco;
   289       val ty = Type (dtco, map TFree vs);
   290       fun pretty_typ_bracket (ty as Type (_, _ :: _)) =
   291             Pretty.enclose "(" ")" [Syntax.pretty_typ ctxt ty]
   292         | pretty_typ_bracket ty =
   293             Syntax.pretty_typ ctxt ty;
   294       fun pretty_constr (co, tys) =
   295         (Pretty.block o Pretty.breaks)
   296           (Syntax.pretty_term ctxt (Const (co, tys ---> ty)) ::
   297             map pretty_typ_bracket tys);
   298       val pretty_datatype =
   299         Pretty.block
   300           (Pretty.command "datatype" :: Pretty.brk 1 ::
   301            Syntax.pretty_typ ctxt ty ::
   302            Pretty.str " =" :: Pretty.brk 1 ::
   303            flat (separate [Pretty.brk 1, Pretty.str "| "]
   304              (map (single o pretty_constr) cos)));
   305     in ThyOutput.output (ThyOutput.maybe_pretty_source (K pretty_datatype) src [()]) end);
   306 
   307 
   308 (** abstract theory extensions relative to a datatype characterisation **)
   309 
   310 structure DatatypeInterpretation = InterpretationFun
   311   (type T = config * string list val eq: T * T -> bool = eq_snd op =);
   312 fun interpretation f = DatatypeInterpretation.interpretation (uncurry f);
   313 
   314 fun make_dt_info alt_names descr sorts induct inducts rec_names rec_rewrites
   315     (index, (((((((((((_, (tname, _, _))), inject), distinct),
   316       exhaust), nchotomy), case_name), case_rewrites), case_cong), weak_case_cong), (split, split_asm))) =
   317   (tname,
   318    {index = index,
   319     alt_names = alt_names,
   320     descr = descr,
   321     sorts = sorts,
   322     inject = inject,
   323     distinct = distinct,
   324     induct = induct,
   325     inducts = inducts,
   326     exhaust = exhaust,
   327     nchotomy = nchotomy,
   328     rec_names = rec_names,
   329     rec_rewrites = rec_rewrites,
   330     case_name = case_name,
   331     case_rewrites = case_rewrites,
   332     case_cong = case_cong,
   333     weak_case_cong = weak_case_cong,
   334     split = split,
   335     split_asm = split_asm});
   336 
   337 fun derive_datatype_props config dt_names alt_names descr sorts
   338     induct inject (distinct_rules, distinct_rewrites, distinct_entry) thy1 =
   339   let
   340     val thy2 = thy1 |> Theory.checkpoint;
   341     val flat_descr = flat descr;
   342     val new_type_names = map Long_Name.base_name (the_default dt_names alt_names);
   343     val _ = message config ("Deriving properties for datatype(s) " ^ commas_quote new_type_names);
   344 
   345     val (exhaust, thy3) = DatatypeAbsProofs.prove_casedist_thms config new_type_names
   346       descr sorts induct (mk_case_names_exhausts flat_descr dt_names) thy2;
   347     val (nchotomys, thy4) = DatatypeAbsProofs.prove_nchotomys config new_type_names
   348       descr sorts exhaust thy3;
   349     val ((rec_names, rec_rewrites), thy5) = DatatypeAbsProofs.prove_primrec_thms
   350       config new_type_names descr sorts (#inject o the o Symtab.lookup (get_all thy4))
   351       inject distinct_rewrites (Simplifier.theory_context thy4 dist_ss) induct thy4;
   352     val ((case_rewrites, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
   353       config new_type_names descr sorts rec_names rec_rewrites thy5;
   354     val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
   355       descr sorts nchotomys case_rewrites thy6;
   356     val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
   357       descr sorts thy7;
   358     val (splits, thy9) = DatatypeAbsProofs.prove_split_thms
   359       config new_type_names descr sorts inject distinct_rewrites exhaust case_rewrites thy8;
   360 
   361     val inducts = Project_Rule.projections (ProofContext.init thy2) induct;
   362     val dt_infos = map_index (make_dt_info alt_names flat_descr sorts induct inducts rec_names rec_rewrites)
   363       (hd descr ~~ inject ~~ distinct_entry ~~ exhaust ~~ nchotomys ~~
   364         case_names ~~ case_rewrites ~~ case_congs ~~ weak_case_congs ~~ splits);
   365     val dt_names = map fst dt_infos;
   366     val prfx = Binding.qualify true (space_implode "_" new_type_names);
   367     val simps = flat (inject @ distinct_rules @ case_rewrites) @ rec_rewrites;
   368     val named_rules = flat (map_index (fn (index, tname) =>
   369       [((Binding.empty, [nth inducts index]), [Induct.induct_type tname]),
   370        ((Binding.empty, [nth exhaust index]), [Induct.cases_type tname])]) dt_names);
   371     val unnamed_rules = map (fn induct =>
   372       ((Binding.empty, [induct]), [Thm.kind_internal, Induct.induct_type ""]))
   373         (Library.drop (length dt_names, inducts));
   374   in
   375     thy9
   376     |> PureThy.add_thmss ([((prfx (Binding.name "simps"), simps), []),
   377         ((prfx (Binding.name "inducts"), inducts), []),
   378         ((prfx (Binding.name "splits"), maps (fn (x, y) => [x, y]) splits), []),
   379         ((Binding.empty, flat case_rewrites @ flat distinct_rules @ rec_rewrites),
   380           [Simplifier.simp_add]),
   381         ((Binding.empty, rec_rewrites), [Code.add_default_eqn_attribute]),
   382         ((Binding.empty, flat inject), [iff_add]),
   383         ((Binding.empty, map (fn th => th RS notE) (flat distinct_rules)),
   384           [Classical.safe_elim NONE]),
   385         ((Binding.empty, weak_case_congs), [Simplifier.attrib (op addcongs)])]
   386         @ named_rules @ unnamed_rules)
   387     |> snd
   388     |> add_case_tr' case_names
   389     |> register dt_infos
   390     |> DatatypeInterpretation.data (config, dt_names)
   391     |> pair dt_names
   392   end;
   393 
   394 
   395 (** declare existing type as datatype **)
   396 
   397 fun prove_rep_datatype config dt_names alt_names descr sorts raw_inject half_distinct raw_induct thy1 =
   398   let
   399     val raw_distinct = (map o maps) (fn thm => [thm, thm RS not_sym]) half_distinct;
   400     val new_type_names = map Long_Name.base_name (the_default dt_names alt_names);
   401     val (((inject, distinct), [induct]), thy2) =
   402       thy1
   403       |> store_thmss "inject" new_type_names raw_inject
   404       ||>> store_thmss "distinct" new_type_names raw_distinct
   405       ||> Sign.add_path (space_implode "_" new_type_names)
   406       ||>> PureThy.add_thms [((Binding.name "induct", raw_induct), [mk_case_names_induct descr])]
   407       ||> Sign.restore_naming thy1;
   408   in
   409     thy2
   410     |> derive_datatype_props config dt_names alt_names [descr] sorts
   411          induct inject (distinct, distinct, map FewConstrs distinct)
   412  end;
   413 
   414 fun gen_rep_datatype prep_term config after_qed alt_names raw_ts thy =
   415   let
   416     fun constr_of_term (Const (c, T)) = (c, T)
   417       | constr_of_term t =
   418           error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
   419     fun no_constr (c, T) = error ("Bad constructor: "
   420       ^ Sign.extern_const thy c ^ "::"
   421       ^ Syntax.string_of_typ_global thy T);
   422     fun type_of_constr (cT as (_, T)) =
   423       let
   424         val frees = OldTerm.typ_tfrees T;
   425         val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) T
   426           handle TYPE _ => no_constr cT
   427         val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
   428         val _ = if length frees <> length vs then no_constr cT else ();
   429       in (tyco, (vs, cT)) end;
   430 
   431     val raw_cs = AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
   432     val _ = case map_filter (fn (tyco, _) =>
   433         if Symtab.defined (get_all thy) tyco then SOME tyco else NONE) raw_cs
   434      of [] => ()
   435       | tycos => error ("Type(s) " ^ commas (map quote tycos)
   436           ^ " already represented inductivly");
   437     val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
   438     val ms = case distinct (op =) (map length raw_vss)
   439      of [n] => 0 upto n - 1
   440       | _ => error ("Different types in given constructors");
   441     fun inter_sort m = map (fn xs => nth xs m) raw_vss
   442       |> Library.foldr1 (Sorts.inter_sort (Sign.classes_of thy))
   443     val sorts = map inter_sort ms;
   444     val vs = Name.names Name.context Name.aT sorts;
   445 
   446     fun norm_constr (raw_vs, (c, T)) = (c, map_atyps
   447       (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
   448 
   449     val cs = map (apsnd (map norm_constr)) raw_cs;
   450     val dtyps_of_typ = map (dtyp_of_typ (map (rpair (map fst vs) o fst) cs))
   451       o fst o strip_type;
   452     val dt_names = map fst cs;
   453 
   454     fun mk_spec (i, (tyco, constr)) = (i, (tyco,
   455       map (DtTFree o fst) vs,
   456       (map o apsnd) dtyps_of_typ constr))
   457     val descr = map_index mk_spec cs;
   458     val injs = DatatypeProp.make_injs [descr] vs;
   459     val half_distincts = map snd (DatatypeProp.make_distincts [descr] vs);
   460     val ind = DatatypeProp.make_ind [descr] vs;
   461     val rules = (map o map o map) Logic.close_form [[[ind]], injs, half_distincts];
   462 
   463     fun after_qed' raw_thms =
   464       let
   465         val [[[raw_induct]], raw_inject, half_distinct] =
   466           unflat rules (map Drule.zero_var_indexes_list raw_thms);
   467             (*FIXME somehow dubious*)
   468       in
   469         ProofContext.theory_result
   470           (prove_rep_datatype config dt_names alt_names descr vs raw_inject half_distinct raw_induct)
   471         #-> after_qed
   472       end;
   473   in
   474     thy
   475     |> ProofContext.init
   476     |> Proof.theorem_i NONE after_qed' ((map o map) (rpair []) (flat rules))
   477   end;
   478 
   479 val rep_datatype = gen_rep_datatype Sign.cert_term;
   480 val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global default_config (K I);
   481 
   482 
   483 (** definitional introduction of datatypes **)
   484 
   485 fun gen_add_datatype prep_typ config new_type_names dts thy =
   486   let
   487     val _ = Theory.requires thy "Datatype" "datatype definitions";
   488 
   489     (* this theory is used just for parsing *)
   490     val tmp_thy = thy |>
   491       Theory.copy |>
   492       Sign.add_types (map (fn (tvs, tname, mx, _) =>
   493         (tname, length tvs, mx)) dts);
   494 
   495     val (tyvars, _, _, _)::_ = dts;
   496     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   497       let val full_tname = Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname)
   498       in (case duplicates (op =) tvs of
   499             [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   500                   else error ("Mutually recursive datatypes must have same type parameters")
   501           | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
   502               " : " ^ commas dups))
   503       end) dts);
   504     val dt_names = map fst new_dts;
   505 
   506     val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
   507       [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
   508 
   509     fun prep_dt_spec ((tvs, tname, mx, constrs), tname') (dts', constr_syntax, sorts, i) =
   510       let
   511         fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
   512           let
   513             val (cargs', sorts'') = Library.foldl (prep_typ tmp_thy) (([], sorts'), cargs);
   514             val _ = (case fold (curry OldTerm.add_typ_tfree_names) cargs' [] \\ tvs of
   515                 [] => ()
   516               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   517           in (constrs @ [(Sign.full_name_path tmp_thy tname'
   518                   (Binding.map_name (Syntax.const_name mx') cname),
   519                    map (dtyp_of_typ new_dts) cargs')],
   520               constr_syntax' @ [(cname, mx')], sorts'')
   521           end handle ERROR msg => cat_error msg
   522            ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
   523             " of datatype " ^ quote (Binding.str_of tname));
   524 
   525         val (constrs', constr_syntax', sorts') =
   526           fold prep_constr constrs ([], [], sorts)
   527 
   528       in
   529         case duplicates (op =) (map fst constrs') of
   530            [] =>
   531              (dts' @ [(i, (Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname),
   532                 map DtTFree tvs, constrs'))],
   533               constr_syntax @ [constr_syntax'], sorts', i + 1)
   534          | dups => error ("Duplicate constructors " ^ commas dups ^
   535              " in datatype " ^ quote (Binding.str_of tname))
   536       end;
   537 
   538     val (dts', constr_syntax, sorts', i) =
   539       fold prep_dt_spec (dts ~~ new_type_names) ([], [], [], 0);
   540     val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (tyvars \\ map fst sorts'));
   541     val dt_info = get_all thy;
   542     val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
   543     val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
   544       if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
   545       else raise exn;
   546 
   547     val _ = message config ("Constructing datatype(s) " ^ commas_quote new_type_names);
   548     val ((inject, distinct_rules, distinct_rewrites, distinct_entry, induct), thy') = thy |>
   549       DatatypeRepProofs.representation_proofs config dt_info new_type_names descr sorts
   550         types_syntax constr_syntax (mk_case_names_induct (flat descr));
   551   in
   552     derive_datatype_props config dt_names (SOME new_type_names) descr sorts
   553       induct inject (distinct_rules, distinct_rewrites, distinct_entry) thy'
   554   end;
   555 
   556 val add_datatype = gen_add_datatype cert_typ;
   557 val datatype_cmd = snd ooo gen_add_datatype read_typ default_config;
   558 
   559 
   560 (** package setup **)
   561 
   562 (* setup theory *)
   563 
   564 val setup =
   565   DatatypeRepProofs.distinctness_limit_setup #>
   566   simproc_setup #>
   567   trfun_setup #>
   568   DatatypeInterpretation.init;
   569 
   570 (* outer syntax *)
   571 
   572 local
   573 
   574 structure P = OuterParse and K = OuterKeyword
   575 
   576 fun prep_datatype_decls args =
   577   let
   578     val names = map
   579       (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
   580     val specs = map (fn ((((_, vs), t), mx), cons) =>
   581       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   582   in (names, specs) end;
   583 
   584 val parse_datatype_decl =
   585   (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_infix --
   586     (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
   587 
   588 val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
   589 
   590 in
   591 
   592 val _ =
   593   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   594     (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
   595 
   596 val _ =
   597   OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_goal
   598     (Scan.option (P.$$$ "(" |-- Scan.repeat1 P.name --| P.$$$ ")") -- Scan.repeat1 P.term
   599       >> (fn (alt_names, ts) => Toplevel.print
   600            o Toplevel.theory_to_proof (rep_datatype_cmd alt_names ts)));
   601 
   602 end;
   603 
   604 end;
   605