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