src/HOL/Tools/Datatype/datatype.ML
author haftmann
Tue Nov 24 17:28:25 2009 +0100 (2009-11-24)
changeset 33955 fff6f11b1f09
parent 33522 737589bb9bb8
child 33957 e9afca2118d4
permissions -rw-r--r--
curried take/drop
haftmann@31723
     1
(*  Title:      HOL/Tools/datatype.ML
wenzelm@11539
     2
    Author:     Stefan Berghofer, TU Muenchen
berghofe@5177
     3
wenzelm@6360
     4
Datatype package for Isabelle/HOL.
berghofe@5177
     5
*)
berghofe@5177
     6
haftmann@31723
     7
signature DATATYPE =
wenzelm@6360
     8
sig
haftmann@31735
     9
  include DATATYPE_COMMON
haftmann@31735
    10
  val add_datatype : config -> string list -> (string list * binding * mixfix *
haftmann@31783
    11
    (binding * typ list * mixfix) list) list -> theory -> string list * theory
haftmann@31735
    12
  val datatype_cmd : string list -> (string list * binding * mixfix *
haftmann@31735
    13
    (binding * string list * mixfix) list) list -> theory -> theory
haftmann@31781
    14
  val rep_datatype : config -> (string list -> Proof.context -> Proof.context)
haftmann@31735
    15
    -> string list option -> term list -> theory -> Proof.state
haftmann@31735
    16
  val rep_datatype_cmd : string list option -> string list -> theory -> Proof.state
haftmann@31784
    17
  val get_info : theory -> string -> info option
haftmann@31784
    18
  val the_info : theory -> string -> info
haftmann@31784
    19
  val the_descr : theory -> string list
haftmann@31735
    20
    -> descr * (string * sort) list * string list
haftmann@31868
    21
      * string * (string list * string list) * (typ list * typ list)
haftmann@31784
    22
  val the_spec : theory -> string -> (string * sort) list * (string * typ list) list
haftmann@32911
    23
  val all_distincts : theory -> typ list -> thm list list
haftmann@31784
    24
  val get_constrs : theory -> string -> (string * typ) list option
haftmann@31784
    25
  val get_all : theory -> info Symtab.table
haftmann@32896
    26
  val info_of_constr : theory -> string * typ -> info option
haftmann@31784
    27
  val info_of_case : theory -> string -> info option
haftmann@31735
    28
  val interpretation : (config -> string list -> theory -> theory) -> theory -> theory
bulwahn@32671
    29
  val make_case :  Proof.context -> DatatypeCase.config -> string list -> term ->
haftmann@31735
    30
    (term * term) list -> term * (term * (int * bool)) list
haftmann@31735
    31
  val strip_case : Proof.context -> bool -> term -> (term * (term * term) list) option
wenzelm@33244
    32
  val read_typ: theory -> string -> (string * sort) list -> typ * (string * sort) list
wenzelm@18708
    33
  val setup: theory -> theory
berghofe@5177
    34
end;
berghofe@5177
    35
haftmann@31723
    36
structure Datatype : DATATYPE =
berghofe@5177
    37
struct
berghofe@5177
    38
berghofe@5177
    39
open DatatypeAux;
berghofe@5177
    40
haftmann@32717
    41
(** theory data **)
wenzelm@6360
    42
haftmann@32717
    43
(* data management *)
berghofe@5177
    44
wenzelm@33522
    45
structure DatatypesData = Theory_Data
wenzelm@22846
    46
(
berghofe@22777
    47
  type T =
haftmann@31735
    48
    {types: info Symtab.table,
haftmann@32896
    49
     constrs: (string * info) list Symtab.table,
haftmann@31735
    50
     cases: info Symtab.table};
berghofe@5177
    51
berghofe@22777
    52
  val empty =
berghofe@22777
    53
    {types = Symtab.empty, constrs = Symtab.empty, cases = Symtab.empty};
wenzelm@16430
    54
  val extend = I;
wenzelm@33522
    55
  fun merge
berghofe@22777
    56
    ({types = types1, constrs = constrs1, cases = cases1},
wenzelm@33522
    57
     {types = types2, constrs = constrs2, cases = cases2}) : T =
berghofe@22777
    58
    {types = Symtab.merge (K true) (types1, types2),
haftmann@32896
    59
     constrs = Symtab.join (K (AList.merge (op =) (K true))) (constrs1, constrs2),
berghofe@22777
    60
     cases = Symtab.merge (K true) (cases1, cases2)};
wenzelm@22846
    61
);
berghofe@5177
    62
haftmann@31784
    63
val get_all = #types o DatatypesData.get;
haftmann@32717
    64
val get_info = Symtab.lookup o get_all;
wenzelm@33303
    65
wenzelm@33303
    66
fun the_info thy name =
wenzelm@33303
    67
  (case get_info thy name of
wenzelm@33303
    68
    SOME info => info
wenzelm@33303
    69
  | NONE => error ("Unknown datatype " ^ quote name));
berghofe@5177
    70
haftmann@32896
    71
fun info_of_constr thy (c, T) =
haftmann@32896
    72
  let
haftmann@32896
    73
    val tab = Symtab.lookup_list ((#constrs o DatatypesData.get) thy) c;
haftmann@32896
    74
    val hint = case strip_type T of (_, Type (tyco, _)) => SOME tyco | _ => NONE;
haftmann@32896
    75
    val default = if null tab then NONE
haftmann@32896
    76
      else SOME (snd (Library.last_elem tab))
haftmann@32896
    77
        (*conservative wrt. overloaded constructors*);
haftmann@32896
    78
  in case hint
haftmann@32896
    79
   of NONE => default
haftmann@32896
    80
    | SOME tyco => case AList.lookup (op =) tab tyco
haftmann@32896
    81
       of NONE => default (*permissive*)
haftmann@32896
    82
        | SOME info => SOME info
haftmann@32896
    83
  end;
haftmann@32896
    84
haftmann@32717
    85
val info_of_case = Symtab.lookup o #cases o DatatypesData.get;
berghofe@5177
    86
haftmann@32717
    87
fun register (dt_infos : (string * info) list) =
haftmann@32717
    88
  DatatypesData.map (fn {types, constrs, cases} =>
haftmann@32896
    89
    {types = types |> fold Symtab.update dt_infos,
haftmann@32896
    90
     constrs = constrs |> fold (fn (constr, dtname_info) =>
haftmann@32896
    91
         Symtab.map_default (constr, []) (cons dtname_info))
haftmann@32896
    92
       (maps (fn (dtname, info as {descr, index, ...}) =>
haftmann@32896
    93
          map (rpair (dtname, info) o fst)
haftmann@32896
    94
            (#3 (the (AList.lookup op = descr index)))) dt_infos),
haftmann@32896
    95
     cases = cases |> fold Symtab.update
haftmann@32896
    96
       (map (fn (_, info as {case_name, ...}) => (case_name, info)) dt_infos)});
berghofe@22777
    97
wenzelm@33313
    98
haftmann@32717
    99
(* complex queries *)
berghofe@7015
   100
haftmann@31784
   101
fun the_spec thy dtco =
haftmann@18518
   102
  let
haftmann@31784
   103
    val info as { descr, index, sorts = raw_sorts, ... } = the_info thy dtco;
haftmann@26093
   104
    val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr index;
haftmann@26093
   105
    val sorts = map ((fn v => (v, (the o AList.lookup (op =) raw_sorts) v))
haftmann@26093
   106
      o DatatypeAux.dest_DtTFree) dtys;
haftmann@26093
   107
    val cos = map
haftmann@26093
   108
      (fn (co, tys) => (co, map (DatatypeAux.typ_of_dtyp descr sorts) tys)) raw_cos;
haftmann@26093
   109
  in (sorts, cos) end;
haftmann@18518
   110
haftmann@31784
   111
fun the_descr thy (raw_tycos as raw_tyco :: _) =
haftmann@31604
   112
  let
haftmann@31784
   113
    val info = the_info thy raw_tyco;
haftmann@31604
   114
    val descr = #descr info;
haftmann@31604
   115
haftmann@31604
   116
    val SOME (_, dtys, raw_cos) = AList.lookup (op =) descr (#index info);
haftmann@31604
   117
    val vs = map ((fn v => (v, (the o AList.lookup (op =) (#sorts info)) v))
haftmann@31604
   118
      o dest_DtTFree) dtys;
haftmann@31604
   119
haftmann@31604
   120
    fun is_DtTFree (DtTFree _) = true
haftmann@31604
   121
      | is_DtTFree _ = false
haftmann@31604
   122
    val k = find_index (fn (_, (_, dTs, _)) => not (forall is_DtTFree dTs)) descr;
haftmann@31604
   123
    val protoTs as (dataTs, _) = chop k descr
haftmann@31604
   124
      |> (pairself o map) (fn (_, (tyco, dTs, _)) => (tyco, map (typ_of_dtyp descr vs) dTs));
haftmann@31604
   125
    
haftmann@31604
   126
    val tycos = map fst dataTs;
haftmann@33038
   127
    val _ = if eq_set (op =) (tycos, raw_tycos) then ()
haftmann@31604
   128
      else error ("Type constructors " ^ commas (map quote raw_tycos)
haftmann@32374
   129
        ^ " do not belong exhaustively to one mutual recursive datatype");
haftmann@31604
   130
haftmann@31604
   131
    val (Ts, Us) = (pairself o map) Type protoTs;
haftmann@31604
   132
haftmann@31604
   133
    val names = map Long_Name.base_name (the_default tycos (#alt_names info));
haftmann@31604
   134
    val (auxnames, _) = Name.make_context names
haftmann@31868
   135
      |> fold_map (yield_singleton Name.variants o name_of_typ) Us;
haftmann@31868
   136
    val prefix = space_implode "_" names;
haftmann@31604
   137
haftmann@31868
   138
  in (descr, vs, tycos, prefix, (names, auxnames), (Ts, Us)) end;
haftmann@31604
   139
haftmann@32911
   140
fun all_distincts thy Ts =
haftmann@32911
   141
  let
haftmann@32911
   142
    fun add_tycos (Type (tyco, Ts)) = insert (op =) tyco #> fold add_tycos Ts
haftmann@32911
   143
      | add_tycos _ = I;
haftmann@32911
   144
    val tycos = fold add_tycos Ts [];
haftmann@32911
   145
  in map_filter (Option.map #distinct o get_info thy) tycos end;
haftmann@32911
   146
haftmann@31784
   147
fun get_constrs thy dtco =
haftmann@31784
   148
  case try (the_spec thy) dtco
haftmann@19346
   149
   of SOME (sorts, cos) =>
haftmann@19346
   150
        let
haftmann@19346
   151
          fun subst (v, sort) = TVar ((v, 0), sort);
haftmann@19346
   152
          fun subst_ty (TFree v) = subst v
haftmann@19346
   153
            | subst_ty ty = ty;
haftmann@19346
   154
          val dty = Type (dtco, map subst sorts);
haftmann@19346
   155
          fun mk_co (co, tys) = (co, map (Term.map_atyps subst_ty) tys ---> dty);
haftmann@19346
   156
        in SOME (map mk_co cos) end
haftmann@19346
   157
    | NONE => NONE;
haftmann@18518
   158
berghofe@5177
   159
wenzelm@33313
   160
haftmann@32717
   161
(** various auxiliary **)
wenzelm@8437
   162
haftmann@32717
   163
(* prepare datatype specifications *)
berghofe@5177
   164
wenzelm@33244
   165
fun read_typ thy str sorts =
berghofe@5177
   166
  let
wenzelm@27277
   167
    val ctxt = ProofContext.init thy
wenzelm@27277
   168
      |> fold (Variable.declare_typ o TFree) sorts;
wenzelm@27277
   169
    val T = Syntax.read_typ ctxt str;
wenzelm@33244
   170
  in (T, Term.add_tfreesT T sorts) end;
berghofe@5177
   171
wenzelm@33244
   172
fun cert_typ sign raw_T sorts =
berghofe@5177
   173
  let
wenzelm@33244
   174
    val T = Type.no_tvars (Sign.certify_typ sign raw_T)
wenzelm@33244
   175
      handle TYPE (msg, _, _) => error msg;
wenzelm@27277
   176
    val sorts' = Term.add_tfreesT T sorts;
wenzelm@33244
   177
    val _ =
wenzelm@18964
   178
      case duplicates (op =) (map fst sorts') of
wenzelm@33244
   179
        [] => ()
wenzelm@33244
   180
      | dups => error ("Inconsistent sort constraints for " ^ commas dups)
wenzelm@33244
   181
  in (T, sorts') end;
wenzelm@33244
   182
berghofe@5177
   183
haftmann@32717
   184
(* case names *)
haftmann@32717
   185
haftmann@32717
   186
local
haftmann@32717
   187
haftmann@32717
   188
fun dt_recs (DtTFree _) = []
haftmann@32717
   189
  | dt_recs (DtType (_, dts)) = maps dt_recs dts
haftmann@32717
   190
  | dt_recs (DtRec i) = [i];
haftmann@32717
   191
haftmann@32717
   192
fun dt_cases (descr: descr) (_, args, constrs) =
haftmann@32717
   193
  let
haftmann@32717
   194
    fun the_bname i = Long_Name.base_name (#1 (the (AList.lookup (op =) descr i)));
haftmann@32717
   195
    val bnames = map the_bname (distinct (op =) (maps dt_recs args));
haftmann@32717
   196
  in map (fn (c, _) => space_implode "_" (Long_Name.base_name c :: bnames)) constrs end;
haftmann@32717
   197
haftmann@32717
   198
fun induct_cases descr =
haftmann@32717
   199
  DatatypeProp.indexify_names (maps (dt_cases descr) (map #2 descr));
haftmann@32717
   200
haftmann@32717
   201
fun exhaust_cases descr i = dt_cases descr (the (AList.lookup (op =) descr i));
haftmann@32717
   202
haftmann@32717
   203
in
haftmann@32717
   204
wenzelm@33368
   205
fun mk_case_names_induct descr = Rule_Cases.case_names (induct_cases descr);
haftmann@32717
   206
haftmann@32717
   207
fun mk_case_names_exhausts descr new =
wenzelm@33368
   208
  map (Rule_Cases.case_names o exhaust_cases descr o #1)
haftmann@32717
   209
    (filter (fn ((_, (name, _, _))) => member (op =) new name) descr);
haftmann@32717
   210
haftmann@32717
   211
end;
haftmann@32717
   212
wenzelm@33313
   213
haftmann@32717
   214
(* translation rules for case *)
berghofe@5177
   215
haftmann@32717
   216
fun make_case ctxt = DatatypeCase.make_case
haftmann@32717
   217
  (info_of_constr (ProofContext.theory_of ctxt)) ctxt;
haftmann@32717
   218
haftmann@32717
   219
fun strip_case ctxt = DatatypeCase.strip_case
haftmann@32717
   220
  (info_of_case (ProofContext.theory_of ctxt));
berghofe@5177
   221
haftmann@32717
   222
fun add_case_tr' case_names thy =
haftmann@32717
   223
  Sign.add_advanced_trfuns ([], [],
haftmann@32717
   224
    map (fn case_name =>
haftmann@32717
   225
      let val case_name' = Sign.const_syntax_name thy case_name
haftmann@32717
   226
      in (case_name', DatatypeCase.case_tr' info_of_case case_name')
haftmann@32717
   227
      end) case_names, []) thy;
berghofe@5177
   228
haftmann@32717
   229
val trfun_setup =
haftmann@32717
   230
  Sign.add_advanced_trfuns ([],
haftmann@32717
   231
    [("_case_syntax", DatatypeCase.case_tr true info_of_constr)],
haftmann@32717
   232
    [], []);
haftmann@32717
   233
haftmann@33062
   234
wenzelm@33313
   235
haftmann@33062
   236
(** document antiquotation **)
berghofe@5177
   237
haftmann@32717
   238
val _ = ThyOutput.antiquotation "datatype" Args.tyname
haftmann@32717
   239
  (fn {source = src, context = ctxt, ...} => fn dtco =>
haftmann@32717
   240
    let
haftmann@32717
   241
      val thy = ProofContext.theory_of ctxt;
haftmann@32717
   242
      val (vs, cos) = the_spec thy dtco;
haftmann@32717
   243
      val ty = Type (dtco, map TFree vs);
haftmann@32717
   244
      fun pretty_typ_bracket (ty as Type (_, _ :: _)) =
haftmann@32717
   245
            Pretty.enclose "(" ")" [Syntax.pretty_typ ctxt ty]
haftmann@32717
   246
        | pretty_typ_bracket ty =
haftmann@32717
   247
            Syntax.pretty_typ ctxt ty;
haftmann@32717
   248
      fun pretty_constr (co, tys) =
haftmann@32717
   249
        (Pretty.block o Pretty.breaks)
haftmann@32717
   250
          (Syntax.pretty_term ctxt (Const (co, tys ---> ty)) ::
haftmann@32717
   251
            map pretty_typ_bracket tys);
haftmann@32717
   252
      val pretty_datatype =
haftmann@32717
   253
        Pretty.block
haftmann@32717
   254
          (Pretty.command "datatype" :: Pretty.brk 1 ::
haftmann@32717
   255
           Syntax.pretty_typ ctxt ty ::
haftmann@32717
   256
           Pretty.str " =" :: Pretty.brk 1 ::
haftmann@32717
   257
           flat (separate [Pretty.brk 1, Pretty.str "| "]
haftmann@32717
   258
             (map (single o pretty_constr) cos)));
haftmann@32717
   259
    in ThyOutput.output (ThyOutput.maybe_pretty_source (K pretty_datatype) src [()]) end);
berghofe@5177
   260
berghofe@5177
   261
wenzelm@33313
   262
haftmann@32721
   263
(** abstract theory extensions relative to a datatype characterisation **)
haftmann@32721
   264
wenzelm@33314
   265
structure Datatype_Interpretation = Interpretation
haftmann@32721
   266
  (type T = config * string list val eq: T * T -> bool = eq_snd op =);
wenzelm@33313
   267
fun interpretation f = Datatype_Interpretation.interpretation (uncurry f);
haftmann@32721
   268
haftmann@32729
   269
fun make_dt_info alt_names descr sorts induct inducts rec_names rec_rewrites
haftmann@32729
   270
    (index, (((((((((((_, (tname, _, _))), inject), distinct),
wenzelm@33313
   271
      exhaust), nchotomy), case_name), case_rewrites), case_cong), weak_case_cong),
wenzelm@33313
   272
        (split, split_asm))) =
haftmann@32729
   273
  (tname,
haftmann@32729
   274
   {index = index,
haftmann@32729
   275
    alt_names = alt_names,
haftmann@32729
   276
    descr = descr,
haftmann@32729
   277
    sorts = sorts,
haftmann@32729
   278
    inject = inject,
haftmann@32729
   279
    distinct = distinct,
haftmann@32729
   280
    induct = induct,
haftmann@32729
   281
    inducts = inducts,
haftmann@32729
   282
    exhaust = exhaust,
haftmann@32729
   283
    nchotomy = nchotomy,
haftmann@32729
   284
    rec_names = rec_names,
haftmann@32729
   285
    rec_rewrites = rec_rewrites,
haftmann@32729
   286
    case_name = case_name,
haftmann@32729
   287
    case_rewrites = case_rewrites,
haftmann@32729
   288
    case_cong = case_cong,
haftmann@32729
   289
    weak_case_cong = weak_case_cong,
haftmann@32729
   290
    split = split,
haftmann@32729
   291
    split_asm = split_asm});
haftmann@32729
   292
haftmann@32728
   293
fun derive_datatype_props config dt_names alt_names descr sorts
haftmann@32907
   294
    induct inject distinct thy1 =
haftmann@32721
   295
  let
haftmann@32729
   296
    val thy2 = thy1 |> Theory.checkpoint;
haftmann@32728
   297
    val flat_descr = flat descr;
haftmann@32719
   298
    val new_type_names = map Long_Name.base_name (the_default dt_names alt_names);
haftmann@32728
   299
    val _ = message config ("Deriving properties for datatype(s) " ^ commas_quote new_type_names);
haftmann@32729
   300
haftmann@32729
   301
    val (exhaust, thy3) = DatatypeAbsProofs.prove_casedist_thms config new_type_names
haftmann@32729
   302
      descr sorts induct (mk_case_names_exhausts flat_descr dt_names) thy2;
haftmann@32729
   303
    val (nchotomys, thy4) = DatatypeAbsProofs.prove_nchotomys config new_type_names
haftmann@32729
   304
      descr sorts exhaust thy3;
haftmann@32729
   305
    val ((rec_names, rec_rewrites), thy5) = DatatypeAbsProofs.prove_primrec_thms
haftmann@32729
   306
      config new_type_names descr sorts (#inject o the o Symtab.lookup (get_all thy4))
haftmann@32915
   307
      inject (distinct, all_distincts thy2 (get_rec_types flat_descr sorts))
haftmann@32911
   308
      induct thy4;
haftmann@32729
   309
    val ((case_rewrites, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
haftmann@32729
   310
      config new_type_names descr sorts rec_names rec_rewrites thy5;
haftmann@32729
   311
    val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
haftmann@32729
   312
      descr sorts nchotomys case_rewrites thy6;
haftmann@32729
   313
    val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
haftmann@32729
   314
      descr sorts thy7;
haftmann@32731
   315
    val (splits, thy9) = DatatypeAbsProofs.prove_split_thms
haftmann@32907
   316
      config new_type_names descr sorts inject distinct exhaust case_rewrites thy8;
berghofe@5177
   317
haftmann@32731
   318
    val inducts = Project_Rule.projections (ProofContext.init thy2) induct;
wenzelm@33313
   319
    val dt_infos = map_index
wenzelm@33313
   320
      (make_dt_info alt_names flat_descr sorts induct inducts rec_names rec_rewrites)
haftmann@32907
   321
      (hd descr ~~ inject ~~ distinct ~~ exhaust ~~ nchotomys ~~
haftmann@32731
   322
        case_names ~~ case_rewrites ~~ case_congs ~~ weak_case_congs ~~ splits);
haftmann@31781
   323
    val dt_names = map fst dt_infos;
haftmann@32731
   324
    val prfx = Binding.qualify true (space_implode "_" new_type_names);
haftmann@32907
   325
    val simps = flat (inject @ distinct @ case_rewrites) @ rec_rewrites;
haftmann@32731
   326
    val named_rules = flat (map_index (fn (index, tname) =>
haftmann@32731
   327
      [((Binding.empty, [nth inducts index]), [Induct.induct_type tname]),
haftmann@32731
   328
       ((Binding.empty, [nth exhaust index]), [Induct.cases_type tname])]) dt_names);
haftmann@32731
   329
    val unnamed_rules = map (fn induct =>
wenzelm@33368
   330
      ((Binding.empty, [induct]), [Rule_Cases.inner_rule, Induct.induct_type ""]))
haftmann@33955
   331
        ((uncurry drop) (length dt_names, inducts));
haftmann@32720
   332
  in
haftmann@32720
   333
    thy9
haftmann@32731
   334
    |> PureThy.add_thmss ([((prfx (Binding.name "simps"), simps), []),
haftmann@32731
   335
        ((prfx (Binding.name "inducts"), inducts), []),
haftmann@32731
   336
        ((prfx (Binding.name "splits"), maps (fn (x, y) => [x, y]) splits), []),
haftmann@32907
   337
        ((Binding.empty, flat case_rewrites @ flat distinct @ rec_rewrites),
haftmann@32731
   338
          [Simplifier.simp_add]),
haftmann@32731
   339
        ((Binding.empty, rec_rewrites), [Code.add_default_eqn_attribute]),
haftmann@32731
   340
        ((Binding.empty, flat inject), [iff_add]),
haftmann@32907
   341
        ((Binding.empty, map (fn th => th RS notE) (flat distinct)),
haftmann@32731
   342
          [Classical.safe_elim NONE]),
haftmann@32731
   343
        ((Binding.empty, weak_case_congs), [Simplifier.attrib (op addcongs)])]
haftmann@32731
   344
        @ named_rules @ unnamed_rules)
haftmann@32720
   345
    |> snd
haftmann@32730
   346
    |> add_case_tr' case_names
haftmann@32730
   347
    |> register dt_infos
wenzelm@33313
   348
    |> Datatype_Interpretation.data (config, dt_names)
haftmann@32720
   349
    |> pair dt_names
haftmann@32720
   350
  end;
berghofe@5177
   351
haftmann@32721
   352
wenzelm@33313
   353
haftmann@32721
   354
(** declare existing type as datatype **)
haftmann@32721
   355
wenzelm@33313
   356
fun prove_rep_datatype config dt_names alt_names descr sorts
wenzelm@33313
   357
    raw_inject half_distinct raw_induct thy1 =
haftmann@32721
   358
  let
haftmann@32721
   359
    val raw_distinct = (map o maps) (fn thm => [thm, thm RS not_sym]) half_distinct;
haftmann@32721
   360
    val new_type_names = map Long_Name.base_name (the_default dt_names alt_names);
haftmann@32721
   361
    val (((inject, distinct), [induct]), thy2) =
haftmann@32721
   362
      thy1
haftmann@32721
   363
      |> store_thmss "inject" new_type_names raw_inject
haftmann@32721
   364
      ||>> store_thmss "distinct" new_type_names raw_distinct
haftmann@32721
   365
      ||> Sign.add_path (space_implode "_" new_type_names)
haftmann@32729
   366
      ||>> PureThy.add_thms [((Binding.name "induct", raw_induct), [mk_case_names_induct descr])]
haftmann@32729
   367
      ||> Sign.restore_naming thy1;
haftmann@32722
   368
  in
haftmann@32722
   369
    thy2
haftmann@32728
   370
    |> derive_datatype_props config dt_names alt_names [descr] sorts
haftmann@32907
   371
         induct inject distinct
haftmann@32722
   372
 end;
haftmann@32721
   373
haftmann@32721
   374
fun gen_rep_datatype prep_term config after_qed alt_names raw_ts thy =
haftmann@27104
   375
  let
haftmann@27104
   376
    fun constr_of_term (Const (c, T)) = (c, T)
haftmann@27104
   377
      | constr_of_term t =
haftmann@27104
   378
          error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
haftmann@27104
   379
    fun no_constr (c, T) = error ("Bad constructor: "
haftmann@27104
   380
      ^ Sign.extern_const thy c ^ "::"
haftmann@27104
   381
      ^ Syntax.string_of_typ_global thy T);
haftmann@27104
   382
    fun type_of_constr (cT as (_, T)) =
haftmann@27104
   383
      let
wenzelm@29270
   384
        val frees = OldTerm.typ_tfrees T;
haftmann@27104
   385
        val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) T
haftmann@27104
   386
          handle TYPE _ => no_constr cT
haftmann@27104
   387
        val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
haftmann@27104
   388
        val _ = if length frees <> length vs then no_constr cT else ();
haftmann@27104
   389
      in (tyco, (vs, cT)) end;
haftmann@27104
   390
haftmann@27104
   391
    val raw_cs = AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
haftmann@27104
   392
    val _ = case map_filter (fn (tyco, _) =>
haftmann@31784
   393
        if Symtab.defined (get_all thy) tyco then SOME tyco else NONE) raw_cs
haftmann@27104
   394
     of [] => ()
haftmann@27104
   395
      | tycos => error ("Type(s) " ^ commas (map quote tycos)
haftmann@27104
   396
          ^ " already represented inductivly");
haftmann@27104
   397
    val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
haftmann@27104
   398
    val ms = case distinct (op =) (map length raw_vss)
haftmann@27104
   399
     of [n] => 0 upto n - 1
haftmann@27104
   400
      | _ => error ("Different types in given constructors");
haftmann@27104
   401
    fun inter_sort m = map (fn xs => nth xs m) raw_vss
haftmann@27104
   402
      |> Library.foldr1 (Sorts.inter_sort (Sign.classes_of thy))
haftmann@27104
   403
    val sorts = map inter_sort ms;
haftmann@27104
   404
    val vs = Name.names Name.context Name.aT sorts;
haftmann@27104
   405
haftmann@27104
   406
    fun norm_constr (raw_vs, (c, T)) = (c, map_atyps
haftmann@27104
   407
      (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
haftmann@27104
   408
haftmann@27104
   409
    val cs = map (apsnd (map norm_constr)) raw_cs;
haftmann@27104
   410
    val dtyps_of_typ = map (dtyp_of_typ (map (rpair (map fst vs) o fst) cs))
haftmann@27104
   411
      o fst o strip_type;
haftmann@32719
   412
    val dt_names = map fst cs;
haftmann@27104
   413
haftmann@27104
   414
    fun mk_spec (i, (tyco, constr)) = (i, (tyco,
haftmann@27104
   415
      map (DtTFree o fst) vs,
haftmann@27104
   416
      (map o apsnd) dtyps_of_typ constr))
haftmann@27104
   417
    val descr = map_index mk_spec cs;
haftmann@27104
   418
    val injs = DatatypeProp.make_injs [descr] vs;
haftmann@27300
   419
    val half_distincts = map snd (DatatypeProp.make_distincts [descr] vs);
haftmann@27104
   420
    val ind = DatatypeProp.make_ind [descr] vs;
haftmann@27300
   421
    val rules = (map o map o map) Logic.close_form [[[ind]], injs, half_distincts];
haftmann@27104
   422
haftmann@27104
   423
    fun after_qed' raw_thms =
haftmann@27104
   424
      let
haftmann@32729
   425
        val [[[raw_induct]], raw_inject, half_distinct] =
haftmann@27104
   426
          unflat rules (map Drule.zero_var_indexes_list raw_thms);
haftmann@27104
   427
            (*FIXME somehow dubious*)
haftmann@27104
   428
      in
haftmann@27104
   429
        ProofContext.theory_result
wenzelm@33313
   430
          (prove_rep_datatype config dt_names alt_names descr vs
wenzelm@33313
   431
            raw_inject half_distinct raw_induct)
haftmann@27104
   432
        #-> after_qed
haftmann@27104
   433
      end;
haftmann@27104
   434
  in
haftmann@27104
   435
    thy
haftmann@27104
   436
    |> ProofContext.init
haftmann@27104
   437
    |> Proof.theorem_i NONE after_qed' ((map o map) (rpair []) (flat rules))
haftmann@27104
   438
  end;
haftmann@27104
   439
haftmann@27104
   440
val rep_datatype = gen_rep_datatype Sign.cert_term;
haftmann@31735
   441
val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global default_config (K I);
wenzelm@6385
   442
berghofe@5177
   443
wenzelm@33313
   444
haftmann@32717
   445
(** definitional introduction of datatypes **)
wenzelm@11958
   446
haftmann@32721
   447
fun gen_add_datatype prep_typ config new_type_names dts thy =
berghofe@5177
   448
  let
wenzelm@20820
   449
    val _ = Theory.requires thy "Datatype" "datatype definitions";
berghofe@5177
   450
berghofe@5177
   451
    (* this theory is used just for parsing *)
berghofe@5177
   452
    val tmp_thy = thy |>
wenzelm@5892
   453
      Theory.copy |>
wenzelm@24712
   454
      Sign.add_types (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   455
        (tname, length tvs, mx)) dts);
berghofe@5177
   456
berghofe@5661
   457
    val (tyvars, _, _, _)::_ = dts;
berghofe@5177
   458
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
wenzelm@30345
   459
      let val full_tname = Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname)
wenzelm@33313
   460
      in
wenzelm@33313
   461
        (case duplicates (op =) tvs of
wenzelm@33313
   462
          [] =>
wenzelm@33313
   463
            if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
wenzelm@33313
   464
            else error ("Mutually recursive datatypes must have same type parameters")
wenzelm@33313
   465
        | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
wenzelm@33313
   466
            " : " ^ commas dups))
berghofe@5177
   467
      end) dts);
haftmann@32728
   468
    val dt_names = map fst new_dts;
berghofe@5177
   469
wenzelm@33313
   470
    val _ =
wenzelm@33313
   471
      (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
wenzelm@33313
   472
        [] => ()
wenzelm@33313
   473
      | dups => error ("Duplicate datatypes: " ^ commas dups));
berghofe@5177
   474
berghofe@31361
   475
    fun prep_dt_spec ((tvs, tname, mx, constrs), tname') (dts', constr_syntax, sorts, i) =
berghofe@5177
   476
      let
haftmann@21045
   477
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
berghofe@5279
   478
          let
wenzelm@33244
   479
            val (cargs', sorts'') = fold_map (prep_typ tmp_thy) cargs sorts';
wenzelm@33244
   480
            val _ =
wenzelm@33244
   481
              (case subtract (op =) tvs (fold (curry OldTerm.add_typ_tfree_names) cargs' []) of
berghofe@5279
   482
                [] => ()
berghofe@5279
   483
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
haftmann@32124
   484
          in (constrs @ [(Sign.full_name_path tmp_thy tname'
wenzelm@30345
   485
                  (Binding.map_name (Syntax.const_name mx') cname),
berghofe@5177
   486
                   map (dtyp_of_typ new_dts) cargs')],
berghofe@5177
   487
              constr_syntax' @ [(cname, mx')], sorts'')
wenzelm@30345
   488
          end handle ERROR msg => cat_error msg
wenzelm@30345
   489
           ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
wenzelm@30345
   490
            " of datatype " ^ quote (Binding.str_of tname));
berghofe@5177
   491
berghofe@5177
   492
        val (constrs', constr_syntax', sorts') =
haftmann@21045
   493
          fold prep_constr constrs ([], [], sorts)
berghofe@5177
   494
wenzelm@8405
   495
      in
wenzelm@18964
   496
        case duplicates (op =) (map fst constrs') of
berghofe@5177
   497
           [] =>
wenzelm@30345
   498
             (dts' @ [(i, (Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname),
berghofe@5177
   499
                map DtTFree tvs, constrs'))],
berghofe@5177
   500
              constr_syntax @ [constr_syntax'], sorts', i + 1)
berghofe@5177
   501
         | dups => error ("Duplicate constructors " ^ commas dups ^
wenzelm@30345
   502
             " in datatype " ^ quote (Binding.str_of tname))
berghofe@5177
   503
      end;
berghofe@5177
   504
berghofe@31361
   505
    val (dts', constr_syntax, sorts', i) =
berghofe@31361
   506
      fold prep_dt_spec (dts ~~ new_type_names) ([], [], [], 0);
haftmann@33040
   507
    val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (subtract (op =) (map fst sorts') tyvars));
haftmann@31784
   508
    val dt_info = get_all thy;
haftmann@20597
   509
    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
berghofe@14887
   510
    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
haftmann@31668
   511
      if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
berghofe@14887
   512
      else raise exn;
haftmann@32729
   513
haftmann@32729
   514
    val _ = message config ("Constructing datatype(s) " ^ commas_quote new_type_names);
haftmann@32907
   515
    val ((inject, distinct, induct), thy') = thy |>
haftmann@32729
   516
      DatatypeRepProofs.representation_proofs config dt_info new_type_names descr sorts
haftmann@32729
   517
        types_syntax constr_syntax (mk_case_names_induct (flat descr));
berghofe@5177
   518
  in
haftmann@32729
   519
    derive_datatype_props config dt_names (SOME new_type_names) descr sorts
haftmann@32907
   520
      induct inject distinct thy'
berghofe@5177
   521
  end;
berghofe@5177
   522
haftmann@27104
   523
val add_datatype = gen_add_datatype cert_typ;
haftmann@31735
   524
val datatype_cmd = snd ooo gen_add_datatype read_typ default_config;
berghofe@5177
   525
wenzelm@6360
   526
wenzelm@33313
   527
wenzelm@6360
   528
(** package setup **)
wenzelm@6360
   529
wenzelm@6360
   530
(* setup theory *)
wenzelm@6360
   531
wenzelm@18708
   532
val setup =
haftmann@24626
   533
  trfun_setup #>
wenzelm@33313
   534
  Datatype_Interpretation.init;
wenzelm@33313
   535
wenzelm@6360
   536
wenzelm@6360
   537
(* outer syntax *)
wenzelm@6360
   538
haftmann@31735
   539
local
wenzelm@6360
   540
haftmann@31735
   541
structure P = OuterParse and K = OuterKeyword
wenzelm@6360
   542
haftmann@31735
   543
fun prep_datatype_decls args =
wenzelm@6360
   544
  let
wenzelm@30345
   545
    val names = map
wenzelm@30345
   546
      (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
wenzelm@12876
   547
    val specs = map (fn ((((_, vs), t), mx), cons) =>
wenzelm@12876
   548
      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
haftmann@31735
   549
  in (names, specs) end;
haftmann@31735
   550
haftmann@31735
   551
val parse_datatype_decl =
haftmann@31735
   552
  (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_infix --
haftmann@31735
   553
    (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
haftmann@31735
   554
haftmann@31735
   555
val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
haftmann@31735
   556
haftmann@31735
   557
in
wenzelm@6360
   558
wenzelm@24867
   559
val _ =
wenzelm@6723
   560
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
haftmann@31735
   561
    (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
wenzelm@6360
   562
wenzelm@24867
   563
val _ =
haftmann@27104
   564
  OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_goal
haftmann@27104
   565
    (Scan.option (P.$$$ "(" |-- Scan.repeat1 P.name --| P.$$$ ")") -- Scan.repeat1 P.term
haftmann@27104
   566
      >> (fn (alt_names, ts) => Toplevel.print
haftmann@27104
   567
           o Toplevel.theory_to_proof (rep_datatype_cmd alt_names ts)));
wenzelm@6385
   568
wenzelm@30391
   569
end;
wenzelm@30391
   570
wenzelm@6385
   571
end;