src/HOL/Tools/datatype_package.ML
author wenzelm
Fri Mar 10 01:16:19 2000 +0100 (2000-03-10)
changeset 8405 0255394a05da
parent 8325 80855ae484ce
child 8437 258281c43dea
permissions -rw-r--r--
add_cases_induct: produce proper case names;
     1 (*  Title:      HOL/Tools/datatype_package.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer
     4     Copyright   1998  TU Muenchen
     5 
     6 Datatype package for Isabelle/HOL.
     7 *)
     8 
     9 signature BASIC_DATATYPE_PACKAGE =
    10 sig
    11   val induct_tac : string -> int -> tactic
    12   val exhaust_tac : string -> int -> tactic
    13   val cases_tac : string -> int -> tactic
    14   val distinct_simproc : simproc
    15 end;
    16 
    17 signature DATATYPE_PACKAGE =
    18 sig
    19   include BASIC_DATATYPE_PACKAGE
    20   val quiet_mode : bool ref
    21   val add_datatype : bool -> string list -> (string list * bstring * mixfix *
    22     (bstring * string list * mixfix) list) list -> theory -> theory *
    23       {distinct : thm list list,
    24        inject : thm list list,
    25        exhaustion : thm list,
    26        rec_thms : thm list,
    27        case_thms : thm list list,
    28        split_thms : (thm * thm) list,
    29        induction : thm,
    30        size : thm list,
    31        simps : thm list}
    32   val add_datatype_i : bool -> string list -> (string list * bstring * mixfix *
    33     (bstring * typ list * mixfix) list) list -> theory -> theory *
    34       {distinct : thm list list,
    35        inject : thm list list,
    36        exhaustion : thm list,
    37        rec_thms : thm list,
    38        case_thms : thm list list,
    39        split_thms : (thm * thm) list,
    40        induction : thm,
    41        size : thm list,
    42        simps : thm list}
    43   val rep_datatype_i : string list option -> (thm * theory attribute list) list list ->
    44     (thm * theory attribute list) list list -> (thm * theory attribute list) -> theory -> theory *
    45       {distinct : thm list list,
    46        inject : thm list list,
    47        exhaustion : thm list,
    48        rec_thms : thm list,
    49        case_thms : thm list list,
    50        split_thms : (thm * thm) list,
    51        induction : thm,
    52        size : thm list,
    53        simps : thm list}
    54   val rep_datatype : string list option -> (xstring * Args.src list) list list ->
    55     (xstring * Args.src list) list list -> xstring * Args.src list -> theory -> theory *
    56       {distinct : thm list list,
    57        inject : thm list list,
    58        exhaustion : thm list,
    59        rec_thms : thm list,
    60        case_thms : thm list list,
    61        split_thms : (thm * thm) list,
    62        induction : thm,
    63        size : thm list,
    64        simps : thm list}
    65   val get_datatypes : theory -> DatatypeAux.datatype_info Symtab.table
    66   val print_datatypes : theory -> unit
    67   val datatype_info_sg : Sign.sg -> string -> DatatypeAux.datatype_info option
    68   val datatype_info : theory -> string -> DatatypeAux.datatype_info option
    69   val datatype_info_sg_err : Sign.sg -> string -> DatatypeAux.datatype_info
    70   val datatype_info_err : theory -> string -> DatatypeAux.datatype_info
    71   val constrs_of : theory -> string -> term list option
    72   val constrs_of_sg : Sign.sg -> string -> term list option
    73   val case_const_of : theory -> string -> term option
    74   val cases_of: Sign.sg -> string -> thm
    75   val setup: (theory -> theory) list
    76 end;
    77 
    78 structure DatatypePackage : DATATYPE_PACKAGE =
    79 struct
    80 
    81 open DatatypeAux;
    82 
    83 val quiet_mode = quiet_mode;
    84 
    85 
    86 (* data kind 'HOL/datatypes' *)
    87 
    88 structure DatatypesArgs =
    89 struct
    90   val name = "HOL/datatypes";
    91   type T = datatype_info Symtab.table;
    92 
    93   val empty = Symtab.empty;
    94   val copy = I;
    95   val prep_ext = I;
    96   val merge: T * T -> T = Symtab.merge (K true);
    97 
    98   fun print sg tab =
    99     Pretty.writeln (Pretty.strs ("datatypes:" ::
   100       map #1 (Sign.cond_extern_table sg Sign.typeK tab)));
   101 end;
   102 
   103 structure DatatypesData = TheoryDataFun(DatatypesArgs);
   104 val get_datatypes_sg = DatatypesData.get_sg;
   105 val get_datatypes = DatatypesData.get;
   106 val put_datatypes = DatatypesData.put;
   107 val print_datatypes = DatatypesData.print;
   108 
   109 
   110 (** theory information about datatypes **)
   111 
   112 fun datatype_info_sg sg name = Symtab.lookup (get_datatypes_sg sg, name);
   113 
   114 fun datatype_info_sg_err sg name = (case datatype_info_sg sg name of
   115       Some info => info
   116     | None => error ("Unknown datatype " ^ quote name));
   117 
   118 val datatype_info = datatype_info_sg o Theory.sign_of;
   119 
   120 fun datatype_info_err thy name = (case datatype_info thy name of
   121       Some info => info
   122     | None => error ("Unknown datatype " ^ quote name));
   123 
   124 fun constrs_of_sg sg tname = (case datatype_info_sg sg tname of
   125    Some {index, descr, ...} =>
   126      let val (_, _, constrs) = the (assoc (descr, index))
   127      in Some (map (fn (cname, _) => Const (cname, the (Sign.const_type sg cname))) constrs)
   128      end
   129  | _ => None);
   130 
   131 val constrs_of = constrs_of_sg o Theory.sign_of;
   132 
   133 val exhaustion_of = #exhaustion oo datatype_info_sg_err
   134 fun cases_of sg name = if name = HOLogic.boolN then case_split_thm else exhaustion_of sg name;
   135 
   136 fun case_const_of thy tname = (case datatype_info thy tname of
   137    Some {case_name, ...} => Some (Const (case_name, the (Sign.const_type
   138      (Theory.sign_of thy) case_name)))
   139  | _ => None);
   140 
   141 fun find_tname var Bi =
   142   let val frees = map dest_Free (term_frees Bi)
   143       val params = Logic.strip_params Bi;
   144   in case assoc (frees @ params, var) of
   145        None => error ("No such variable in subgoal: " ^ quote var)
   146      | Some(Type (tn, _)) => tn
   147      | _ => error ("Cannot determine type of " ^ quote var)
   148   end;
   149 
   150 fun infer_tname state i aterm =
   151   let
   152     val sign = Thm.sign_of_thm state;
   153     val (_, _, Bi, _) = Thm.dest_state (state, i)
   154     val params = Logic.strip_params Bi;   (*params of subgoal i*)
   155     val params = rev (rename_wrt_term Bi params);   (*as they are printed*)
   156     val (types, sorts) = types_sorts state;
   157     fun types' (a, ~1) = (case assoc (params, a) of None => types(a, ~1) | sm => sm)
   158       | types' ixn = types ixn;
   159     val (ct, _) = read_def_cterm (sign, types', sorts) [] false (aterm, TypeInfer.logicT);
   160   in case #T (rep_cterm ct) of
   161        Type (tn, _) => tn
   162      | _ => error ("Cannot determine type of " ^ quote aterm)
   163   end;
   164 
   165 (*Warn if the (induction) variable occurs Free among the premises, which
   166   usually signals a mistake.  But calls the tactic either way!*)
   167 fun occs_in_prems tacf vars =
   168   SUBGOAL (fn (Bi, i) =>
   169            (if  exists (fn Free (a, _) => a mem vars)
   170                       (foldr add_term_frees (#2 (strip_context Bi), []))
   171              then warning "Induction variable occurs also among premises!"
   172              else ();
   173             tacf i));
   174 
   175 (* generic induction tactic for datatypes *)
   176 
   177 fun induct_tac s i state =
   178   let
   179     val vars = Syntax.read_idents s;
   180     val (_, _, Bi, _) = dest_state (state, i);
   181     val {sign, ...} = rep_thm state;
   182     val tn = find_tname (hd vars) Bi;
   183     val {induction, ...} = datatype_info_sg_err sign tn;
   184     val ind_vnames = map (fn (_ $ Var (ixn, _)) =>
   185       implode (tl (explode (Syntax.string_of_vname ixn))))
   186         (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induction)));
   187     val insts = (ind_vnames ~~ vars) handle LIST _ =>
   188       error ("Induction rule for type " ^ tn ^ " has different number of variables")
   189   in
   190     occs_in_prems (res_inst_tac insts induction) vars i state
   191   end;
   192 
   193 
   194 (* generic exhaustion tactic for datatypes *)
   195 
   196 fun gen_exhaust_tac get_rule aterm i state =
   197   let
   198     val rule = get_rule (Thm.sign_of_thm state) (infer_tname state i aterm);
   199     val _ $ Var (ixn, _) $ _ = HOLogic.dest_Trueprop
   200       (hd (Logic.strip_assums_hyp (hd (Thm.prems_of rule))));
   201     val exh_vname = implode (tl (explode (Syntax.string_of_vname ixn)))
   202   in res_inst_tac [(exh_vname, aterm)] rule i state end;
   203 
   204 val exhaust_tac = gen_exhaust_tac exhaustion_of;
   205 val cases_tac = gen_exhaust_tac cases_of;
   206 
   207 
   208 (* add_cases_induct -- interface to induct method *)
   209 
   210 fun add_cases_induct infos =
   211   let
   212     fun proj _ 1 thm = thm
   213       | proj i n thm =
   214           (if i + 1 < n then (fn th => th RS conjunct1) else I)
   215             (Library.funpow i (fn th => th RS conjunct2) thm)
   216           |> Drule.standard;
   217 
   218     fun dt_recs (DtTFree _) = []
   219       | dt_recs (DtType (_, dts)) = flat (map dt_recs dts)
   220       | dt_recs (DtRec i) = [i];
   221 
   222     fun dt_cases (descr: descr) (_, args, constrs) =
   223       let
   224         fun the_bname i = Sign.base_name (#1 (the (assoc (descr, i))));
   225         val bnames = map the_bname (distinct (flat (map dt_recs args)));
   226       in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
   227 
   228     fun induct_cases descr =
   229       Term.variantlist (flat (map (dt_cases descr) (map #2 descr)), []);
   230 
   231     fun exhaust_cases descr i = dt_cases descr (the (assoc (descr, i)));
   232 
   233     fun add (ths, (name, {index, descr, induction, exhaustion, ...}: datatype_info)) =
   234       (("", proj index (length descr) induction),
   235         [RuleCases.case_names (induct_cases descr), InductMethod.induct_type_global name]) ::
   236       (("", exhaustion), [RuleCases.case_names (exhaust_cases descr index),
   237         InductMethod.cases_type_global name]) :: ths;
   238   in PureThy.add_thms (foldl add ([], infos)) end;
   239 
   240 
   241 
   242 (**** simplification procedure for showing distinctness of constructors ****)
   243 
   244 fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
   245   | stripT p = p;
   246 
   247 fun stripC (i, f $ x) = stripC (i + 1, f)
   248   | stripC p = p;
   249 
   250 val distinctN = "constr_distinct";
   251 
   252 exception ConstrDistinct of term;
   253 
   254 fun distinct_proc sg _ (t as Const ("op =", _) $ t1 $ t2) =
   255   (case (stripC (0, t1), stripC (0, t2)) of
   256      ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
   257          (case (stripT (0, T1), stripT (0, T2)) of
   258             ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
   259                 if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
   260                    (case (constrs_of_sg sg tname1) of
   261                       Some constrs => let val cnames = map (fst o dest_Const) constrs
   262                         in if cname1 mem cnames andalso cname2 mem cnames then
   263                              let val eq_t = Logic.mk_equals (t, Const ("False", HOLogic.boolT));
   264                                  val eq_ct = cterm_of sg eq_t;
   265                                  val Datatype_thy = theory "Datatype";
   266                                  val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
   267                                    map (get_thm Datatype_thy)
   268                                      ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"]
   269                              in (case (#distinct (datatype_info_sg_err sg tname1)) of
   270                                  QuickAndDirty => Some (Thm.invoke_oracle
   271                                    Datatype_thy distinctN (sg, ConstrDistinct eq_t))
   272                                | FewConstrs thms => Some (prove_goalw_cterm [] eq_ct (K
   273                                    [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
   274                                     atac 2, resolve_tac thms 1, etac FalseE 1]))
   275                                | ManyConstrs (thm, ss) => Some (prove_goalw_cterm [] eq_ct (K
   276                                    [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
   277                                     full_simp_tac ss 1,
   278                                     REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   279                                     eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
   280                                     etac FalseE 1])))
   281                              end
   282                            else None
   283                         end
   284                     | None => None)
   285                 else None
   286           | _ => None)
   287    | _ => None)
   288   | distinct_proc sg _ _ = None;
   289 
   290 val distinct_pats = [Thm.read_cterm (Theory.sign_of HOL.thy) ("s = t", HOLogic.termT)];
   291 val distinct_simproc = mk_simproc distinctN distinct_pats distinct_proc;
   292 
   293 val dist_ss = HOL_ss addsimprocs [distinct_simproc];
   294 
   295 val simproc_setup =
   296   [Theory.add_oracle (distinctN, fn (_, ConstrDistinct t) => t),
   297    fn thy => (simpset_ref_of thy := simpset_of thy addsimprocs [distinct_simproc]; thy)];
   298 
   299 
   300 (* prepare types *)
   301 
   302 fun read_typ sign ((Ts, sorts), str) =
   303   let
   304     val T = Type.no_tvars (Sign.read_typ (sign, (curry assoc)
   305       (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
   306   in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
   307 
   308 fun cert_typ sign ((Ts, sorts), raw_T) =
   309   let
   310     val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
   311       TYPE (msg, _, _) => error msg;
   312     val sorts' = add_typ_tfrees (T, sorts)
   313   in (Ts @ [T],
   314       case duplicates (map fst sorts') of
   315          [] => sorts'
   316        | dups => error ("Inconsistent sort constraints for " ^ commas dups))
   317   end;
   318 
   319 
   320 (**** make datatype info ****)
   321 
   322 fun make_dt_info descr induct reccomb_names rec_thms
   323   ((((((((i, (_, (tname, _, _))), case_name), case_thms),
   324     exhaustion_thm), distinct_thm), inject), nchotomy), case_cong) = (tname,
   325       {index = i,
   326        descr = descr,
   327        rec_names = reccomb_names,
   328        rec_rewrites = rec_thms,
   329        case_name = case_name,
   330        case_rewrites = case_thms,
   331        induction = induct,
   332        exhaustion = exhaustion_thm,
   333        distinct = distinct_thm,
   334        inject = inject,
   335        nchotomy = nchotomy,
   336        case_cong = case_cong});
   337 
   338 fun store_clasimp thy (cla, simp) =
   339   (claset_ref_of thy := cla; simpset_ref_of thy := simp);
   340 
   341 
   342 (********************* axiomatic introduction of datatypes ********************)
   343 
   344 fun add_and_get_axioms label tnames ts thy =
   345   foldr (fn ((tname, t), (thy', axs)) =>
   346     let
   347       val thy'' = thy' |>
   348         Theory.add_path tname |>
   349         PureThy.add_axioms_i [((label, t), [])];
   350       val ax = PureThy.get_thm thy'' label
   351     in (Theory.parent_path thy'', ax::axs)
   352     end) (tnames ~~ ts, (thy, []));
   353 
   354 fun add_and_get_axiomss label tnames tss thy =
   355   foldr (fn ((tname, ts), (thy', axss)) =>
   356     let
   357       val thy'' = thy' |>
   358         Theory.add_path tname |>
   359         PureThy.add_axiomss_i [((label, ts), [])];
   360       val axs = PureThy.get_thms thy'' label
   361     in (Theory.parent_path thy'', axs::axss)
   362     end) (tnames ~~ tss, (thy, []));
   363 
   364 fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
   365   let
   366     val descr' = flat descr;
   367     val recTs = get_rec_types descr' sorts;
   368     val used = foldr add_typ_tfree_names (recTs, []);
   369     val newTs = take (length (hd descr), recTs);
   370 
   371     val no_size = exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists
   372       (fn (DtType ("fun", [_, DtRec _])) => true | _ => false) cargs) constrs) descr';
   373 
   374     (**** declare new types and constants ****)
   375 
   376     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
   377 
   378     val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
   379       map (fn ((_, cargs), (cname, mx)) =>
   380         (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   381           (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
   382 
   383     val rec_result_Ts = map TFree (variantlist (replicate (length descr') "'t", used) ~~
   384       replicate (length descr') HOLogic.termS);
   385 
   386     val reccomb_fn_Ts = flat (map (fn (i, (_, _, constrs)) =>
   387       map (fn (_, cargs) =>
   388         let
   389           val Ts = map (typ_of_dtyp descr' sorts) cargs;
   390           val recs = filter (is_rec_type o fst) (cargs ~~ Ts);
   391 
   392           fun mk_argT (DtRec k, _) = nth_elem (k, rec_result_Ts)
   393             | mk_argT (DtType ("fun", [_, DtRec k]), Type ("fun", [T, _])) =
   394                T --> nth_elem (k, rec_result_Ts);
   395 
   396           val argTs = Ts @ map mk_argT recs
   397         in argTs ---> nth_elem (i, rec_result_Ts)
   398         end) constrs) descr');
   399 
   400     val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
   401     val reccomb_names = if length descr' = 1 then [big_reccomb_name] else
   402       (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
   403         (1 upto (length descr')));
   404 
   405     val big_size_name = space_implode "_" new_type_names ^ "_size";
   406     val size_names = if length (flat (tl descr)) = 1 then [big_size_name] else
   407       map (fn i => big_size_name ^ "_" ^ string_of_int i)
   408         (1 upto length (flat (tl descr)));
   409 
   410     val freeT = TFree (variant used "'t", HOLogic.termS);
   411     val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
   412       map (fn (_, cargs) =>
   413         let val Ts = map (typ_of_dtyp descr' sorts) cargs
   414         in Ts ---> freeT end) constrs) (hd descr);
   415 
   416     val case_names = map (fn s => (s ^ "_case")) new_type_names;
   417 
   418     val thy2' = thy |>
   419 
   420       (** new types **)
   421 
   422       curry (foldr (fn (((name, mx), tvs), thy') => thy' |>
   423           TypedefPackage.add_typedecls [(name, tvs, mx)]))
   424         (types_syntax ~~ tyvars) |>
   425       add_path flat_names (space_implode "_" new_type_names) |>
   426 
   427       (** primrec combinators **)
   428 
   429       Theory.add_consts_i (map (fn ((name, T), T') =>
   430         (name, reccomb_fn_Ts @ [T] ---> T', NoSyn))
   431           (reccomb_names ~~ recTs ~~ rec_result_Ts)) |>
   432 
   433       (** case combinators **)
   434 
   435       Theory.add_consts_i (map (fn ((name, T), Ts) =>
   436         (name, Ts @ [T] ---> freeT, NoSyn))
   437           (case_names ~~ newTs ~~ case_fn_Ts)) |>
   438       Theory.add_trrules_i (DatatypeProp.make_case_trrules new_type_names descr);
   439 
   440     val reccomb_names' = map (Sign.intern_const (Theory.sign_of thy2')) reccomb_names;
   441     val case_names' = map (Sign.intern_const (Theory.sign_of thy2')) case_names;
   442 
   443     val thy2 = thy2' |>
   444 
   445       (** size functions **)
   446 
   447       (if no_size then I else Theory.add_consts_i (map (fn (s, T) =>
   448         (Sign.base_name s, T --> HOLogic.natT, NoSyn))
   449           (size_names ~~ drop (length (hd descr), recTs)))) |>
   450 
   451       (** constructors **)
   452 
   453       parent_path flat_names |>
   454       curry (foldr (fn (((((_, (_, _, constrs)), T), tname),
   455         constr_syntax'), thy') => thy' |>
   456           add_path flat_names tname |>
   457             Theory.add_consts_i (map (fn ((_, cargs), (cname, mx)) =>
   458               (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   459                 (constrs ~~ constr_syntax')) |>
   460           parent_path flat_names))
   461             (hd descr ~~ newTs ~~ new_type_names ~~ constr_syntax);
   462 
   463     (**** introduction of axioms ****)
   464 
   465     val rec_axs = DatatypeProp.make_primrecs new_type_names descr sorts thy2;
   466     val size_axs = if no_size then [] else DatatypeProp.make_size new_type_names descr sorts thy2;
   467 
   468     val (thy3, inject) = thy2 |>
   469       Theory.add_path (space_implode "_" new_type_names) |>
   470       PureThy.add_axioms_i [(("induct", DatatypeProp.make_ind descr sorts), [])] |>
   471       PureThy.add_axiomss_i [(("recs", rec_axs), [])] |>
   472       (if no_size then I else PureThy.add_axiomss_i [(("size", size_axs), [])]) |>
   473       Theory.parent_path |>
   474       add_and_get_axiomss "inject" new_type_names
   475         (DatatypeProp.make_injs descr sorts);
   476     val induct = get_thm thy3 "induct";
   477     val rec_thms = get_thms thy3 "recs";
   478     val size_thms = if no_size then [] else get_thms thy3 "size";
   479     val (thy4, distinct) = add_and_get_axiomss "distinct" new_type_names
   480       (DatatypeProp.make_distincts new_type_names descr sorts thy3) thy3;
   481     val (thy5, exhaustion) = add_and_get_axioms "exhaust" new_type_names
   482       (DatatypeProp.make_casedists descr sorts) thy4;
   483     val (thy6, case_thms) = add_and_get_axiomss "cases" new_type_names
   484       (DatatypeProp.make_cases new_type_names descr sorts thy5) thy5;
   485     val (split_ts, split_asm_ts) = ListPair.unzip
   486       (DatatypeProp.make_splits new_type_names descr sorts thy6);
   487     val (thy7, split) = add_and_get_axioms "split" new_type_names split_ts thy6;
   488     val (thy8, split_asm) = add_and_get_axioms "split_asm" new_type_names
   489       split_asm_ts thy7;
   490     val (thy9, nchotomys) = add_and_get_axioms "nchotomy" new_type_names
   491       (DatatypeProp.make_nchotomys descr sorts) thy8;
   492     val (thy10, case_congs) = add_and_get_axioms "case_cong" new_type_names
   493       (DatatypeProp.make_case_congs new_type_names descr sorts thy9) thy9;
   494 
   495     val dt_infos = map (make_dt_info descr' induct reccomb_names' rec_thms)
   496       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names' ~~ case_thms ~~
   497         exhaustion ~~ replicate (length (hd descr)) QuickAndDirty ~~ inject ~~
   498           nchotomys ~~ case_congs);
   499 
   500     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   501 
   502     val thy11 = thy10 |>
   503       Theory.add_path (space_implode "_" new_type_names) |>
   504       PureThy.add_thmss [(("simps", simps), [])] |>
   505       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   506       add_cases_induct dt_infos |>
   507       Theory.parent_path;
   508 
   509     val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
   510       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   511       addIffs flat (inject @ distinct));
   512 
   513   in
   514     (thy11,
   515      {distinct = distinct,
   516       inject = inject,
   517       exhaustion = exhaustion,
   518       rec_thms = rec_thms,
   519       case_thms = case_thms,
   520       split_thms = split ~~ split_asm,
   521       induction = induct,
   522       size = size_thms,
   523       simps = simps})
   524   end;
   525 
   526 
   527 (******************* definitional introduction of datatypes *******************)
   528 
   529 fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
   530   let
   531     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   532 
   533     val (thy2, inject, distinct, dist_rewrites, simproc_dists, induct) = thy |>
   534       DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
   535         types_syntax constr_syntax;
   536 
   537     val (thy3, casedist_thms) =
   538       DatatypeAbsProofs.prove_casedist_thms new_type_names descr sorts induct thy2;
   539     val (thy4, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
   540       flat_names new_type_names descr sorts dt_info inject dist_rewrites dist_ss induct thy3;
   541     val (thy6, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms
   542       flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
   543     val (thy7, split_thms) = DatatypeAbsProofs.prove_split_thms new_type_names
   544       descr sorts inject dist_rewrites casedist_thms case_thms thy6;
   545     val (thy8, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   546       descr sorts casedist_thms thy7;
   547     val (thy9, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   548       descr sorts nchotomys case_thms thy8;
   549     val (thy10, size_thms) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
   550       descr sorts reccomb_names rec_thms thy9;
   551 
   552     val dt_infos = map (make_dt_info (flat descr) induct reccomb_names rec_thms)
   553       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
   554         casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs);
   555 
   556     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   557 
   558     val thy11 = thy10 |>
   559       Theory.add_path (space_implode "_" new_type_names) |>
   560       PureThy.add_thmss [(("simps", simps), [])] |>
   561       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   562       add_cases_induct dt_infos |>
   563       Theory.parent_path;
   564 
   565     val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
   566       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   567       addIffs flat (inject @ distinct));
   568 
   569   in
   570     (thy11,
   571      {distinct = distinct,
   572       inject = inject,
   573       exhaustion = casedist_thms,
   574       rec_thms = rec_thms,
   575       case_thms = case_thms,
   576       split_thms = split_thms,
   577       induction = induct,
   578       size = size_thms,
   579       simps = simps})
   580   end;
   581 
   582 
   583 (*********************** declare existing type as datatype *********************)
   584 
   585 fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
   586   let
   587     fun app_thmss srcs thy = foldl_map (fn (thy, x) => apply_theorems x thy) (thy, srcs);
   588     fun app_thm src thy = apsnd Library.hd (apply_theorems [src] thy);
   589 
   590     val (((thy1, induction), inject), distinct) = thy0
   591       |> app_thmss raw_distinct
   592       |> apfst (app_thmss raw_inject)
   593       |> apfst (apfst (app_thm raw_induction));
   594     val sign = Theory.sign_of thy1;
   595 
   596     val induction' = freezeT induction;
   597 
   598     fun err t = error ("Ill-formed predicate in induction rule: " ^
   599       Sign.string_of_term sign t);
   600 
   601     fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
   602           ((tname, map dest_TFree Ts) handle TERM _ => err t)
   603       | get_typ t = err t;
   604 
   605     val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induction')));
   606     val new_type_names = if_none alt_names (map fst dtnames);
   607 
   608     fun get_constr t = (case Logic.strip_assums_concl t of
   609         _ $ (_ $ t') => (case head_of t' of
   610             Const (cname, cT) => (case strip_type cT of
   611                 (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
   612               | _ => err t)
   613           | _ => err t)
   614       | _ => err t);
   615 
   616     fun make_dt_spec [] _ _ = []
   617       | make_dt_spec ((tname, tvs)::dtnames') i constrs =
   618           let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
   619           in (i, (tname, map DtTFree tvs, map snd constrs'))::
   620             (make_dt_spec dtnames' (i + 1) constrs'')
   621           end;
   622 
   623     val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
   624     val sorts = add_term_tfrees (concl_of induction', []);
   625     val dt_info = get_datatypes thy1;
   626 
   627     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   628 
   629     val (thy2, casedist_thms) = thy1 |>
   630       DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction;
   631     val (thy3, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
   632       false new_type_names [descr] sorts dt_info inject distinct dist_ss induction thy2;
   633     val (thy4, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms false
   634       new_type_names [descr] sorts reccomb_names rec_thms thy3;
   635     val (thy5, split_thms) = DatatypeAbsProofs.prove_split_thms
   636       new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
   637     val (thy6, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   638       [descr] sorts casedist_thms thy5;
   639     val (thy7, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   640       [descr] sorts nchotomys case_thms thy6;
   641     val (thy8, size_thms) =
   642       if exists (equal "Arith") (Sign.stamp_names_of (Theory.sign_of thy7)) then
   643         DatatypeAbsProofs.prove_size_thms false new_type_names
   644           [descr] sorts reccomb_names rec_thms thy7
   645       else (thy7, []);
   646 
   647     val dt_infos = map (make_dt_info descr induction reccomb_names rec_thms)
   648       ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~
   649         casedist_thms ~~ map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs);
   650 
   651     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   652 
   653     val thy9 = thy8 |>
   654       store_thmss "inject" new_type_names inject |>
   655       store_thmss "distinct" new_type_names distinct |>
   656       Theory.add_path (space_implode "_" new_type_names) |>
   657       PureThy.add_thms [(("induct", induction), [])] |>
   658       PureThy.add_thmss [(("simps", simps), [])] |>
   659       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   660       add_cases_induct dt_infos |>
   661       Theory.parent_path;
   662 
   663     val _ = store_clasimp thy9 ((claset_of thy9, simpset_of thy9)
   664       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   665       addIffs flat (inject @ distinct));
   666 
   667   in
   668     (thy9,
   669      {distinct = distinct,
   670       inject = inject,
   671       exhaustion = casedist_thms,
   672       rec_thms = rec_thms,
   673       case_thms = case_thms,
   674       split_thms = split_thms,
   675       induction = induction,
   676       size = size_thms,
   677       simps = simps})
   678   end;
   679 
   680 val rep_datatype = gen_rep_datatype IsarThy.apply_theorems;
   681 val rep_datatype_i = gen_rep_datatype IsarThy.apply_theorems_i;
   682 
   683 
   684 (******************************** add datatype ********************************)
   685 
   686 fun gen_add_datatype prep_typ flat_names new_type_names dts thy =
   687   let
   688     val _ = Theory.requires thy "Datatype" "datatype definitions";
   689 
   690     (* this theory is used just for parsing *)
   691 
   692     val tmp_thy = thy |>
   693       Theory.copy |>
   694       Theory.add_types (map (fn (tvs, tname, mx, _) =>
   695         (tname, length tvs, mx)) dts);
   696 
   697     val sign = Theory.sign_of tmp_thy;
   698 
   699     val (tyvars, _, _, _)::_ = dts;
   700     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   701       let val full_tname = Sign.full_name sign (Syntax.type_name tname mx)
   702       in (case duplicates tvs of
   703             [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   704                   else error ("Mutually recursive datatypes must have same type parameters")
   705           | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
   706               " : " ^ commas dups))
   707       end) dts);
   708 
   709     val _ = (case duplicates (map fst new_dts) @ duplicates new_type_names of
   710       [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
   711 
   712     fun prep_dt_spec ((dts', constr_syntax, sorts, i), (tvs, tname, mx, constrs)) =
   713       let
   714         fun prep_constr ((constrs, constr_syntax', sorts'), (cname, cargs, mx')) =
   715           let
   716             val (cargs', sorts'') = foldl (prep_typ sign) (([], sorts'), cargs);
   717             val _ = (case foldr add_typ_tfree_names (cargs', []) \\ tvs of
   718                 [] => ()
   719               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   720           in (constrs @ [((if flat_names then Sign.full_name sign else
   721                 Sign.full_name_path sign tname) (Syntax.const_name cname mx'),
   722                    map (dtyp_of_typ new_dts) cargs')],
   723               constr_syntax' @ [(cname, mx')], sorts'')
   724           end handle ERROR =>
   725             error ("The error above occured in constructor " ^ cname ^
   726               " of datatype " ^ tname);
   727 
   728         val (constrs', constr_syntax', sorts') =
   729           foldl prep_constr (([], [], sorts), constrs)
   730 
   731       in
   732         case duplicates (map fst constrs') of
   733            [] =>
   734              (dts' @ [(i, (Sign.full_name sign (Syntax.type_name tname mx),
   735                 map DtTFree tvs, constrs'))],
   736               constr_syntax @ [constr_syntax'], sorts', i + 1)
   737          | dups => error ("Duplicate constructors " ^ commas dups ^
   738              " in datatype " ^ tname)
   739       end;
   740 
   741     val (dts', constr_syntax, sorts', i) = foldl prep_dt_spec (([], [], [], 0), dts);
   742     val sorts = sorts' @ (map (rpair (Sign.defaultS sign)) (tyvars \\ map fst sorts'));
   743     val dt_info = get_datatypes thy;
   744     val (descr, _) = unfold_datatypes sign dts' sorts dt_info dts' i;
   745     val _ = check_nonempty descr;
   746 
   747   in
   748     (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
   749       flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy
   750   end;
   751 
   752 val add_datatype_i = gen_add_datatype cert_typ;
   753 val add_datatype = gen_add_datatype read_typ;
   754 
   755 
   756 (** package setup **)
   757 
   758 (* setup theory *)
   759 
   760 val setup = [DatatypesData.init] @ simproc_setup;
   761 
   762 
   763 (* outer syntax *)
   764 
   765 local structure P = OuterParse and K = OuterSyntax.Keyword in
   766 
   767 val datatype_decl =
   768   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
   769     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix --| P.marg_comment));
   770 
   771 fun mk_datatype args =
   772   let
   773     val names = map (fn ((((None, _), t), _), _) => t | ((((Some t, _), _), _), _) => t) args;
   774     val specs = map (fn ((((_, vs), t), mx), cons) => (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   775   in #1 o add_datatype false names specs end;
   776 
   777 val datatypeP =
   778   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   779     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
   780 
   781 
   782 val rep_datatype_decl =
   783   Scan.option (Scan.repeat1 P.name) --
   784     Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 P.xthms1)) [] --
   785     Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 P.xthms1)) [] --
   786     (P.$$$ "induction" |-- P.!!! P.xthm);
   787 
   788 fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #1 o rep_datatype opt_ts dss iss ind;
   789 
   790 val rep_datatypeP =
   791   OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
   792     (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
   793 
   794 
   795 val _ = OuterSyntax.add_keywords ["distinct", "inject", "induction"];
   796 val _ = OuterSyntax.add_parsers [datatypeP, rep_datatypeP];
   797 
   798 end;
   799 
   800 
   801 end;
   802 
   803 structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
   804 open BasicDatatypePackage;