src/HOL/Tools/datatype_package.ML
author haftmann
Sat Sep 15 19:27:44 2007 +0200 (2007-09-15)
changeset 24589 d3fca349736c
parent 24423 ae9cd0e92423
child 24624 b8383b1bbae3
permissions -rw-r--r--
clarified class interfaces and internals
berghofe@5177
     1
(*  Title:      HOL/Tools/datatype_package.ML
berghofe@5177
     2
    ID:         $Id$
wenzelm@11539
     3
    Author:     Stefan Berghofer, TU Muenchen
berghofe@5177
     4
wenzelm@6360
     5
Datatype package for Isabelle/HOL.
berghofe@5177
     6
*)
berghofe@5177
     7
wenzelm@6360
     8
signature BASIC_DATATYPE_PACKAGE =
wenzelm@6360
     9
sig
wenzelm@6360
    10
  val induct_tac : string -> int -> tactic
nipkow@9747
    11
  val induct_thm_tac : thm -> string -> int -> tactic
wenzelm@8437
    12
  val case_tac : string -> int -> tactic
berghofe@7015
    13
  val distinct_simproc : simproc
wenzelm@6360
    14
end;
wenzelm@6360
    15
berghofe@5177
    16
signature DATATYPE_PACKAGE =
berghofe@5177
    17
sig
wenzelm@6360
    18
  include BASIC_DATATYPE_PACKAGE
berghofe@5661
    19
  val quiet_mode : bool ref
berghofe@5661
    20
  val add_datatype : bool -> string list -> (string list * bstring * mixfix *
haftmann@18008
    21
    (bstring * string list * mixfix) list) list -> theory ->
berghofe@5177
    22
      {distinct : thm list list,
berghofe@5177
    23
       inject : thm list list,
berghofe@5177
    24
       exhaustion : thm list,
berghofe@5177
    25
       rec_thms : thm list,
berghofe@5177
    26
       case_thms : thm list list,
berghofe@5177
    27
       split_thms : (thm * thm) list,
berghofe@5177
    28
       induction : thm,
berghofe@5177
    29
       size : thm list,
haftmann@18008
    30
       simps : thm list} * theory
berghofe@14887
    31
  val add_datatype_i : bool -> bool -> string list -> (string list * bstring * mixfix *
haftmann@18008
    32
    (bstring * typ list * mixfix) list) list -> theory ->
berghofe@5177
    33
      {distinct : thm list list,
berghofe@5177
    34
       inject : thm list list,
berghofe@5177
    35
       exhaustion : thm list,
berghofe@5177
    36
       rec_thms : thm list,
berghofe@5177
    37
       case_thms : thm list list,
berghofe@5177
    38
       split_thms : (thm * thm) list,
berghofe@5177
    39
       induction : thm,
berghofe@5177
    40
       size : thm list,
haftmann@18008
    41
       simps : thm list} * theory
wenzelm@18728
    42
  val rep_datatype_i : string list option -> (thm list * attribute list) list list ->
wenzelm@18728
    43
    (thm list * attribute list) list list -> (thm list * attribute list) ->
haftmann@18008
    44
    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,
haftmann@18008
    53
       simps : thm list} * theory
wenzelm@15703
    54
  val rep_datatype : string list option -> (thmref * Attrib.src list) list list ->
haftmann@18008
    55
    (thmref * Attrib.src list) list list -> thmref * Attrib.src list -> 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,
haftmann@18008
    64
       simps : thm list} * theory
berghofe@5177
    65
  val get_datatypes : theory -> DatatypeAux.datatype_info Symtab.table
haftmann@19346
    66
  val get_datatype : theory -> string -> DatatypeAux.datatype_info option
haftmann@19346
    67
  val the_datatype : theory -> string -> DatatypeAux.datatype_info
berghofe@22777
    68
  val datatype_of_constr : theory -> string -> DatatypeAux.datatype_info option
berghofe@22777
    69
  val datatype_of_case : theory -> string -> DatatypeAux.datatype_info option
haftmann@19346
    70
  val get_datatype_spec : theory -> string -> ((string * sort) list * (string * typ list) list) option
haftmann@19346
    71
  val get_datatype_constrs : theory -> string -> (string * typ) list option
wenzelm@6441
    72
  val print_datatypes : theory -> unit
berghofe@22777
    73
  val make_case :  Proof.context -> bool -> string list -> term ->
berghofe@22777
    74
    (term * term) list -> term * (term * (int * bool)) list
berghofe@22777
    75
  val strip_case: Proof.context -> bool ->
berghofe@22777
    76
    term -> (term * (term * term) list) option
wenzelm@18708
    77
  val setup: theory -> theory
berghofe@5177
    78
end;
berghofe@5177
    79
berghofe@5177
    80
structure DatatypePackage : DATATYPE_PACKAGE =
berghofe@5177
    81
struct
berghofe@5177
    82
berghofe@5177
    83
open DatatypeAux;
berghofe@5177
    84
berghofe@5661
    85
val quiet_mode = quiet_mode;
berghofe@5661
    86
wenzelm@6360
    87
wenzelm@22846
    88
(* theory data *)
berghofe@5177
    89
wenzelm@16430
    90
structure DatatypesData = TheoryDataFun
wenzelm@22846
    91
(
berghofe@22777
    92
  type T =
berghofe@22777
    93
    {types: datatype_info Symtab.table,
berghofe@22777
    94
     constrs: datatype_info Symtab.table,
berghofe@22777
    95
     cases: datatype_info Symtab.table};
berghofe@5177
    96
berghofe@22777
    97
  val empty =
berghofe@22777
    98
    {types = Symtab.empty, constrs = Symtab.empty, cases = Symtab.empty};
wenzelm@6556
    99
  val copy = I;
wenzelm@16430
   100
  val extend = I;
berghofe@22777
   101
  fun merge _
berghofe@22777
   102
    ({types = types1, constrs = constrs1, cases = cases1},
berghofe@22777
   103
     {types = types2, constrs = constrs2, cases = cases2}) =
berghofe@22777
   104
    {types = Symtab.merge (K true) (types1, types2),
berghofe@22777
   105
     constrs = Symtab.merge (K true) (constrs1, constrs2),
berghofe@22777
   106
     cases = Symtab.merge (K true) (cases1, cases2)};
wenzelm@22846
   107
);
berghofe@5177
   108
berghofe@22777
   109
val get_datatypes = #types o DatatypesData.get;
berghofe@22777
   110
val map_datatypes = DatatypesData.map;
wenzelm@22846
   111
wenzelm@22846
   112
fun print_datatypes thy =
wenzelm@22846
   113
  Pretty.writeln (Pretty.strs ("datatypes:" ::
wenzelm@22846
   114
    map #1 (NameSpace.extern_table (Sign.type_space thy, get_datatypes thy))));
berghofe@5177
   115
berghofe@5177
   116
berghofe@5177
   117
(** theory information about datatypes **)
berghofe@5177
   118
berghofe@22777
   119
fun put_dt_infos (dt_infos : (string * datatype_info) list) =
berghofe@22777
   120
  map_datatypes (fn {types, constrs, cases} =>
berghofe@22777
   121
    {types = fold Symtab.update dt_infos types,
berghofe@22777
   122
     constrs = fold Symtab.update
berghofe@22777
   123
       (maps (fn (_, info as {descr, index, ...}) => map (rpair info o fst)
berghofe@22777
   124
          (#3 (the (AList.lookup op = descr index)))) dt_infos) constrs,
berghofe@22777
   125
     cases = fold Symtab.update
berghofe@22777
   126
       (map (fn (_, info as {case_name, ...}) => (case_name, info)) dt_infos)
berghofe@22777
   127
       cases});
berghofe@22777
   128
haftmann@19346
   129
val get_datatype = Symtab.lookup o get_datatypes;
berghofe@5177
   130
haftmann@19346
   131
fun the_datatype thy name = (case get_datatype thy name of
skalberg@15531
   132
      SOME info => info
skalberg@15531
   133
    | NONE => error ("Unknown datatype " ^ quote name));
berghofe@5177
   134
berghofe@22777
   135
val datatype_of_constr = Symtab.lookup o #constrs o DatatypesData.get;
berghofe@22777
   136
val datatype_of_case = Symtab.lookup o #cases o DatatypesData.get;
berghofe@22777
   137
haftmann@19346
   138
fun get_datatype_descr thy dtco =
haftmann@19346
   139
  get_datatype thy dtco
haftmann@19346
   140
  |> Option.map (fn info as { descr, index, ... } => 
haftmann@19346
   141
       (info, (((fn SOME (_, dtys, cos) => (dtys, cos)) o AList.lookup (op =) descr) index)));
berghofe@7015
   142
haftmann@19346
   143
fun get_datatype_spec thy dtco =
haftmann@18518
   144
  let
haftmann@19346
   145
    fun mk_cons typ_of_dtyp (co, tys) =
haftmann@19346
   146
      (co, map typ_of_dtyp tys);
haftmann@19346
   147
    fun mk_dtyp ({ sorts = raw_sorts, descr, ... } : DatatypeAux.datatype_info, (dtys, cos)) =
haftmann@19346
   148
      let
haftmann@19346
   149
        val sorts = map ((fn v => (v, (the o AList.lookup (op =) raw_sorts) v))
haftmann@19346
   150
          o DatatypeAux.dest_DtTFree) dtys;
haftmann@19346
   151
        val typ_of_dtyp = DatatypeAux.typ_of_dtyp descr sorts;
haftmann@19346
   152
        val tys = map typ_of_dtyp dtys;
haftmann@19346
   153
      in (sorts, map (mk_cons typ_of_dtyp) cos) end;
haftmann@19346
   154
  in Option.map mk_dtyp (get_datatype_descr thy dtco) end;
haftmann@18518
   155
haftmann@19346
   156
fun get_datatype_constrs thy dtco =
haftmann@19346
   157
  case get_datatype_spec thy dtco
haftmann@19346
   158
   of SOME (sorts, cos) =>
haftmann@19346
   159
        let
haftmann@19346
   160
          fun subst (v, sort) = TVar ((v, 0), sort);
haftmann@19346
   161
          fun subst_ty (TFree v) = subst v
haftmann@19346
   162
            | subst_ty ty = ty;
haftmann@19346
   163
          val dty = Type (dtco, map subst sorts);
haftmann@19346
   164
          fun mk_co (co, tys) = (co, map (Term.map_atyps subst_ty) tys ---> dty);
haftmann@19346
   165
        in SOME (map mk_co cos) end
haftmann@19346
   166
    | NONE => NONE;
haftmann@18518
   167
berghofe@5177
   168
fun find_tname var Bi =
berghofe@5177
   169
  let val frees = map dest_Free (term_frees Bi)
berghofe@14412
   170
      val params = rename_wrt_term Bi (Logic.strip_params Bi);
haftmann@17521
   171
  in case AList.lookup (op =) (frees @ params) var of
skalberg@15531
   172
       NONE => error ("No such variable in subgoal: " ^ quote var)
skalberg@15531
   173
     | SOME(Type (tn, _)) => tn
berghofe@5177
   174
     | _ => error ("Cannot determine type of " ^ quote var)
berghofe@5177
   175
  end;
berghofe@5177
   176
wenzelm@8279
   177
fun infer_tname state i aterm =
berghofe@5177
   178
  let
wenzelm@22578
   179
    val sign = Thm.theory_of_thm state;
wenzelm@8279
   180
    val (_, _, Bi, _) = Thm.dest_state (state, i)
berghofe@5177
   181
    val params = Logic.strip_params Bi;   (*params of subgoal i*)
berghofe@5177
   182
    val params = rev (rename_wrt_term Bi params);   (*as they are printed*)
berghofe@5177
   183
    val (types, sorts) = types_sorts state;
haftmann@17521
   184
    fun types' (a, ~1) = (case AList.lookup (op =) params a of NONE => types(a, ~1) | sm => sm)
berghofe@5177
   185
      | types' ixn = types ixn;
wenzelm@22709
   186
    val ([ct], _) = Thm.read_def_cterms (sign, types', sorts) [] false [(aterm, dummyT)];
berghofe@5177
   187
  in case #T (rep_cterm ct) of
berghofe@5177
   188
       Type (tn, _) => tn
berghofe@5177
   189
     | _ => error ("Cannot determine type of " ^ quote aterm)
berghofe@5177
   190
  end;
berghofe@5177
   191
berghofe@5177
   192
(*Warn if the (induction) variable occurs Free among the premises, which
berghofe@5177
   193
  usually signals a mistake.  But calls the tactic either way!*)
wenzelm@8405
   194
fun occs_in_prems tacf vars =
berghofe@5177
   195
  SUBGOAL (fn (Bi, i) =>
haftmann@21045
   196
           (if exists (fn (a, _) => member (op =) vars a)
haftmann@21045
   197
                      (fold Term.add_frees (#2 (strip_context Bi)) [])
wenzelm@8405
   198
             then warning "Induction variable occurs also among premises!"
wenzelm@8405
   199
             else ();
wenzelm@8405
   200
            tacf i));
berghofe@5177
   201
wenzelm@8689
   202
berghofe@5177
   203
(* generic induction tactic for datatypes *)
berghofe@5177
   204
wenzelm@8689
   205
local
wenzelm@8689
   206
skalberg@15531
   207
fun prep_var (Var (ixn, _), SOME x) = SOME (ixn, x)
skalberg@15531
   208
  | prep_var _ = NONE;
wenzelm@8689
   209
haftmann@21045
   210
fun prep_inst (concl, xs) = (*exception Library.UnequalLengths*)
wenzelm@11725
   211
  let val vs = InductAttrib.vars_of concl
haftmann@21045
   212
  in map_filter prep_var (Library.drop (length vs - length xs, vs) ~~ xs) end;
wenzelm@8689
   213
wenzelm@8689
   214
in
wenzelm@8689
   215
paulson@18751
   216
fun gen_induct_tac inst_tac (varss, opt_rule) i state = 
paulson@18751
   217
  SUBGOAL (fn (Bi,_) =>
berghofe@5177
   218
  let
wenzelm@8672
   219
    val (rule, rule_name) =
paulson@18751
   220
      case opt_rule of
haftmann@21045
   221
          SOME r => (r, "Induction rule")
haftmann@21045
   222
        | NONE =>
haftmann@21045
   223
            let val tn = find_tname (hd (map_filter I (flat varss))) Bi
wenzelm@22598
   224
                val thy = Thm.theory_of_thm state
wenzelm@22598
   225
            in (#induction (the_datatype thy tn), "Induction rule for type " ^ tn) 
haftmann@21045
   226
            end
wenzelm@11725
   227
    val concls = HOLogic.dest_concls (Thm.concl_of rule);
haftmann@21045
   228
    val insts = maps prep_inst (concls ~~ varss) handle Library.UnequalLengths =>
wenzelm@8689
   229
      error (rule_name ^ " has different numbers of variables");
paulson@18751
   230
  in occs_in_prems (inst_tac insts rule) (map #2 insts) i end)
paulson@18751
   231
  i state;
wenzelm@8689
   232
ballarin@14174
   233
fun induct_tac s =
berghofe@15444
   234
  gen_induct_tac Tactic.res_inst_tac'
haftmann@21045
   235
    (map (single o SOME) (Syntax.read_idents s), NONE);
wenzelm@8689
   236
nipkow@9747
   237
fun induct_thm_tac th s =
berghofe@15444
   238
  gen_induct_tac Tactic.res_inst_tac'
skalberg@15531
   239
    ([map SOME (Syntax.read_idents s)], SOME th);
nipkow@9747
   240
wenzelm@8689
   241
end;
berghofe@5177
   242
wenzelm@8279
   243
wenzelm@8437
   244
(* generic case tactic for datatypes *)
berghofe@5177
   245
ballarin@14174
   246
fun case_inst_tac inst_tac t rule i state =
wenzelm@8672
   247
  let
wenzelm@8672
   248
    val _ $ Var (ixn, _) $ _ = HOLogic.dest_Trueprop
wenzelm@8672
   249
      (hd (Logic.strip_assums_hyp (hd (Thm.prems_of rule))));
berghofe@15444
   250
  in inst_tac [(ixn, t)] rule i state end;
wenzelm@8672
   251
skalberg@15531
   252
fun gen_case_tac inst_tac (t, SOME rule) i state =
ballarin@14174
   253
      case_inst_tac inst_tac t rule i state
skalberg@15531
   254
  | gen_case_tac inst_tac (t, NONE) i state =
wenzelm@8672
   255
      let val tn = infer_tname state i t in
berghofe@15444
   256
        if tn = HOLogic.boolN then inst_tac [(("P", 0), t)] case_split_thm i state
ballarin@14174
   257
        else case_inst_tac inst_tac t
wenzelm@22578
   258
               (#exhaustion (the_datatype (Thm.theory_of_thm state) tn))
ballarin@14174
   259
               i state
berghofe@14471
   260
      end handle THM _ => Seq.empty;
wenzelm@8672
   261
skalberg@15531
   262
fun case_tac t = gen_case_tac Tactic.res_inst_tac' (t, NONE);
wenzelm@8672
   263
wenzelm@8279
   264
wenzelm@8279
   265
wenzelm@8541
   266
(** Isar tactic emulations **)
wenzelm@8541
   267
wenzelm@8672
   268
local
wenzelm@8672
   269
wenzelm@8689
   270
val rule_spec = Scan.lift (Args.$$$ "rule" -- Args.$$$ ":");
wenzelm@18988
   271
val opt_rule = Scan.option (rule_spec |-- Attrib.thm);
wenzelm@8689
   272
wenzelm@15703
   273
val varss =
wenzelm@15703
   274
  Args.and_list (Scan.repeat (Scan.unless rule_spec (Scan.lift (Args.maybe Args.name))));
wenzelm@8672
   275
wenzelm@20328
   276
val inst_tac = RuleInsts.bires_inst_tac false;
ballarin@14174
   277
ballarin@14174
   278
fun induct_meth ctxt (varss, opt_rule) =
ballarin@14174
   279
  gen_induct_tac (inst_tac ctxt) (varss, opt_rule);
ballarin@14174
   280
fun case_meth ctxt (varss, opt_rule) =
ballarin@14174
   281
  gen_case_tac (inst_tac ctxt) (varss, opt_rule);
ballarin@14174
   282
wenzelm@8672
   283
in
wenzelm@8541
   284
wenzelm@8541
   285
val tactic_emulations =
ballarin@14174
   286
 [("induct_tac", Method.goal_args_ctxt' (varss -- opt_rule) induct_meth,
ballarin@14174
   287
    "induct_tac emulation (dynamic instantiation)"),
ballarin@14174
   288
  ("case_tac", Method.goal_args_ctxt' (Scan.lift Args.name -- opt_rule) case_meth,
ballarin@14174
   289
    "case_tac emulation (dynamic instantiation)")];
wenzelm@8672
   290
wenzelm@8672
   291
end;
wenzelm@8541
   292
wenzelm@8541
   293
berghofe@5177
   294
wenzelm@8437
   295
(** induct method setup **)
wenzelm@8437
   296
wenzelm@8437
   297
(* case names *)
wenzelm@8437
   298
wenzelm@8437
   299
local
wenzelm@8437
   300
wenzelm@8437
   301
fun dt_recs (DtTFree _) = []
haftmann@21045
   302
  | dt_recs (DtType (_, dts)) = maps dt_recs dts
wenzelm@8437
   303
  | dt_recs (DtRec i) = [i];
wenzelm@8437
   304
wenzelm@8437
   305
fun dt_cases (descr: descr) (_, args, constrs) =
wenzelm@8437
   306
  let
haftmann@21045
   307
    fun the_bname i = Sign.base_name (#1 (the (AList.lookup (op =) descr i)));
haftmann@21045
   308
    val bnames = map the_bname (distinct (op =) (maps dt_recs args));
wenzelm@8437
   309
  in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
wenzelm@8437
   310
wenzelm@8437
   311
wenzelm@8437
   312
fun induct_cases descr =
haftmann@21045
   313
  DatatypeProp.indexify_names (maps (dt_cases descr) (map #2 descr));
wenzelm@8437
   314
haftmann@21045
   315
fun exhaust_cases descr i = dt_cases descr (the (AList.lookup (op =) descr i));
wenzelm@8437
   316
wenzelm@8437
   317
in
wenzelm@8437
   318
wenzelm@8437
   319
fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
wenzelm@8437
   320
wenzelm@8437
   321
fun mk_case_names_exhausts descr new =
wenzelm@8437
   322
  map (RuleCases.case_names o exhaust_cases descr o #1)
haftmann@21045
   323
    (filter (fn ((_, (name, _, _))) => member (op =) new name) descr);
wenzelm@8437
   324
wenzelm@8437
   325
end;
wenzelm@8437
   326
oheimb@11345
   327
fun add_rules simps case_thms size_thms rec_thms inject distinct
oheimb@11345
   328
                  weak_case_congs cong_att =
haftmann@21127
   329
  PureThy.add_thmss [(("simps", simps), []),
haftmann@21045
   330
    (("", flat case_thms @ size_thms @ 
haftmann@21045
   331
          flat distinct @ rec_thms), [Simplifier.simp_add]),
haftmann@21127
   332
    (("", size_thms @ rec_thms), [RecfunCodegen.add NONE]),
haftmann@21127
   333
    (("", flat inject), [iff_add]),
paulson@21689
   334
    (("", map (fn th => th RS notE) (flat distinct)), [Classical.safe_elim NONE]),
haftmann@21127
   335
    (("", weak_case_congs), [cong_att])]
haftmann@21127
   336
  #> snd;
oheimb@11345
   337
wenzelm@8437
   338
wenzelm@8437
   339
(* add_cases_induct *)
wenzelm@8306
   340
wenzelm@19874
   341
fun add_cases_induct infos induction thy =
wenzelm@8306
   342
  let
wenzelm@19874
   343
    val inducts = ProjectRule.projections (ProofContext.init thy) induction;
wenzelm@8405
   344
wenzelm@11805
   345
    fun named_rules (name, {index, exhaustion, ...}: datatype_info) =
wenzelm@19874
   346
      [(("", nth inducts index), [InductAttrib.induct_type name]),
wenzelm@18728
   347
       (("", exhaustion), [InductAttrib.cases_type name])];
wenzelm@11805
   348
    fun unnamed_rule i =
wenzelm@19874
   349
      (("", nth inducts i), [PureThy.kind_internal, InductAttrib.induct_type ""]);
wenzelm@18462
   350
  in
wenzelm@19874
   351
    thy |> PureThy.add_thms
haftmann@21045
   352
      (maps named_rules infos @
wenzelm@19874
   353
        map unnamed_rule (length infos upto length inducts - 1)) |> snd
wenzelm@19874
   354
    |> PureThy.add_thmss [(("inducts", inducts), [])] |> snd
wenzelm@18462
   355
  end;
wenzelm@8306
   356
berghofe@5177
   357
wenzelm@8405
   358
berghofe@7015
   359
(**** simplification procedure for showing distinctness of constructors ****)
berghofe@7015
   360
berghofe@7060
   361
fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
berghofe@7060
   362
  | stripT p = p;
berghofe@7060
   363
berghofe@7060
   364
fun stripC (i, f $ x) = stripC (i + 1, f)
berghofe@7060
   365
  | stripC p = p;
berghofe@7060
   366
berghofe@7015
   367
val distinctN = "constr_distinct";
berghofe@7015
   368
berghofe@7015
   369
exception ConstrDistinct of term;
berghofe@7015
   370
wenzelm@19539
   371
fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
berghofe@7060
   372
  (case (stripC (0, t1), stripC (0, t2)) of
berghofe@7060
   373
     ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
berghofe@7060
   374
         (case (stripT (0, T1), stripT (0, T2)) of
berghofe@7060
   375
            ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
berghofe@7060
   376
                if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
wenzelm@19539
   377
                   (case (get_datatype_descr thy) tname1 of
haftmann@19346
   378
                      SOME (_, (_, constrs)) => let val cnames = map fst constrs
berghofe@7015
   379
                        in if cname1 mem cnames andalso cname2 mem cnames then
berghofe@7015
   380
                             let val eq_t = Logic.mk_equals (t, Const ("False", HOLogic.boolT));
wenzelm@19539
   381
                                 val eq_ct = cterm_of thy eq_t;
wenzelm@19539
   382
                                 val Datatype_thy = ThyInfo.the_theory "Datatype" thy;
berghofe@7015
   383
                                 val [In0_inject, In1_inject, In0_not_In1, In1_not_In0] =
wenzelm@16486
   384
                                   map (get_thm Datatype_thy o Name)
berghofe@7015
   385
                                     ["In0_inject", "In1_inject", "In0_not_In1", "In1_not_In0"]
wenzelm@19539
   386
                             in (case (#distinct (the_datatype thy tname1)) of
skalberg@15531
   387
                                 QuickAndDirty => SOME (Thm.invoke_oracle
wenzelm@19539
   388
                                   Datatype_thy distinctN (thy, ConstrDistinct eq_t))
wenzelm@20054
   389
                               | FewConstrs thms =>
wenzelm@20054
   390
                                   SOME (Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
wenzelm@20054
   391
                                     (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
wenzelm@20054
   392
                                       atac 2, resolve_tac thms 1, etac FalseE 1])))
wenzelm@20054
   393
                               | ManyConstrs (thm, simpset) =>
wenzelm@20054
   394
                                   SOME (Goal.prove (Simplifier.the_context ss) [] [] eq_t (K
wenzelm@20054
   395
                                     (EVERY [rtac eq_reflection 1, rtac iffI 1, dtac thm 1,
wenzelm@20054
   396
                                      full_simp_tac (Simplifier.inherit_context ss simpset) 1,
wenzelm@20054
   397
                                      REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
wenzelm@20054
   398
                                      eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1,
wenzelm@20054
   399
                                      etac FalseE 1]))))
berghofe@7015
   400
                             end
skalberg@15531
   401
                           else NONE
berghofe@7015
   402
                        end
skalberg@15531
   403
                    | NONE => NONE)
skalberg@15531
   404
                else NONE
skalberg@15531
   405
          | _ => NONE)
skalberg@15531
   406
   | _ => NONE)
wenzelm@20054
   407
  | distinct_proc _ _ _ = NONE;
berghofe@7015
   408
wenzelm@13462
   409
val distinct_simproc =
wenzelm@16430
   410
  Simplifier.simproc HOL.thy distinctN ["s = t"] distinct_proc;
berghofe@7015
   411
berghofe@7015
   412
val dist_ss = HOL_ss addsimprocs [distinct_simproc];
berghofe@7015
   413
berghofe@7015
   414
val simproc_setup =
wenzelm@18708
   415
  Theory.add_oracle (distinctN, fn (_, ConstrDistinct t) => t) #>
wenzelm@18708
   416
  (fn thy => ((change_simpset_of thy) (fn ss => ss addsimprocs [distinct_simproc]); thy));
berghofe@7015
   417
berghofe@7015
   418
berghofe@14799
   419
(**** translation rules for case ****)
berghofe@14799
   420
berghofe@22777
   421
fun make_case ctxt = DatatypeCase.make_case
berghofe@22777
   422
  (datatype_of_constr (ProofContext.theory_of ctxt)) ctxt;
berghofe@22777
   423
berghofe@22777
   424
fun strip_case ctxt = DatatypeCase.strip_case
berghofe@22777
   425
  (datatype_of_case (ProofContext.theory_of ctxt));
berghofe@14799
   426
berghofe@22777
   427
fun add_case_tr' case_names thy =
berghofe@22777
   428
  Theory.add_advanced_trfuns ([], [],
berghofe@22777
   429
    map (fn case_name => 
berghofe@22777
   430
      let val case_name' = Sign.const_syntax_name thy case_name
berghofe@22777
   431
      in (case_name', DatatypeCase.case_tr' datatype_of_case case_name')
berghofe@22777
   432
      end) case_names, []) thy;
berghofe@14799
   433
berghofe@14799
   434
val trfun_setup =
berghofe@22777
   435
  Theory.add_advanced_trfuns ([],
nipkow@24349
   436
    [("_case_syntax", DatatypeCase.case_tr true datatype_of_constr)],
berghofe@22777
   437
    [], []);
berghofe@14799
   438
berghofe@14799
   439
berghofe@5177
   440
(* prepare types *)
berghofe@5177
   441
berghofe@5177
   442
fun read_typ sign ((Ts, sorts), str) =
berghofe@5177
   443
  let
wenzelm@22675
   444
    val T = Type.no_tvars (Sign.read_def_typ (sign, AList.lookup (op =)
berghofe@5177
   445
      (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
berghofe@5177
   446
  in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
berghofe@5177
   447
berghofe@5177
   448
fun cert_typ sign ((Ts, sorts), raw_T) =
berghofe@5177
   449
  let
berghofe@5177
   450
    val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
berghofe@5177
   451
      TYPE (msg, _, _) => error msg;
berghofe@5177
   452
    val sorts' = add_typ_tfrees (T, sorts)
berghofe@5177
   453
  in (Ts @ [T],
wenzelm@18964
   454
      case duplicates (op =) (map fst sorts') of
berghofe@5177
   455
         [] => sorts'
berghofe@5177
   456
       | dups => error ("Inconsistent sort constraints for " ^ commas dups))
berghofe@5177
   457
  end;
berghofe@5177
   458
berghofe@5177
   459
berghofe@5177
   460
(**** make datatype info ****)
berghofe@5177
   461
berghofe@18319
   462
fun make_dt_info descr sorts induct reccomb_names rec_thms
wenzelm@10121
   463
    (((((((((i, (_, (tname, _, _))), case_name), case_thms),
wenzelm@10121
   464
      exhaustion_thm), distinct_thm), inject), nchotomy), case_cong), weak_case_cong) =
wenzelm@10121
   465
  (tname,
wenzelm@10121
   466
   {index = i,
wenzelm@10121
   467
    descr = descr,
berghofe@18319
   468
    sorts = sorts,
wenzelm@10121
   469
    rec_names = reccomb_names,
wenzelm@10121
   470
    rec_rewrites = rec_thms,
wenzelm@10121
   471
    case_name = case_name,
wenzelm@10121
   472
    case_rewrites = case_thms,
wenzelm@10121
   473
    induction = induct,
wenzelm@10121
   474
    exhaustion = exhaustion_thm,
wenzelm@10121
   475
    distinct = distinct_thm,
wenzelm@10121
   476
    inject = inject,
wenzelm@10121
   477
    nchotomy = nchotomy,
wenzelm@10121
   478
    case_cong = case_cong,
wenzelm@10121
   479
    weak_case_cong = weak_case_cong});
berghofe@5177
   480
berghofe@5177
   481
berghofe@5177
   482
(********************* axiomatic introduction of datatypes ********************)
berghofe@5177
   483
haftmann@20597
   484
fun add_axiom label t atts thy =
haftmann@20597
   485
  thy
haftmann@20597
   486
  |> PureThy.add_axioms_i [((label, t), atts)];
haftmann@20597
   487
haftmann@20597
   488
fun add_axioms label ts atts thy =
haftmann@20597
   489
  thy
haftmann@20597
   490
  |> PureThy.add_axiomss_i [((label, ts), atts)];
wenzelm@8437
   491
haftmann@20597
   492
fun add_and_get_axioms_atts label tnames ts attss =
haftmann@20597
   493
  fold_map (fn (tname, (atts, t)) => fn thy =>
haftmann@20597
   494
    thy
haftmann@20597
   495
    |> Theory.add_path tname
haftmann@20597
   496
    |> add_axiom label t atts
haftmann@20597
   497
    ||> Theory.parent_path
haftmann@20597
   498
    |-> (fn [ax] => pair ax)) (tnames ~~ (attss ~~ ts));
berghofe@5177
   499
haftmann@20597
   500
fun add_and_get_axioms label tnames ts =
haftmann@20597
   501
  add_and_get_axioms_atts label tnames ts (replicate (length tnames) []);
haftmann@20597
   502
haftmann@20597
   503
fun add_and_get_axiomss label tnames tss =
haftmann@20597
   504
  fold_map (fn (tname, ts) => fn thy =>
haftmann@20597
   505
    thy
haftmann@20597
   506
    |> Theory.add_path tname
haftmann@20597
   507
    |> add_axioms label ts []
haftmann@20597
   508
    ||> Theory.parent_path
haftmann@20597
   509
    |-> (fn [ax] => pair ax)) (tnames ~~ tss);
berghofe@5177
   510
berghofe@22777
   511
fun gen_specify_consts add args thy =
haftmann@20597
   512
  let
haftmann@20597
   513
    val specs = map (fn (c, T, mx) =>
haftmann@20597
   514
      Const (Sign.full_name thy (Syntax.const_name c mx), T)) args;
haftmann@20597
   515
  in
haftmann@20597
   516
    thy
berghofe@22777
   517
    |> add args
haftmann@20597
   518
    |> Theory.add_finals_i false specs
haftmann@20597
   519
  end;
wenzelm@19716
   520
berghofe@22777
   521
val specify_consts = gen_specify_consts Sign.add_consts_i;
berghofe@22777
   522
val specify_consts_authentic = gen_specify_consts Sign.add_consts_authentic;
berghofe@22777
   523
wenzelm@8437
   524
fun add_datatype_axm flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   525
    case_names_induct case_names_exhausts thy =
berghofe@5177
   526
  let
haftmann@21045
   527
    val descr' = flat descr;
berghofe@5177
   528
    val recTs = get_rec_types descr' sorts;
haftmann@21045
   529
    val used = map fst (fold Term.add_tfreesT recTs []);
skalberg@15570
   530
    val newTs = Library.take (length (hd descr), recTs);
berghofe@5177
   531
berghofe@7015
   532
    val no_size = exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists
berghofe@13641
   533
      (fn dt => is_rec_type dt andalso not (null (fst (strip_dtyp dt))))
berghofe@13641
   534
        cargs) constrs) descr';
berghofe@7015
   535
berghofe@5177
   536
    (**** declare new types and constants ****)
berghofe@5177
   537
berghofe@5177
   538
    val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
berghofe@5177
   539
berghofe@5177
   540
    val constr_decls = map (fn (((_, (_, _, constrs)), T), constr_syntax') =>
berghofe@5177
   541
      map (fn ((_, cargs), (cname, mx)) =>
berghofe@5177
   542
        (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
berghofe@5177
   543
          (constrs ~~ constr_syntax')) ((hd descr) ~~ newTs ~~ constr_syntax);
berghofe@5177
   544
berghofe@15457
   545
    val (rec_result_Ts, reccomb_fn_Ts) = DatatypeProp.make_primrec_Ts descr sorts used;
berghofe@5177
   546
berghofe@5177
   547
    val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
berghofe@5177
   548
    val reccomb_names = if length descr' = 1 then [big_reccomb_name] else
berghofe@5177
   549
      (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
berghofe@5177
   550
        (1 upto (length descr')));
berghofe@5177
   551
berghofe@9739
   552
    val size_names = DatatypeProp.indexify_names
skalberg@15570
   553
      (map (fn T => name_of_typ T ^ "_size") (Library.drop (length (hd descr), recTs)));
berghofe@5177
   554
wenzelm@20071
   555
    val freeT = TFree (Name.variant used "'t", HOLogic.typeS);
berghofe@5177
   556
    val case_fn_Ts = map (fn (i, (_, _, constrs)) =>
berghofe@5177
   557
      map (fn (_, cargs) =>
berghofe@5177
   558
        let val Ts = map (typ_of_dtyp descr' sorts) cargs
berghofe@5177
   559
        in Ts ---> freeT end) constrs) (hd descr);
berghofe@5177
   560
berghofe@5177
   561
    val case_names = map (fn s => (s ^ "_case")) new_type_names;
berghofe@5177
   562
haftmann@21419
   563
    fun instance_size_class tyco thy =
haftmann@21419
   564
      let
haftmann@21419
   565
        val n = Sign.arity_number thy tyco;
haftmann@21419
   566
      in
haftmann@21419
   567
        thy
haftmann@24589
   568
        |> Class.prove_instance (Class.intro_classes_tac [])
haftmann@24346
   569
            [(tyco, replicate n HOLogic.typeS, [HOLogic.class_size])] []
haftmann@24423
   570
        |> snd
haftmann@21419
   571
      end
haftmann@21419
   572
haftmann@21045
   573
    val thy2' = thy
berghofe@5177
   574
berghofe@5177
   575
      (** new types **)
haftmann@21419
   576
      |> fold2 (fn (name, mx) => fn tvs => TypedefPackage.add_typedecls [(name, tvs, mx)])
haftmann@21419
   577
           types_syntax tyvars
haftmann@21419
   578
      |> fold (fn (_, (name, _, _)) => instance_size_class name) descr'
haftmann@21045
   579
      |> add_path flat_names (space_implode "_" new_type_names)
berghofe@5177
   580
berghofe@5177
   581
      (** primrec combinators **)
berghofe@5177
   582
haftmann@21045
   583
      |> specify_consts (map (fn ((name, T), T') =>
haftmann@21045
   584
           (name, reccomb_fn_Ts @ [T] ---> T', NoSyn)) (reccomb_names ~~ recTs ~~ rec_result_Ts))
berghofe@5177
   585
berghofe@5177
   586
      (** case combinators **)
berghofe@5177
   587
berghofe@22777
   588
      |> specify_consts_authentic (map (fn ((name, T), Ts) =>
haftmann@21045
   589
           (name, Ts @ [T] ---> freeT, NoSyn)) (case_names ~~ newTs ~~ case_fn_Ts));
berghofe@6305
   590
wenzelm@19716
   591
    val reccomb_names' = map (Sign.full_name thy2') reccomb_names;
wenzelm@19716
   592
    val case_names' = map (Sign.full_name thy2') case_names;
berghofe@6305
   593
haftmann@21045
   594
    val thy2 = thy2'
berghofe@5177
   595
berghofe@5177
   596
      (** size functions **)
berghofe@5177
   597
haftmann@21045
   598
      |> (if no_size then I else specify_consts (map (fn (s, T) =>
berghofe@5177
   599
        (Sign.base_name s, T --> HOLogic.natT, NoSyn))
haftmann@21045
   600
          (size_names ~~ Library.drop (length (hd descr), recTs))))
berghofe@5661
   601
berghofe@5661
   602
      (** constructors **)
berghofe@5661
   603
haftmann@21045
   604
      |> parent_path flat_names
haftmann@21045
   605
      |> fold (fn ((((_, (_, _, constrs)), T), tname),
haftmann@21045
   606
        constr_syntax') =>
haftmann@21045
   607
          add_path flat_names tname #>
wenzelm@19716
   608
            specify_consts (map (fn ((_, cargs), (cname, mx)) =>
berghofe@5661
   609
              (cname, map (typ_of_dtyp descr' sorts) cargs ---> T, mx))
haftmann@21045
   610
                (constrs ~~ constr_syntax')) #>
haftmann@21045
   611
          parent_path flat_names)
berghofe@5661
   612
            (hd descr ~~ newTs ~~ new_type_names ~~ constr_syntax);
berghofe@5177
   613
berghofe@5177
   614
    (**** introduction of axioms ****)
berghofe@5177
   615
berghofe@5661
   616
    val rec_axs = DatatypeProp.make_primrecs new_type_names descr sorts thy2;
berghofe@9739
   617
    val size_axs = if no_size then [] else DatatypeProp.make_size descr sorts thy2;
berghofe@5661
   618
haftmann@18377
   619
    val ((([induct], [rec_thms]), inject), thy3) =
haftmann@18377
   620
      thy2
haftmann@18377
   621
      |> Theory.add_path (space_implode "_" new_type_names)
haftmann@20597
   622
      |> add_axiom "induct" (DatatypeProp.make_ind descr sorts) [case_names_induct]
haftmann@20597
   623
      ||>> add_axioms "recs" rec_axs []
haftmann@20597
   624
      ||> (if no_size then I else add_axioms "size" size_axs [] #> snd)
haftmann@18377
   625
      ||> Theory.parent_path
haftmann@18377
   626
      ||>> add_and_get_axiomss "inject" new_type_names
haftmann@18377
   627
            (DatatypeProp.make_injs descr sorts);
wenzelm@16486
   628
    val size_thms = if no_size then [] else get_thms thy3 (Name "size");
haftmann@18377
   629
    val (distinct, thy4) = add_and_get_axiomss "distinct" new_type_names
berghofe@5177
   630
      (DatatypeProp.make_distincts new_type_names descr sorts thy3) thy3;
wenzelm@8437
   631
wenzelm@8437
   632
    val exhaust_ts = DatatypeProp.make_casedists descr sorts;
haftmann@18377
   633
    val (exhaustion, thy5) = add_and_get_axioms_atts "exhaust" new_type_names
haftmann@20597
   634
      exhaust_ts (map single case_names_exhausts) thy4;
haftmann@18377
   635
    val (case_thms, thy6) = add_and_get_axiomss "cases" new_type_names
berghofe@5177
   636
      (DatatypeProp.make_cases new_type_names descr sorts thy5) thy5;
berghofe@5177
   637
    val (split_ts, split_asm_ts) = ListPair.unzip
berghofe@5177
   638
      (DatatypeProp.make_splits new_type_names descr sorts thy6);
haftmann@18377
   639
    val (split, thy7) = add_and_get_axioms "split" new_type_names split_ts thy6;
haftmann@18377
   640
    val (split_asm, thy8) = add_and_get_axioms "split_asm" new_type_names
berghofe@5177
   641
      split_asm_ts thy7;
haftmann@18377
   642
    val (nchotomys, thy9) = add_and_get_axioms "nchotomy" new_type_names
berghofe@5177
   643
      (DatatypeProp.make_nchotomys descr sorts) thy8;
haftmann@18377
   644
    val (case_congs, thy10) = add_and_get_axioms "case_cong" new_type_names
berghofe@5177
   645
      (DatatypeProp.make_case_congs new_type_names descr sorts thy9) thy9;
haftmann@18377
   646
    val (weak_case_congs, thy11) = add_and_get_axioms "weak_case_cong" new_type_names
nipkow@8601
   647
      (DatatypeProp.make_weak_case_congs new_type_names descr sorts thy10) thy10;
wenzelm@8405
   648
berghofe@18319
   649
    val dt_infos = map (make_dt_info descr' sorts induct reccomb_names' rec_thms)
berghofe@6305
   650
      ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names' ~~ case_thms ~~
berghofe@7015
   651
        exhaustion ~~ replicate (length (hd descr)) QuickAndDirty ~~ inject ~~
wenzelm@10121
   652
          nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   653
haftmann@21045
   654
    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
wenzelm@9386
   655
    val split_thms = split ~~ split_asm;
berghofe@5177
   656
haftmann@18518
   657
    val thy12 =
haftmann@18518
   658
      thy11
berghofe@22777
   659
      |> add_case_tr' case_names'
haftmann@18518
   660
      |> Theory.add_path (space_implode "_" new_type_names)
haftmann@18518
   661
      |> add_rules simps case_thms size_thms rec_thms inject distinct
wenzelm@18728
   662
          weak_case_congs Simplifier.cong_add
berghofe@22777
   663
      |> put_dt_infos dt_infos
haftmann@18518
   664
      |> add_cases_induct dt_infos induct
haftmann@18518
   665
      |> Theory.parent_path
haftmann@19599
   666
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)
haftmann@19599
   667
      |> snd
haftmann@18518
   668
      |> DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos)
haftmann@21251
   669
      |> DatatypeHooks.all (map fst dt_infos);
berghofe@5177
   670
  in
haftmann@18008
   671
    ({distinct = distinct,
berghofe@5177
   672
      inject = inject,
berghofe@5177
   673
      exhaustion = exhaustion,
berghofe@5177
   674
      rec_thms = rec_thms,
berghofe@5177
   675
      case_thms = case_thms,
wenzelm@9386
   676
      split_thms = split_thms,
berghofe@5177
   677
      induction = induct,
berghofe@5177
   678
      size = size_thms,
haftmann@18008
   679
      simps = simps}, thy12)
berghofe@5177
   680
  end;
berghofe@5177
   681
berghofe@5177
   682
berghofe@5177
   683
(******************* definitional introduction of datatypes *******************)
berghofe@5177
   684
wenzelm@8437
   685
fun add_datatype_def flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   686
    case_names_induct case_names_exhausts thy =
berghofe@5177
   687
  let
wenzelm@6360
   688
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   689
haftmann@18314
   690
    val ((inject, distinct, dist_rewrites, simproc_dists, induct), thy2) = thy |>
berghofe@5661
   691
      DatatypeRepProofs.representation_proofs flat_names dt_info new_type_names descr sorts
wenzelm@8437
   692
        types_syntax constr_syntax case_names_induct;
berghofe@5177
   693
haftmann@18314
   694
    val (casedist_thms, thy3) = DatatypeAbsProofs.prove_casedist_thms new_type_names descr
wenzelm@8437
   695
      sorts induct case_names_exhausts thy2;
haftmann@18314
   696
    val ((reccomb_names, rec_thms), thy4) = DatatypeAbsProofs.prove_primrec_thms
wenzelm@20054
   697
      flat_names new_type_names descr sorts dt_info inject dist_rewrites
wenzelm@20054
   698
      (Simplifier.theory_context thy3 dist_ss) induct thy3;
haftmann@18314
   699
    val ((case_thms, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
berghofe@5661
   700
      flat_names new_type_names descr sorts reccomb_names rec_thms thy4;
haftmann@18314
   701
    val (split_thms, thy7) = DatatypeAbsProofs.prove_split_thms new_type_names
berghofe@5177
   702
      descr sorts inject dist_rewrites casedist_thms case_thms thy6;
haftmann@18314
   703
    val (nchotomys, thy8) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   704
      descr sorts casedist_thms thy7;
haftmann@18314
   705
    val (case_congs, thy9) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   706
      descr sorts nchotomys case_thms thy8;
haftmann@18314
   707
    val (weak_case_congs, thy10) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
nipkow@8601
   708
      descr sorts thy9;
haftmann@18314
   709
    val (size_thms, thy11) = DatatypeAbsProofs.prove_size_thms flat_names new_type_names
nipkow@8601
   710
      descr sorts reccomb_names rec_thms thy10;
berghofe@5177
   711
haftmann@21045
   712
    val dt_infos = map (make_dt_info (flat descr) sorts induct reccomb_names rec_thms)
berghofe@5177
   713
      ((0 upto length (hd descr) - 1) ~~ (hd descr) ~~ case_names ~~ case_thms ~~
wenzelm@10121
   714
        casedist_thms ~~ simproc_dists ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   715
haftmann@21045
   716
    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
berghofe@5177
   717
haftmann@18518
   718
    val thy12 =
haftmann@18518
   719
      thy11
berghofe@22777
   720
      |> add_case_tr' case_names
haftmann@18518
   721
      |> Theory.add_path (space_implode "_" new_type_names)
haftmann@18518
   722
      |> add_rules simps case_thms size_thms rec_thms inject distinct
wenzelm@18728
   723
          weak_case_congs (Simplifier.attrib (op addcongs))
berghofe@22777
   724
      |> put_dt_infos dt_infos
haftmann@18518
   725
      |> add_cases_induct dt_infos induct
haftmann@18518
   726
      |> Theory.parent_path
haftmann@18518
   727
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms) |> snd
haftmann@18518
   728
      |> DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos)
haftmann@21251
   729
      |> DatatypeHooks.all (map fst dt_infos);
berghofe@5177
   730
  in
haftmann@18008
   731
    ({distinct = distinct,
berghofe@5177
   732
      inject = inject,
berghofe@5177
   733
      exhaustion = casedist_thms,
berghofe@5177
   734
      rec_thms = rec_thms,
berghofe@5177
   735
      case_thms = case_thms,
berghofe@5177
   736
      split_thms = split_thms,
berghofe@5177
   737
      induction = induct,
berghofe@5177
   738
      size = size_thms,
haftmann@18008
   739
      simps = simps}, thy12)
berghofe@5177
   740
  end;
berghofe@5177
   741
berghofe@5177
   742
wenzelm@6385
   743
(*********************** declare existing type as datatype *********************)
berghofe@5177
   744
wenzelm@6385
   745
fun gen_rep_datatype apply_theorems alt_names raw_distinct raw_inject raw_induction thy0 =
berghofe@5177
   746
  let
haftmann@18418
   747
    val (((distinct, inject), [induction]), thy1) =
haftmann@18418
   748
      thy0
haftmann@18418
   749
      |> fold_map apply_theorems raw_distinct
haftmann@18418
   750
      ||>> fold_map apply_theorems raw_inject
haftmann@18418
   751
      ||>> apply_theorems [raw_induction];
berghofe@5177
   752
wenzelm@22598
   753
    val ((_, [induction']), _) =
wenzelm@22598
   754
      Variable.importT_thms [induction] (Variable.thm_context induction);
berghofe@5177
   755
berghofe@5177
   756
    fun err t = error ("Ill-formed predicate in induction rule: " ^
haftmann@20715
   757
      Sign.string_of_term thy1 t);
berghofe@5177
   758
berghofe@5177
   759
    fun get_typ (t as _ $ Var (_, Type (tname, Ts))) =
berghofe@7015
   760
          ((tname, map dest_TFree Ts) handle TERM _ => err t)
berghofe@5177
   761
      | get_typ t = err t;
berghofe@5177
   762
wenzelm@8437
   763
    val dtnames = map get_typ (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of induction')));
skalberg@15570
   764
    val new_type_names = getOpt (alt_names, map fst dtnames);
berghofe@5177
   765
berghofe@5177
   766
    fun get_constr t = (case Logic.strip_assums_concl t of
berghofe@5177
   767
        _ $ (_ $ t') => (case head_of t' of
berghofe@5177
   768
            Const (cname, cT) => (case strip_type cT of
berghofe@5177
   769
                (Ts, Type (tname, _)) => (tname, (cname, map (dtyp_of_typ dtnames) Ts))
berghofe@5177
   770
              | _ => err t)
berghofe@5177
   771
          | _ => err t)
berghofe@5177
   772
      | _ => err t);
berghofe@5177
   773
berghofe@5177
   774
    fun make_dt_spec [] _ _ = []
berghofe@5177
   775
      | make_dt_spec ((tname, tvs)::dtnames') i constrs =
berghofe@5177
   776
          let val (constrs', constrs'') = take_prefix (equal tname o fst) constrs
berghofe@5177
   777
          in (i, (tname, map DtTFree tvs, map snd constrs'))::
berghofe@5177
   778
            (make_dt_spec dtnames' (i + 1) constrs'')
berghofe@5177
   779
          end;
berghofe@5177
   780
berghofe@5177
   781
    val descr = make_dt_spec dtnames 0 (map get_constr (prems_of induction'));
berghofe@5177
   782
    val sorts = add_term_tfrees (concl_of induction', []);
wenzelm@6385
   783
    val dt_info = get_datatypes thy1;
berghofe@5177
   784
haftmann@21419
   785
    val (case_names_induct, case_names_exhausts) =
haftmann@21419
   786
      (mk_case_names_induct descr, mk_case_names_exhausts descr (map #1 dtnames));
wenzelm@8437
   787
wenzelm@6427
   788
    val _ = message ("Proofs for datatype(s) " ^ commas_quote new_type_names);
berghofe@5177
   789
haftmann@18314
   790
    val (casedist_thms, thy2) = thy1 |>
wenzelm@8437
   791
      DatatypeAbsProofs.prove_casedist_thms new_type_names [descr] sorts induction
wenzelm@8437
   792
        case_names_exhausts;
haftmann@18314
   793
    val ((reccomb_names, rec_thms), thy3) = DatatypeAbsProofs.prove_primrec_thms
wenzelm@20054
   794
      false new_type_names [descr] sorts dt_info inject distinct
wenzelm@20054
   795
      (Simplifier.theory_context thy2 dist_ss) induction thy2;
haftmann@18314
   796
    val ((case_thms, case_names), thy4) = DatatypeAbsProofs.prove_case_thms false
berghofe@5177
   797
      new_type_names [descr] sorts reccomb_names rec_thms thy3;
haftmann@18314
   798
    val (split_thms, thy5) = DatatypeAbsProofs.prove_split_thms
berghofe@5177
   799
      new_type_names [descr] sorts inject distinct casedist_thms case_thms thy4;
haftmann@18314
   800
    val (nchotomys, thy6) = DatatypeAbsProofs.prove_nchotomys new_type_names
berghofe@5177
   801
      [descr] sorts casedist_thms thy5;
haftmann@18314
   802
    val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
berghofe@5177
   803
      [descr] sorts nchotomys case_thms thy6;
haftmann@18314
   804
    val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
nipkow@8601
   805
      [descr] sorts thy7;
haftmann@18314
   806
    val (size_thms, thy9) =
haftmann@21459
   807
      DatatypeAbsProofs.prove_size_thms false new_type_names
haftmann@21459
   808
        [descr] sorts reccomb_names rec_thms thy8;
berghofe@5177
   809
haftmann@18377
   810
    val ((_, [induction']), thy10) =
haftmann@18377
   811
      thy9
haftmann@18377
   812
      |> store_thmss "inject" new_type_names inject
haftmann@18377
   813
      ||>> store_thmss "distinct" new_type_names distinct
haftmann@18377
   814
      ||> Theory.add_path (space_implode "_" new_type_names)
haftmann@18377
   815
      ||>> PureThy.add_thms [(("induct", induction), [case_names_induct])];
wenzelm@9149
   816
berghofe@18319
   817
    val dt_infos = map (make_dt_info descr sorts induction' reccomb_names rec_thms)
wenzelm@10121
   818
      ((0 upto length descr - 1) ~~ descr ~~ case_names ~~ case_thms ~~ casedist_thms ~~
wenzelm@10121
   819
        map FewConstrs distinct ~~ inject ~~ nchotomys ~~ case_congs ~~ weak_case_congs);
berghofe@5177
   820
haftmann@21045
   821
    val simps = flat (distinct @ inject @ case_thms) @ size_thms @ rec_thms;
berghofe@5177
   822
haftmann@19599
   823
    val thy11 =
haftmann@19599
   824
      thy10
berghofe@22777
   825
      |> add_case_tr' case_names
haftmann@19599
   826
      |> add_rules simps case_thms size_thms rec_thms inject distinct
haftmann@19599
   827
           weak_case_congs (Simplifier.attrib (op addcongs))
berghofe@22777
   828
      |> put_dt_infos dt_infos
haftmann@19599
   829
      |> add_cases_induct dt_infos induction'
haftmann@19599
   830
      |> Theory.parent_path
haftmann@19599
   831
      |> store_thmss "splits" new_type_names (map (fn (x, y) => [x, y]) split_thms)
haftmann@19599
   832
      |> snd
haftmann@19599
   833
      |> DatatypeRealizer.add_dt_realizers sorts (map snd dt_infos)
haftmann@21251
   834
      |> DatatypeHooks.all (map fst dt_infos);
berghofe@5177
   835
  in
haftmann@18008
   836
    ({distinct = distinct,
berghofe@5177
   837
      inject = inject,
berghofe@5177
   838
      exhaustion = casedist_thms,
berghofe@5177
   839
      rec_thms = rec_thms,
berghofe@5177
   840
      case_thms = case_thms,
berghofe@5177
   841
      split_thms = split_thms,
wenzelm@8437
   842
      induction = induction',
berghofe@5177
   843
      size = size_thms,
haftmann@18008
   844
      simps = simps}, thy11)
berghofe@5177
   845
  end;
berghofe@5177
   846
wenzelm@21350
   847
val rep_datatype = gen_rep_datatype IsarCmd.apply_theorems;
wenzelm@21350
   848
val rep_datatype_i = gen_rep_datatype IsarCmd.apply_theorems_i;
wenzelm@6385
   849
berghofe@5177
   850
wenzelm@11958
   851
berghofe@5177
   852
(******************************** add datatype ********************************)
berghofe@5177
   853
berghofe@14887
   854
fun gen_add_datatype prep_typ err flat_names new_type_names dts thy =
berghofe@5177
   855
  let
wenzelm@20820
   856
    val _ = Theory.requires thy "Datatype" "datatype definitions";
berghofe@5177
   857
berghofe@5177
   858
    (* this theory is used just for parsing *)
berghofe@5177
   859
berghofe@5177
   860
    val tmp_thy = thy |>
wenzelm@5892
   861
      Theory.copy |>
berghofe@5177
   862
      Theory.add_types (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   863
        (tname, length tvs, mx)) dts);
berghofe@5177
   864
berghofe@5661
   865
    val (tyvars, _, _, _)::_ = dts;
berghofe@5177
   866
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
haftmann@20597
   867
      let val full_tname = Sign.full_name tmp_thy (Syntax.type_name tname mx)
wenzelm@18964
   868
      in (case duplicates (op =) tvs of
berghofe@5661
   869
            [] => if eq_set (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
berghofe@5661
   870
                  else error ("Mutually recursive datatypes must have same type parameters")
berghofe@5177
   871
          | dups => error ("Duplicate parameter(s) for datatype " ^ full_tname ^
berghofe@5177
   872
              " : " ^ commas dups))
berghofe@5177
   873
      end) dts);
berghofe@5177
   874
wenzelm@18964
   875
    val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
berghofe@5177
   876
      [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
berghofe@5177
   877
haftmann@21045
   878
    fun prep_dt_spec (tvs, tname, mx, constrs) (dts', constr_syntax, sorts, i) =
berghofe@5177
   879
      let
haftmann@21045
   880
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
berghofe@5279
   881
          let
haftmann@20597
   882
            val (cargs', sorts'') = Library.foldl (prep_typ tmp_thy) (([], sorts'), cargs);
haftmann@21045
   883
            val _ = (case fold (curry add_typ_tfree_names) cargs' [] \\ tvs of
berghofe@5279
   884
                [] => ()
berghofe@5279
   885
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
haftmann@20597
   886
          in (constrs @ [((if flat_names then Sign.full_name tmp_thy else
haftmann@20597
   887
                Sign.full_name_path tmp_thy tname) (Syntax.const_name cname mx'),
berghofe@5177
   888
                   map (dtyp_of_typ new_dts) cargs')],
berghofe@5177
   889
              constr_syntax' @ [(cname, mx')], sorts'')
wenzelm@18678
   890
          end handle ERROR msg =>
wenzelm@18678
   891
            cat_error msg ("The error above occured in constructor " ^ cname ^
berghofe@5177
   892
              " of datatype " ^ tname);
berghofe@5177
   893
berghofe@5177
   894
        val (constrs', constr_syntax', sorts') =
haftmann@21045
   895
          fold prep_constr constrs ([], [], sorts)
berghofe@5177
   896
wenzelm@8405
   897
      in
wenzelm@18964
   898
        case duplicates (op =) (map fst constrs') of
berghofe@5177
   899
           [] =>
haftmann@20597
   900
             (dts' @ [(i, (Sign.full_name tmp_thy (Syntax.type_name tname mx),
berghofe@5177
   901
                map DtTFree tvs, constrs'))],
berghofe@5177
   902
              constr_syntax @ [constr_syntax'], sorts', i + 1)
berghofe@5177
   903
         | dups => error ("Duplicate constructors " ^ commas dups ^
berghofe@5177
   904
             " in datatype " ^ tname)
berghofe@5177
   905
      end;
berghofe@5177
   906
haftmann@21045
   907
    val (dts', constr_syntax, sorts', i) = fold prep_dt_spec dts ([], [], [], 0);
haftmann@20597
   908
    val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (tyvars \\ map fst sorts'));
berghofe@5177
   909
    val dt_info = get_datatypes thy;
haftmann@20597
   910
    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
berghofe@14887
   911
    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
wenzelm@15661
   912
      if err then error ("Nonemptiness check failed for datatype " ^ s)
berghofe@14887
   913
      else raise exn;
berghofe@5177
   914
haftmann@21045
   915
    val descr' = flat descr;
wenzelm@8437
   916
    val case_names_induct = mk_case_names_induct descr';
wenzelm@8437
   917
    val case_names_exhausts = mk_case_names_exhausts descr' (map #1 new_dts);
berghofe@5177
   918
  in
berghofe@5177
   919
    (if (!quick_and_dirty) then add_datatype_axm else add_datatype_def)
wenzelm@8437
   920
      flat_names new_type_names descr sorts types_syntax constr_syntax dt_info
wenzelm@8437
   921
      case_names_induct case_names_exhausts thy
berghofe@5177
   922
  end;
berghofe@5177
   923
berghofe@5177
   924
val add_datatype_i = gen_add_datatype cert_typ;
berghofe@14887
   925
val add_datatype = gen_add_datatype read_typ true;
berghofe@5177
   926
wenzelm@6360
   927
haftmann@18451
   928
wenzelm@6360
   929
(** package setup **)
wenzelm@6360
   930
wenzelm@6360
   931
(* setup theory *)
wenzelm@6360
   932
wenzelm@18708
   933
val setup =
wenzelm@24098
   934
  DatatypeProp.distinctness_limit_setup #>
wenzelm@24098
   935
  Method.add_methods tactic_emulations #>
wenzelm@24098
   936
  simproc_setup #>
wenzelm@24098
   937
  trfun_setup;
wenzelm@6360
   938
wenzelm@6360
   939
wenzelm@6360
   940
(* outer syntax *)
wenzelm@6360
   941
wenzelm@17057
   942
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6360
   943
wenzelm@6360
   944
val datatype_decl =
wenzelm@6723
   945
  Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
wenzelm@12876
   946
    (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
wenzelm@6360
   947
wenzelm@6360
   948
fun mk_datatype args =
wenzelm@6360
   949
  let
skalberg@15531
   950
    val names = map (fn ((((NONE, _), t), _), _) => t | ((((SOME t, _), _), _), _) => t) args;
wenzelm@12876
   951
    val specs = map (fn ((((_, vs), t), mx), cons) =>
wenzelm@12876
   952
      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
haftmann@18008
   953
  in snd o add_datatype false names specs end;
wenzelm@6360
   954
wenzelm@6360
   955
val datatypeP =
wenzelm@6723
   956
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
wenzelm@6723
   957
    (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
wenzelm@6360
   958
wenzelm@6385
   959
wenzelm@6385
   960
val rep_datatype_decl =
wenzelm@6723
   961
  Scan.option (Scan.repeat1 P.name) --
wenzelm@22101
   962
    Scan.optional (P.$$$ "distinct" |-- P.!!! (P.and_list1 SpecParse.xthms1)) [[]] --
wenzelm@22101
   963
    Scan.optional (P.$$$ "inject" |-- P.!!! (P.and_list1 SpecParse.xthms1)) [[]] --
wenzelm@22101
   964
    (P.$$$ "induction" |-- P.!!! SpecParse.xthm);
wenzelm@6385
   965
haftmann@18008
   966
fun mk_rep_datatype (((opt_ts, dss), iss), ind) = #2 o rep_datatype opt_ts dss iss ind;
wenzelm@6385
   967
wenzelm@6385
   968
val rep_datatypeP =
wenzelm@6723
   969
  OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_decl
wenzelm@6385
   970
    (rep_datatype_decl >> (Toplevel.theory o mk_rep_datatype));
wenzelm@6385
   971
wenzelm@6385
   972
wenzelm@6479
   973
val _ = OuterSyntax.add_keywords ["distinct", "inject", "induction"];
wenzelm@6385
   974
val _ = OuterSyntax.add_parsers [datatypeP, rep_datatypeP];
wenzelm@6385
   975
wenzelm@6385
   976
end;
wenzelm@6385
   977
wenzelm@6360
   978
berghofe@5177
   979
end;
berghofe@5177
   980
wenzelm@6360
   981
structure BasicDatatypePackage: BASIC_DATATYPE_PACKAGE = DatatypePackage;
wenzelm@6360
   982
open BasicDatatypePackage;
wenzelm@15704
   983