src/HOL/Tools/datatype_package.ML
author berghofe
Thu Oct 10 14:26:50 2002 +0200 (2002-10-10)
changeset 13641 63d1790a43ed
parent 13480 bb72bd43c6c3
child 14174 f3cafd2929d5
permissions -rw-r--r--
Reimplemented parts of datatype package dealing with datatypes involving
function types. Now also supports functions with more than one argument.
     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 (Tactic.prove sg [] [] eq_t (K
   353                                    (EVERY [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 (Tactic.prove sg [] [] eq_t (K
   356                                    (EVERY [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_simproc =
   371   Simplifier.simproc (Theory.sign_of HOL.thy) distinctN ["s = t"] 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 dt => is_rec_type dt andalso not (null (fst (strip_dtyp dt))))
   454         cargs) constrs) descr';
   455 
   456     (**** declare new types and constants ****)
   457 
   458     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
   459 
   460     val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
   461       map (fn ((_, cargs), (cname, mx)) =>
   462         (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
   463           (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
   464 
   465     val rec_result_Ts = map TFree (variantlist (replicate (length descr') "'t", used) ~~
   466       replicate (length descr') HOLogic.typeS);
   467 
   468     val reccomb_fn_Ts = flat (map (fn (i, (_, _, constrs)) =>
   469       map (fn (_, cargs) =>
   470         let
   471           val Ts = map (typ_of_dtyp descr' sorts) cargs;
   472           val recs = filter (is_rec_type o fst) (cargs ~~ Ts);
   473 
   474           fun mk_argT (dt, T) =
   475             binder_types T ---> nth_elem (body_index dt, 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       DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos);
   595   in
   596     (thy12,
   597      {distinct = distinct,
   598       inject = inject,
   599       exhaustion = exhaustion,
   600       rec_thms = rec_thms,
   601       case_thms = case_thms,
   602       split_thms = split_thms,
   603       induction = induct,
   604       size = size_thms,
   605       simps = simps})
   606   end;
   607 
   608 
   609 (******************* definitional introduction of datatypes *******************)
   610 
   611 fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
   612     case_names_induct case_names_exhausts thy =
   613   let
   614     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   615 
   616     val (thy2, inject, distinct, dist_rewrites, simproc_dists, induct) = thy |>
   617       DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
   618         types_syntax constr_syntax case_names_induct;
   619 
   620     val (thy3, casedist_thms) = DatatypeAbsProofs.prove_casedist_thms new_type_names descr
   621       sorts induct case_names_exhausts thy2;
   622     val (thy4, (reccomb_names, rec_thms)) = DatatypeAbsProofs.prove_primrec_thms
   623       flat_names new_type_names descr sorts dt_info inject dist_rewrites dist_ss induct thy3;
   624     val (thy6, (case_thms, case_names)) = DatatypeAbsProofs.prove_case_thms
   625       flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
   626     val (thy7, split_thms) = DatatypeAbsProofs.prove_split_thms new_type_names
   627       descr sorts inject dist_rewrites casedist_thms case_thms thy6;
   628     val (thy8, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   629       descr sorts casedist_thms thy7;
   630     val (thy9, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   631       descr sorts nchotomys case_thms thy8;
   632     val (thy10, weak_case_congs) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
   633       descr sorts thy9;
   634     val (thy11, size_thms) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
   635       descr sorts reccomb_names rec_thms thy10;
   636 
   637     val dt_infos = map (make_dt_info (flat descr) induct reccomb_names rec_thms)
   638       ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
   639         casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
   640 
   641     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   642 
   643     val thy12 = thy11 |>
   644       Theory.add_path (space_implode "_" new_type_names) |>
   645       add_rules simps case_thms size_thms rec_thms inject distinct
   646                 weak_case_congs (Simplifier.change_global_ss (op addcongs)) |> 
   647       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   648       add_cases_induct dt_infos induct |>
   649       Theory.parent_path |>
   650       (#1 o store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)) |>
   651       DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos);
   652   in
   653     (thy12,
   654      {distinct = distinct,
   655       inject = inject,
   656       exhaustion = casedist_thms,
   657       rec_thms = rec_thms,
   658       case_thms = case_thms,
   659       split_thms = split_thms,
   660       induction = induct,
   661       size = size_thms,
   662       simps = simps})
   663   end;
   664 
   665 
   666 (*********************** declare existing type as datatype *********************)
   667 
   668 fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
   669   let
   670     val _ = Theory.requires thy0 "Inductive" "datatype representations";
   671 
   672     fun app_thmss srcs thy = foldl_map (fn (thy, x) => apply_theorems x thy) (thy, srcs);
   673     fun app_thm src thy = apsnd Library.hd (apply_theorems [src] thy);
   674 
   675     val (((thy1, induction), inject), distinct) = thy0
   676       |> app_thmss raw_distinct
   677       |> apfst (app_thmss raw_inject)
   678       |> apfst (apfst (app_thm raw_induction));
   679     val sign = Theory.sign_of thy1;
   680 
   681     val induction' = freezeT induction;
   682 
   683     fun err t = error ("Ill-formed predicate in induction rule: " ^
   684       Sign.string_of_term sign t);
   685 
   686     fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
   687           ((tname, map dest_TFree Ts) handle TERM _ => err t)
   688       | get_typ t = err t;
   689 
   690     val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induction')));
   691     val new_type_names = if_none alt_names (map fst dtnames);
   692 
   693     fun get_constr t = (case Logic.strip_assums_concl t of
   694         _ $ (_ $ t') => (case head_of t' of
   695             Const (cname, cT) => (case strip_type cT of
   696                 (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
   697               | _ => err t)
   698           | _ => err t)
   699       | _ => err t);
   700 
   701     fun make_dt_spec [] _ _ = []
   702       | make_dt_spec ((tname, tvs)::dtnames') i constrs =
   703           let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
   704           in (i, (tname, map DtTFree tvs, map snd constrs'))::
   705             (make_dt_spec dtnames' (i + 1) constrs'')
   706           end;
   707 
   708     val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
   709     val sorts = add_term_tfrees (concl_of induction', []);
   710     val dt_info = get_datatypes thy1;
   711 
   712     val case_names_induct = mk_case_names_induct descr;
   713     val case_names_exhausts = mk_case_names_exhausts descr (map #1 dtnames);
   714     
   715 
   716     val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
   717 
   718     val (thy2, casedist_thms) = thy1 |>
   719       DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction
   720         case_names_exhausts;
   721     val (thy3, (reccomb_names, rec_thms)) = DatatypeAbsProofs.prove_primrec_thms
   722       false new_type_names [descr] sorts dt_info inject distinct dist_ss induction thy2;
   723     val (thy4, (case_thms, case_names)) = DatatypeAbsProofs.prove_case_thms false
   724       new_type_names [descr] sorts reccomb_names rec_thms thy3;
   725     val (thy5, split_thms) = DatatypeAbsProofs.prove_split_thms
   726       new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
   727     val (thy6, nchotomys) = DatatypeAbsProofs.prove_nchotomys new_type_names
   728       [descr] sorts casedist_thms thy5;
   729     val (thy7, case_congs) = DatatypeAbsProofs.prove_case_congs new_type_names
   730       [descr] sorts nchotomys case_thms thy6;
   731     val (thy8, weak_case_congs) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
   732       [descr] sorts thy7;
   733     val (thy9, size_thms) =
   734       if Sign.exists_stamp "NatArith" (Theory.sign_of thy8) then
   735         DatatypeAbsProofs.prove_size_thms false new_type_names
   736           [descr] sorts reccomb_names rec_thms thy8
   737       else (thy8, []);
   738 
   739     val (thy10, [induction']) = thy9 |>
   740       (#1 o store_thmss "inject" new_type_names inject) |>
   741       (#1 o store_thmss "distinct" new_type_names distinct) |>
   742       Theory.add_path (space_implode "_" new_type_names) |>
   743       PureThy.add_thms [(("induct", induction), [case_names_induct])];
   744 
   745     val dt_infos = map (make_dt_info descr induction' reccomb_names rec_thms)
   746       ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
   747         map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
   748 
   749     val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
   750 
   751     val thy11 = thy10 |>
   752       add_rules simps case_thms size_thms rec_thms inject distinct
   753                 weak_case_congs (Simplifier.change_global_ss (op addcongs)) |> 
   754       put_datatypes (foldr Symtab.update (dt_infos, dt_info)) |>
   755       add_cases_induct dt_infos induction' |>
   756       Theory.parent_path |>
   757       (#1 o store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)) |>
   758       DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos);
   759   in
   760     (thy11,
   761      {distinct = distinct,
   762       inject = inject,
   763       exhaustion = casedist_thms,
   764       rec_thms = rec_thms,
   765       case_thms = case_thms,
   766       split_thms = split_thms,
   767       induction = induction',
   768       size = size_thms,
   769       simps = simps})
   770   end;
   771 
   772 val rep_datatype = gen_rep_datatype IsarThy.apply_theorems;
   773 val rep_datatype_i = gen_rep_datatype IsarThy.apply_theorems_i;
   774 
   775 
   776 
   777 (******************************** add datatype ********************************)
   778 
   779 fun gen_add_datatype prep_typ flat_names new_type_names dts thy =
   780   let
   781     val _ = Theory.requires thy "Datatype_Universe" "datatype definitions";
   782 
   783     (* this theory is used just for parsing *)
   784 
   785     val tmp_thy = thy |>
   786       Theory.copy |>
   787       Theory.add_types (map (fn (tvs, tname, mx, _) =>
   788         (tname, length tvs, mx)) dts);
   789 
   790     val sign = Theory.sign_of tmp_thy;
   791 
   792     val (tyvars, _, _, _)::_ = dts;
   793     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   794       let val full_tname = Sign.full_name sign (Syntax.type_name tname mx)
   795       in (case duplicates tvs of
   796             [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   797                   else error ("Mutually recursive datatypes must have same type parameters")
   798           | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
   799               " : " ^ commas dups))
   800       end) dts);
   801 
   802     val _ = (case duplicates (map fst new_dts) @ duplicates new_type_names of
   803       [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
   804 
   805     fun prep_dt_spec ((dts', constr_syntax, sorts, i), (tvs, tname, mx, constrs)) =
   806       let
   807         fun prep_constr ((constrs, constr_syntax', sorts'), (cname, cargs, mx')) =
   808           let
   809             val (cargs', sorts'') = foldl (prep_typ sign) (([], sorts'), cargs);
   810             val _ = (case foldr add_typ_tfree_names (cargs', []) \\ tvs of
   811                 [] => ()
   812               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   813           in (constrs @ [((if flat_names then Sign.full_name sign else
   814                 Sign.full_name_path sign tname) (Syntax.const_name cname mx'),
   815                    map (dtyp_of_typ new_dts) cargs')],
   816               constr_syntax' @ [(cname, mx')], sorts'')
   817           end handle ERROR =>
   818             error ("The error above occured in constructor " ^ cname ^
   819               " of datatype " ^ tname);
   820 
   821         val (constrs', constr_syntax', sorts') =
   822           foldl prep_constr (([], [], sorts), constrs)
   823 
   824       in
   825         case duplicates (map fst constrs') of
   826            [] =>
   827              (dts' @ [(i, (Sign.full_name sign (Syntax.type_name tname mx),
   828                 map DtTFree tvs, constrs'))],
   829               constr_syntax @ [constr_syntax'], sorts', i + 1)
   830          | dups => error ("Duplicate constructors " ^ commas dups ^
   831              " in datatype " ^ tname)
   832       end;
   833 
   834     val (dts', constr_syntax, sorts', i) = foldl prep_dt_spec (([], [], [], 0), dts);
   835     val sorts = sorts' @ (map (rpair (Sign.defaultS sign)) (tyvars \\ map fst sorts'));
   836     val dt_info = get_datatypes thy;
   837     val (descr, _) = unfold_datatypes sign dts' sorts dt_info dts' i;
   838     val _ = check_nonempty descr;
   839 
   840     val descr' = flat descr;
   841     val case_names_induct = mk_case_names_induct descr';
   842     val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
   843   in
   844     (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
   845       flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
   846       case_names_induct case_names_exhausts thy
   847   end;
   848 
   849 val add_datatype_i = gen_add_datatype cert_typ;
   850 val add_datatype = gen_add_datatype read_typ;
   851 
   852 
   853 (** package setup **)
   854 
   855 (* setup theory *)
   856 
   857 val setup = [DatatypesData.init, Method.add_methods tactic_emulations] @ simproc_setup;
   858 
   859 
   860 (* outer syntax *)
   861 
   862 local structure P = OuterParse and K = OuterSyntax.Keyword in
   863 
   864 val datatype_decl =
   865   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
   866     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
   867 
   868 fun mk_datatype args =
   869   let
   870     val names = map (fn ((((None, _), t), _), _) => t | ((((Some t, _), _), _), _) => t) args;
   871     val specs = map (fn ((((_, vs), t), mx), cons) =>
   872       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   873   in #1 o add_datatype false names specs end;
   874 
   875 val datatypeP =
   876   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   877     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
   878 
   879 
   880 val rep_datatype_decl =
   881   Scan.option (Scan.repeat1 P.name) --
   882     Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 P.xthms1)) [[]] --
   883     Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 P.xthms1)) [[]] --
   884     (P.$$$ "induction" |-- P.!!! P.xthm);
   885 
   886 fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #1 o rep_datatype opt_ts dss iss ind;
   887 
   888 val rep_datatypeP =
   889   OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
   890     (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
   891 
   892 
   893 val _ = OuterSyntax.add_keywords ["distinct", "inject", "induction"];
   894 val _ = OuterSyntax.add_parsers [datatypeP, rep_datatypeP];
   895 
   896 end;
   897 
   898 
   899 end;
   900 
   901 structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
   902 open BasicDatatypePackage;