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