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