src/HOL/Tools/datatype_package.ML
author wenzelm
Sun Feb 27 15:31:40 2000 +0100 (2000-02-27)
changeset 8306 9855f1801d2b
parent 8279 3453f73fad71
child 8325 80855ae484ce
permissions -rw-r--r--
HOLogic.dest_conj;
add_cases_induct: induct_method setup;
     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 *)
   209 
   210 fun add_cases_induct infos =
   211   let
   212     fun add (ths, (name, {induction, exhaustion, ...}: datatype_info)) =
   213       (("", induction), [InductMethod.induct_type_global name]) ::
   214        (("", exhaustion), [InductMethod.cases_type_global name]) :: ths;
   215   in PureThy.add_thms (foldl add ([], infos)) end;
   216 
   217 
   218 (**** simplification procedure for showing distinctness of constructors ****)
   219 
   220 fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
   221   | stripT p = p;
   222 
   223 fun stripC (i, f $ x) = stripC (i + 1, f)
   224   | stripC p = p;
   225 
   226 val distinctN = "constr_distinct";
   227 
   228 exception ConstrDistinct of term;
   229 
   230 fun distinct_proc sg _ (t as Const ("op =", _) $ t1 $ t2) =
   231   (case (stripC (0, t1), stripC (0, t2)) of
   232      ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
   233          (case (stripT (0, T1), stripT (0, T2)) of
   234             ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
   235                 if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
   236                    (case (constrs_of_sg sg tname1) of
   237                       Some constrs => let val cnames = map (fst o dest_Const) constrs
   238                         in if cname1 mem cnames andalso cname2 mem cnames then
   239                              let val eq_t = Logic.mk_equals (t, Const ("False", HOLogic.boolT));
   240                                  val eq_ct = cterm_of sg eq_t;
   241                                  val Datatype_thy = theory "Datatype";
   242                                  val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
   243                                    map (get_thm Datatype_thy)
   244                                      ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"]
   245                              in (case (#distinct (datatype_info_sg_err sg tname1)) of
   246                                  QuickAndDirty => Some (Thm.invoke_oracle
   247                                    Datatype_thy distinctN (sg, ConstrDistinct eq_t))
   248                                | FewConstrs thms => Some (prove_goalw_cterm [] eq_ct (K
   249                                    [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
   250                                     atac 2, resolve_tac thms 1, etac FalseE 1]))
   251                                | ManyConstrs (thm, ss) => Some (prove_goalw_cterm [] eq_ct (K
   252                                    [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
   253                                     full_simp_tac ss 1,
   254                                     REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   255                                     eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
   256                                     etac FalseE 1])))
   257                              end
   258                            else None
   259                         end
   260                     | None => None)
   261                 else None
   262           | _ => None)
   263    | _ => None)
   264   | distinct_proc sg _ _ = None;
   265 
   266 val distinct_pats = [Thm.read_cterm (Theory.sign_of HOL.thy) ("s = t", HOLogic.termT)];
   267 val distinct_simproc = mk_simproc distinctN distinct_pats distinct_proc;
   268 
   269 val dist_ss = HOL_ss addsimprocs [distinct_simproc];
   270 
   271 val simproc_setup =
   272   [Theory.add_oracle (distinctN, fn (_, ConstrDistinct t) => t),
   273    fn thy => (simpset_ref_of thy := simpset_of thy addsimprocs [distinct_simproc]; thy)];
   274 
   275 
   276 (* prepare types *)
   277 
   278 fun read_typ sign ((Ts, sorts), str) =
   279   let
   280     val T = Type.no_tvars (Sign.read_typ (sign, (curry assoc)
   281       (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
   282   in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
   283 
   284 fun cert_typ sign ((Ts, sorts), raw_T) =
   285   let
   286     val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
   287       TYPE (msg, _, _) => error msg;
   288     val sorts' = add_typ_tfrees (T, sorts)
   289   in (Ts @ [T],
   290       case duplicates (map fst sorts') of
   291          [] => sorts'
   292        | dups => error ("Inconsistent sort constraints for " ^ commas dups))
   293   end;
   294 
   295 
   296 (**** make datatype info ****)
   297 
   298 fun make_dt_info descr induct reccomb_names rec_thms
   299   ((((((((i, (_, (tname, _, _))), case_name), case_thms),
   300     exhaustion_thm), distinct_thm), inject), nchotomy), case_cong) = (tname,
   301       {index = i,
   302        descr = descr,
   303        rec_names = reccomb_names,
   304        rec_rewrites = rec_thms,
   305        case_name = case_name,
   306        case_rewrites = case_thms,
   307        induction = induct,
   308        exhaustion = exhaustion_thm,
   309        distinct = distinct_thm,
   310        inject = inject,
   311        nchotomy = nchotomy,
   312        case_cong = case_cong});
   313 
   314 fun store_clasimp thy (cla, simp) =
   315   (claset_ref_of thy := cla; simpset_ref_of thy := simp);
   316 
   317 
   318 (********************* axiomatic introduction of datatypes ********************)
   319 
   320 fun add_and_get_axioms label tnames ts thy =
   321   foldr (fn ((tname, t), (thy', axs)) =>
   322     let
   323       val thy'' = thy' |>
   324         Theory.add_path tname |>
   325         PureThy.add_axioms_i [((label, t), [])];
   326       val ax = PureThy.get_thm thy'' label
   327     in (Theory.parent_path thy'', ax::axs)
   328     end) (tnames ~~ ts, (thy, []));
   329 
   330 fun add_and_get_axiomss label tnames tss thy =
   331   foldr (fn ((tname, ts), (thy', axss)) =>
   332     let
   333       val thy'' = thy' |>
   334         Theory.add_path tname |>
   335         PureThy.add_axiomss_i [((label, ts), [])];
   336       val axs = PureThy.get_thms thy'' label
   337     in (Theory.parent_path thy'', axs::axss)
   338     end) (tnames ~~ tss, (thy, []));
   339 
   340 fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
   341   let
   342     val descr' = flat descr;
   343     val recTs = get_rec_types descr' sorts;
   344     val used = foldr add_typ_tfree_names (recTs, []);
   345     val newTs = take (length (hd descr), recTs);
   346 
   347     val no_size = exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists
   348       (fn (DtType ("fun", [_, DtRec _])) => true | _ => false) cargs) constrs) descr';
   349 
   350     (**** declare new types and constants ****)
   351 
   352     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
   353 
   354     val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
   355       map (fn ((_, cargs), (cname, mx)) =>
   356         (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   357           (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
   358 
   359     val rec_result_Ts = map TFree (variantlist (replicate (length descr') "'t", used) ~~
   360       replicate (length descr') HOLogic.termS);
   361 
   362     val reccomb_fn_Ts = flat (map (fn (i, (_, _, constrs)) =>
   363       map (fn (_, cargs) =>
   364         let
   365           val Ts = map (typ_of_dtyp descr' sorts) cargs;
   366           val recs = filter (is_rec_type o fst) (cargs ~~ Ts);
   367 
   368           fun mk_argT (DtRec k, _) = nth_elem (k, rec_result_Ts)
   369             | mk_argT (DtType ("fun", [_, DtRec k]), Type ("fun", [T, _])) =
   370                T --> nth_elem (k, rec_result_Ts);
   371 
   372           val argTs = Ts @ map mk_argT recs
   373         in argTs ---> nth_elem (i, rec_result_Ts)
   374         end) constrs) descr');
   375 
   376     val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
   377     val reccomb_names = if length descr' = 1 then [big_reccomb_name] else
   378       (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
   379         (1 upto (length descr')));
   380 
   381     val big_size_name = space_implode "_" new_type_names ^ "_size";
   382     val size_names = if length (flat (tl descr)) = 1 then [big_size_name] else
   383       map (fn i => big_size_name ^ "_" ^ string_of_int i)
   384         (1 upto length (flat (tl descr)));
   385 
   386     val freeT = TFree (variant used "'t", HOLogic.termS);
   387     val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
   388       map (fn (_, cargs) =>
   389         let val Ts = map (typ_of_dtyp descr' sorts) cargs
   390         in Ts ---> freeT end) constrs) (hd descr);
   391 
   392     val case_names = map (fn s => (s ^ "_case")) new_type_names;
   393 
   394     val thy2' = thy |>
   395 
   396       (** new types **)
   397 
   398       curry (foldr (fn (((name, mx), tvs), thy') => thy' |>
   399           TypedefPackage.add_typedecls [(name, tvs, mx)]))
   400         (types_syntax ~~ tyvars) |>
   401       add_path flat_names (space_implode "_" new_type_names) |>
   402 
   403       (** primrec combinators **)
   404 
   405       Theory.add_consts_i (map (fn ((name, T), T') =>
   406         (name, reccomb_fn_Ts @ [T] ---> T', NoSyn))
   407           (reccomb_names ~~ recTs ~~ rec_result_Ts)) |>
   408 
   409       (** case combinators **)
   410 
   411       Theory.add_consts_i (map (fn ((name, T), Ts) =>
   412         (name, Ts @ [T] ---> freeT, NoSyn))
   413           (case_names ~~ newTs ~~ case_fn_Ts)) |>
   414       Theory.add_trrules_i (DatatypeProp.make_case_trrules new_type_names descr);
   415 
   416     val reccomb_names' = map (Sign.intern_const (Theory.sign_of thy2')) reccomb_names;
   417     val case_names' = map (Sign.intern_const (Theory.sign_of thy2')) case_names;
   418 
   419     val thy2 = thy2' |>
   420 
   421       (** size functions **)
   422 
   423       (if no_size then I else Theory.add_consts_i (map (fn (s, T) =>
   424         (Sign.base_name s, T --> HOLogic.natT, NoSyn))
   425           (size_names ~~ drop (length (hd descr), recTs)))) |>
   426 
   427       (** constructors **)
   428 
   429       parent_path flat_names |>
   430       curry (foldr (fn (((((_, (_, _, constrs)), T), tname),
   431         constr_syntax'), thy') => thy' |>
   432           add_path flat_names tname |>
   433             Theory.add_consts_i (map (fn ((_, cargs), (cname, mx)) =>
   434               (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   435                 (constrs ~~ constr_syntax')) |>
   436           parent_path flat_names))
   437             (hd descr ~~ newTs ~~ new_type_names ~~ constr_syntax);
   438 
   439     (**** introduction of axioms ****)
   440 
   441     val rec_axs = DatatypeProp.make_primrecs new_type_names descr sorts thy2;
   442     val size_axs = if no_size then [] else DatatypeProp.make_size new_type_names descr sorts thy2;
   443 
   444     val (thy3, inject) = thy2 |>
   445       Theory.add_path (space_implode "_" new_type_names) |>
   446       PureThy.add_axioms_i [(("induct", DatatypeProp.make_ind descr sorts), [])] |>
   447       PureThy.add_axiomss_i [(("recs", rec_axs), [])] |>
   448       (if no_size then I else PureThy.add_axiomss_i [(("size", size_axs), [])]) |>
   449       Theory.parent_path |>
   450       add_and_get_axiomss "inject" new_type_names
   451         (DatatypeProp.make_injs descr sorts);
   452     val induct = get_thm thy3 "induct";
   453     val rec_thms = get_thms thy3 "recs";
   454     val size_thms = if no_size then [] else get_thms thy3 "size";
   455     val (thy4, distinct) = add_and_get_axiomss "distinct" new_type_names
   456       (DatatypeProp.make_distincts new_type_names descr sorts thy3) thy3;
   457     val (thy5, exhaustion) = add_and_get_axioms "exhaust" new_type_names
   458       (DatatypeProp.make_casedists descr sorts) thy4;
   459     val (thy6, case_thms) = add_and_get_axiomss "cases" new_type_names
   460       (DatatypeProp.make_cases new_type_names descr sorts thy5) thy5;
   461     val (split_ts, split_asm_ts) = ListPair.unzip
   462       (DatatypeProp.make_splits new_type_names descr sorts thy6);
   463     val (thy7, split) = add_and_get_axioms "split" new_type_names split_ts thy6;
   464     val (thy8, split_asm) = add_and_get_axioms "split_asm" new_type_names
   465       split_asm_ts thy7;
   466     val (thy9, nchotomys) = add_and_get_axioms "nchotomy" new_type_names
   467       (DatatypeProp.make_nchotomys descr sorts) thy8;
   468     val (thy10, case_congs) = add_and_get_axioms "case_cong" new_type_names
   469       (DatatypeProp.make_case_congs new_type_names descr sorts thy9) thy9;
   470     
   471     val dt_infos = map (make_dt_info descr' induct reccomb_names' rec_thms)
   472       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names' ~~ case_thms ~~
   473         exhaustion ~~ replicate (length (hd descr)) QuickAndDirty ~~ inject ~~
   474           nchotomys ~~ case_congs);
   475 
   476     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   477 
   478     val thy11 = thy10 |>
   479       Theory.add_path (space_implode "_" new_type_names) |>
   480       PureThy.add_thmss [(("simps", simps), [])] |>
   481       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   482       add_cases_induct dt_infos |>
   483       Theory.parent_path;
   484 
   485     val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
   486       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   487       addIffs flat (inject @ distinct));
   488 
   489   in
   490     (thy11,
   491      {distinct = distinct,
   492       inject = inject,
   493       exhaustion = exhaustion,
   494       rec_thms = rec_thms,
   495       case_thms = case_thms,
   496       split_thms = split ~~ split_asm,
   497       induction = induct,
   498       size = size_thms,
   499       simps = simps})
   500   end;
   501 
   502 
   503 (******************* definitional introduction of datatypes *******************)
   504 
   505 fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy =
   506   let
   507     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   508 
   509     val (thy2, inject, distinct, dist_rewrites, simproc_dists, induct) = thy |>
   510       DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
   511         types_syntax constr_syntax;
   512 
   513     val (thy3, casedist_thms) =
   514       DatatypeAbsProofs.prove_casedist_thms new_type_names descr sorts induct thy2;
   515     val (thy4, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
   516       flat_names new_type_names descr sorts dt_info inject dist_rewrites dist_ss induct thy3;
   517     val (thy6, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms
   518       flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
   519     val (thy7, split_thms) = DatatypeAbsProofs.prove_split_thms new_type_names
   520       descr sorts inject dist_rewrites casedist_thms case_thms thy6;
   521     val (thy8, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   522       descr sorts casedist_thms thy7;
   523     val (thy9, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   524       descr sorts nchotomys case_thms thy8;
   525     val (thy10, size_thms) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
   526       descr sorts reccomb_names rec_thms thy9;
   527 
   528     val dt_infos = map (make_dt_info (flat descr) induct reccomb_names rec_thms)
   529       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
   530         casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs);
   531 
   532     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   533 
   534     val thy11 = thy10 |>
   535       Theory.add_path (space_implode "_" new_type_names) |>
   536       PureThy.add_thmss [(("simps", simps), [])] |>
   537       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   538       add_cases_induct dt_infos |>
   539       Theory.parent_path;
   540 
   541     val _ = store_clasimp thy11 ((claset_of thy11, simpset_of thy11)
   542       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   543       addIffs flat (inject @ distinct));
   544 
   545   in
   546     (thy11,
   547      {distinct = distinct,
   548       inject = inject,
   549       exhaustion = casedist_thms,
   550       rec_thms = rec_thms,
   551       case_thms = case_thms,
   552       split_thms = split_thms,
   553       induction = induct,
   554       size = size_thms,
   555       simps = simps})
   556   end;
   557 
   558 
   559 (*********************** declare existing type as datatype *********************)
   560 
   561 fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
   562   let
   563     fun app_thmss srcs thy = foldl_map (fn (thy, x) => apply_theorems x thy) (thy, srcs);
   564     fun app_thm src thy = apsnd Library.hd (apply_theorems [src] thy);
   565 
   566     val (((thy1, induction), inject), distinct) = thy0
   567       |> app_thmss raw_distinct
   568       |> apfst (app_thmss raw_inject)
   569       |> apfst (apfst (app_thm raw_induction));
   570     val sign = Theory.sign_of thy1;
   571 
   572     val induction' = freezeT induction;
   573 
   574     fun err t = error ("Ill-formed predicate in induction rule: " ^
   575       Sign.string_of_term sign t);
   576 
   577     fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
   578           ((tname, map dest_TFree Ts) handle TERM _ => err t)
   579       | get_typ t = err t;
   580 
   581     val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induction')));
   582     val new_type_names = if_none alt_names (map fst dtnames);
   583 
   584     fun get_constr t = (case Logic.strip_assums_concl t of
   585         _ $ (_ $ t') => (case head_of t' of
   586             Const (cname, cT) => (case strip_type cT of
   587                 (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
   588               | _ => err t)
   589           | _ => err t)
   590       | _ => err t);
   591 
   592     fun make_dt_spec [] _ _ = []
   593       | make_dt_spec ((tname, tvs)::dtnames') i constrs =
   594           let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
   595           in (i, (tname, map DtTFree tvs, map snd constrs'))::
   596             (make_dt_spec dtnames' (i + 1) constrs'')
   597           end;
   598 
   599     val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
   600     val sorts = add_term_tfrees (concl_of induction', []);
   601     val dt_info = get_datatypes thy1;
   602 
   603     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   604 
   605     val (thy2, casedist_thms) = thy1 |>
   606       DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction;
   607     val (thy3, reccomb_names, rec_thms) = DatatypeAbsProofs.prove_primrec_thms
   608       false new_type_names [descr] sorts dt_info inject distinct dist_ss induction thy2;
   609     val (thy4, case_names, case_thms) = DatatypeAbsProofs.prove_case_thms false
   610       new_type_names [descr] sorts reccomb_names rec_thms thy3;
   611     val (thy5, split_thms) = DatatypeAbsProofs.prove_split_thms
   612       new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
   613     val (thy6, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   614       [descr] sorts casedist_thms thy5;
   615     val (thy7, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   616       [descr] sorts nchotomys case_thms thy6;
   617     val (thy8, size_thms) =
   618       if exists (equal "Arith") (Sign.stamp_names_of (Theory.sign_of thy7)) then
   619         DatatypeAbsProofs.prove_size_thms false new_type_names
   620           [descr] sorts reccomb_names rec_thms thy7
   621       else (thy7, []);
   622 
   623     val dt_infos = map (make_dt_info descr induction reccomb_names rec_thms)
   624       ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~
   625         casedist_thms ~~ map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs);
   626 
   627     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   628 
   629     val thy9 = thy8 |>
   630       store_thmss "inject" new_type_names inject |>
   631       store_thmss "distinct" new_type_names distinct |>
   632       Theory.add_path (space_implode "_" new_type_names) |>
   633       PureThy.add_thms [(("induct", induction), [])] |>
   634       PureThy.add_thmss [(("simps", simps), [])] |>
   635       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   636       add_cases_induct dt_infos |>
   637       Theory.parent_path;
   638 
   639     val _ = store_clasimp thy9 ((claset_of thy9, simpset_of thy9)
   640       addsimps2 flat case_thms addsimps2 size_thms addsimps2 rec_thms
   641       addIffs flat (inject @ distinct));
   642 
   643   in
   644     (thy9,
   645      {distinct = distinct,
   646       inject = inject,
   647       exhaustion = casedist_thms,
   648       rec_thms = rec_thms,
   649       case_thms = case_thms,
   650       split_thms = split_thms,
   651       induction = induction,
   652       size = size_thms,
   653       simps = simps})
   654   end;
   655 
   656 val rep_datatype = gen_rep_datatype IsarThy.apply_theorems;
   657 val rep_datatype_i = gen_rep_datatype IsarThy.apply_theorems_i;
   658 
   659 
   660 (******************************** add datatype ********************************)
   661 
   662 fun gen_add_datatype prep_typ flat_names new_type_names dts thy =
   663   let
   664     val _ = Theory.requires thy "Datatype" "datatype definitions";
   665 
   666     (* this theory is used just for parsing *)
   667 
   668     val tmp_thy = thy |>
   669       Theory.copy |>
   670       Theory.add_types (map (fn (tvs, tname, mx, _) =>
   671         (tname, length tvs, mx)) dts);
   672 
   673     val sign = Theory.sign_of tmp_thy;
   674 
   675     val (tyvars, _, _, _)::_ = dts;
   676     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   677       let val full_tname = Sign.full_name sign (Syntax.type_name tname mx)
   678       in (case duplicates tvs of
   679             [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   680                   else error ("Mutually recursive datatypes must have same type parameters")
   681           | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
   682               " : " ^ commas dups))
   683       end) dts);
   684 
   685     val _ = (case duplicates (map fst new_dts) @ duplicates new_type_names of
   686       [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
   687 
   688     fun prep_dt_spec ((dts', constr_syntax, sorts, i), (tvs, tname, mx, constrs)) =
   689       let
   690         fun prep_constr ((constrs, constr_syntax', sorts'), (cname, cargs, mx')) =
   691           let
   692             val (cargs', sorts'') = foldl (prep_typ sign) (([], sorts'), cargs);
   693             val _ = (case foldr add_typ_tfree_names (cargs', []) \\ tvs of
   694                 [] => ()
   695               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   696           in (constrs @ [((if flat_names then Sign.full_name sign else
   697                 Sign.full_name_path sign tname) (Syntax.const_name cname mx'),
   698                    map (dtyp_of_typ new_dts) cargs')],
   699               constr_syntax' @ [(cname, mx')], sorts'')
   700           end handle ERROR =>
   701             error ("The error above occured in constructor " ^ cname ^
   702               " of datatype " ^ tname);
   703 
   704         val (constrs', constr_syntax', sorts') =
   705           foldl prep_constr (([], [], sorts), constrs)
   706 
   707       in 
   708         case duplicates (map fst constrs') of
   709            [] =>
   710              (dts' @ [(i, (Sign.full_name sign (Syntax.type_name tname mx),
   711                 map DtTFree tvs, constrs'))],
   712               constr_syntax @ [constr_syntax'], sorts', i + 1)
   713          | dups => error ("Duplicate constructors " ^ commas dups ^
   714              " in datatype " ^ tname)
   715       end;
   716 
   717     val (dts', constr_syntax, sorts', i) = foldl prep_dt_spec (([], [], [], 0), dts);
   718     val sorts = sorts' @ (map (rpair (Sign.defaultS sign)) (tyvars \\ map fst sorts'));
   719     val dt_info = get_datatypes thy;
   720     val (descr, _) = unfold_datatypes sign dts' sorts dt_info dts' i;
   721     val _ = check_nonempty descr;
   722 
   723   in
   724     (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
   725       flat_names new_type_names descr sorts types_syntax constr_syntax dt_info thy
   726   end;
   727 
   728 val add_datatype_i = gen_add_datatype cert_typ;
   729 val add_datatype = gen_add_datatype read_typ;
   730 
   731 
   732 (** package setup **)
   733 
   734 (* setup theory *)
   735 
   736 val setup = [DatatypesData.init] @ simproc_setup;
   737 
   738 
   739 (* outer syntax *)
   740 
   741 local structure P = OuterParse and K = OuterSyntax.Keyword in
   742 
   743 val datatype_decl =
   744   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
   745     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix --| P.marg_comment));
   746 
   747 fun mk_datatype args =
   748   let
   749     val names = map (fn ((((None, _), t), _), _) => t | ((((Some t, _), _), _), _) => t) args;
   750     val specs = map (fn ((((_, vs), t), mx), cons) => (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   751   in #1 o add_datatype false names specs end;
   752 
   753 val datatypeP =
   754   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   755     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
   756 
   757 
   758 val rep_datatype_decl =
   759   Scan.option (Scan.repeat1 P.name) --
   760     Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 P.xthms1)) [] --
   761     Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 P.xthms1)) [] --
   762     (P.$$$ "induction" |-- P.!!! P.xthm);
   763 
   764 fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #1 o rep_datatype opt_ts dss iss ind;
   765 
   766 val rep_datatypeP =
   767   OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
   768     (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
   769 
   770 
   771 val _ = OuterSyntax.add_keywords ["distinct", "inject", "induction"];
   772 val _ = OuterSyntax.add_parsers [datatypeP, rep_datatypeP];
   773 
   774 end;
   775 
   776 
   777 end;
   778 
   779 structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
   780 open BasicDatatypePackage;