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