src/HOL/Tools/Datatype/datatype.ML
author haftmann
Tue Oct 20 16:13:01 2009 +0200 (2009-10-20)
changeset 33037 b22e44496dc2
parent 32922 8e40cd05de7a
child 33038 8f9594c31de4
permissions -rw-r--r--
replaced old_style infixes eq_set, subset, union, inter and variants by generic versions
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
haftmann@31735
    29
  val distinct_simproc : simproc
bulwahn@32671
    30
  val make_case :  Proof.context -> DatatypeCase.config -> string list -> term ->
haftmann@31735
    31
    (term * term) list -> term * (term * (int * bool)) list
haftmann@31735
    32
  val strip_case : Proof.context -> bool -> term -> (term * (term * term) list) option
haftmann@31735
    33
  val read_typ: theory ->
haftmann@31735
    34
    (typ list * (string * sort) list) * string -> typ list * (string * sort) list
wenzelm@18708
    35
  val setup: theory -> theory
berghofe@5177
    36
end;
berghofe@5177
    37
haftmann@31723
    38
structure Datatype : DATATYPE =
berghofe@5177
    39
struct
berghofe@5177
    40
berghofe@5177
    41
open DatatypeAux;
berghofe@5177
    42
haftmann@32717
    43
(** theory data **)
wenzelm@6360
    44
haftmann@32717
    45
(* data management *)
berghofe@5177
    46
wenzelm@16430
    47
structure DatatypesData = TheoryDataFun
wenzelm@22846
    48
(
berghofe@22777
    49
  type T =
haftmann@31735
    50
    {types: info Symtab.table,
haftmann@32896
    51
     constrs: (string * info) list Symtab.table,
haftmann@31735
    52
     cases: info Symtab.table};
berghofe@5177
    53
berghofe@22777
    54
  val empty =
berghofe@22777
    55
    {types = Symtab.empty, constrs = Symtab.empty, cases = Symtab.empty};
wenzelm@6556
    56
  val copy = I;
wenzelm@16430
    57
  val extend = I;
berghofe@22777
    58
  fun merge _
berghofe@22777
    59
    ({types = types1, constrs = constrs1, cases = cases1},
berghofe@22777
    60
     {types = types2, constrs = constrs2, cases = cases2}) =
berghofe@22777
    61
    {types = Symtab.merge (K true) (types1, types2),
haftmann@32896
    62
     constrs = Symtab.join (K (AList.merge (op =) (K true))) (constrs1, constrs2),
berghofe@22777
    63
     cases = Symtab.merge (K true) (cases1, cases2)};
wenzelm@22846
    64
);
berghofe@5177
    65
haftmann@31784
    66
val get_all = #types o DatatypesData.get;
haftmann@32717
    67
val get_info = Symtab.lookup o get_all;
haftmann@32717
    68
fun the_info thy name = (case get_info thy name of
haftmann@32717
    69
      SOME info => info
haftmann@32717
    70
    | NONE => error ("Unknown datatype " ^ quote name));
berghofe@5177
    71
haftmann@32896
    72
fun info_of_constr thy (c, T) =
haftmann@32896
    73
  let
haftmann@32896
    74
    val tab = Symtab.lookup_list ((#constrs o DatatypesData.get) thy) c;
haftmann@32896
    75
    val hint = case strip_type T of (_, Type (tyco, _)) => SOME tyco | _ => NONE;
haftmann@32896
    76
    val default = if null tab then NONE
haftmann@32896
    77
      else SOME (snd (Library.last_elem tab))
haftmann@32896
    78
        (*conservative wrt. overloaded constructors*);
haftmann@32896
    79
  in case hint
haftmann@32896
    80
   of NONE => default
haftmann@32896
    81
    | SOME tyco => case AList.lookup (op =) tab tyco
haftmann@32896
    82
       of NONE => default (*permissive*)
haftmann@32896
    83
        | SOME info => SOME info
haftmann@32896
    84
  end;
haftmann@32896
    85
haftmann@32717
    86
val info_of_case = Symtab.lookup o #cases o DatatypesData.get;
berghofe@5177
    87
haftmann@32717
    88
fun register (dt_infos : (string * info) list) =
haftmann@32717
    89
  DatatypesData.map (fn {types, constrs, cases} =>
haftmann@32896
    90
    {types = types |> fold Symtab.update dt_infos,
haftmann@32896
    91
     constrs = constrs |> fold (fn (constr, dtname_info) =>
haftmann@32896
    92
         Symtab.map_default (constr, []) (cons dtname_info))
haftmann@32896
    93
       (maps (fn (dtname, info as {descr, index, ...}) =>
haftmann@32896
    94
          map (rpair (dtname, info) o fst)
haftmann@32896
    95
            (#3 (the (AList.lookup op = descr index)))) dt_infos),
haftmann@32896
    96
     cases = cases |> fold Symtab.update
haftmann@32896
    97
       (map (fn (_, info as {case_name, ...}) => (case_name, info)) dt_infos)});
berghofe@22777
    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@31604
   127
    val _ = if gen_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
haftmann@32717
   160
(** various auxiliary **)
wenzelm@8437
   161
haftmann@32717
   162
(* simplification procedure for showing distinctness of constructors *)
berghofe@7015
   163
berghofe@7060
   164
fun stripT (i, Type ("fun", [_, T])) = stripT (i + 1, T)
berghofe@7060
   165
  | stripT p = p;
berghofe@7060
   166
berghofe@7060
   167
fun stripC (i, f $ x) = stripC (i + 1, f)
berghofe@7060
   168
  | stripC p = p;
berghofe@7060
   169
berghofe@7015
   170
val distinctN = "constr_distinct";
berghofe@7015
   171
haftmann@32900
   172
fun distinct_rule thy ss tname eq_t = Goal.prove (Simplifier.the_context ss) [] [] eq_t
haftmann@32900
   173
  (K (EVERY [rtac eq_reflection 1, rtac iffI 1, rtac notE 1,
haftmann@32900
   174
    atac 2, resolve_tac (#distinct (the_info thy tname)) 1, etac FalseE 1]));
haftmann@25537
   175
haftmann@32717
   176
fun get_constr thy dtco =
haftmann@32717
   177
  get_info thy dtco
haftmann@32717
   178
  |> Option.map (fn { descr, index, ... } => (#3 o the o AList.lookup (op =) descr) index);
haftmann@32717
   179
wenzelm@19539
   180
fun distinct_proc thy ss (t as Const ("op =", _) $ t1 $ t2) =
berghofe@7060
   181
  (case (stripC (0, t1), stripC (0, t2)) of
berghofe@7060
   182
     ((i, Const (cname1, T1)), (j, Const (cname2, T2))) =>
berghofe@7060
   183
         (case (stripT (0, T1), stripT (0, T2)) of
berghofe@7060
   184
            ((i', Type (tname1, _)), (j', Type (tname2, _))) =>
berghofe@7060
   185
                if tname1 = tname2 andalso not (cname1 = cname2) andalso i = i' andalso j = j' then
haftmann@32717
   186
                   (case get_constr thy tname1 of
haftmann@32717
   187
                      SOME constrs => let val cnames = map fst constrs
berghofe@7015
   188
                        in if cname1 mem cnames andalso cname2 mem cnames then
haftmann@25537
   189
                             SOME (distinct_rule thy ss tname1
haftmann@32717
   190
                               (Logic.mk_equals (t, HOLogic.false_const)))
skalberg@15531
   191
                           else NONE
berghofe@7015
   192
                        end
skalberg@15531
   193
                    | NONE => NONE)
skalberg@15531
   194
                else NONE
skalberg@15531
   195
          | _ => NONE)
skalberg@15531
   196
   | _ => NONE)
wenzelm@20054
   197
  | distinct_proc _ _ _ = NONE;
berghofe@7015
   198
wenzelm@13462
   199
val distinct_simproc =
wenzelm@29064
   200
  Simplifier.simproc @{theory HOL} distinctN ["s = t"] distinct_proc;
berghofe@7015
   201
berghofe@7015
   202
val simproc_setup =
wenzelm@26496
   203
  Simplifier.map_simpset (fn ss => ss addsimprocs [distinct_simproc]);
berghofe@7015
   204
haftmann@32717
   205
(* prepare datatype specifications *)
berghofe@5177
   206
wenzelm@27277
   207
fun read_typ thy ((Ts, sorts), str) =
berghofe@5177
   208
  let
wenzelm@27277
   209
    val ctxt = ProofContext.init thy
wenzelm@27277
   210
      |> fold (Variable.declare_typ o TFree) sorts;
wenzelm@27277
   211
    val T = Syntax.read_typ ctxt str;
wenzelm@27277
   212
  in (Ts @ [T], Term.add_tfreesT T sorts) end;
berghofe@5177
   213
berghofe@5177
   214
fun cert_typ sign ((Ts, sorts), raw_T) =
berghofe@5177
   215
  let
berghofe@5177
   216
    val T = Type.no_tvars (Sign.certify_typ sign raw_T) handle
berghofe@5177
   217
      TYPE (msg, _, _) => error msg;
wenzelm@27277
   218
    val sorts' = Term.add_tfreesT T sorts;
berghofe@5177
   219
  in (Ts @ [T],
wenzelm@18964
   220
      case duplicates (op =) (map fst sorts') of
berghofe@5177
   221
         [] => sorts'
berghofe@5177
   222
       | dups => error ("Inconsistent sort constraints for " ^ commas dups))
berghofe@5177
   223
  end;
berghofe@5177
   224
haftmann@32717
   225
(* case names *)
haftmann@32717
   226
haftmann@32717
   227
local
haftmann@32717
   228
haftmann@32717
   229
fun dt_recs (DtTFree _) = []
haftmann@32717
   230
  | dt_recs (DtType (_, dts)) = maps dt_recs dts
haftmann@32717
   231
  | dt_recs (DtRec i) = [i];
haftmann@32717
   232
haftmann@32717
   233
fun dt_cases (descr: descr) (_, args, constrs) =
haftmann@32717
   234
  let
haftmann@32717
   235
    fun the_bname i = Long_Name.base_name (#1 (the (AList.lookup (op =) descr i)));
haftmann@32717
   236
    val bnames = map the_bname (distinct (op =) (maps dt_recs args));
haftmann@32717
   237
  in map (fn (c, _) => space_implode "_" (Long_Name.base_name c :: bnames)) constrs end;
haftmann@32717
   238
haftmann@32717
   239
fun induct_cases descr =
haftmann@32717
   240
  DatatypeProp.indexify_names (maps (dt_cases descr) (map #2 descr));
haftmann@32717
   241
haftmann@32717
   242
fun exhaust_cases descr i = dt_cases descr (the (AList.lookup (op =) descr i));
haftmann@32717
   243
haftmann@32717
   244
in
haftmann@32717
   245
haftmann@32717
   246
fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
haftmann@32717
   247
haftmann@32717
   248
fun mk_case_names_exhausts descr new =
haftmann@32717
   249
  map (RuleCases.case_names o exhaust_cases descr o #1)
haftmann@32717
   250
    (filter (fn ((_, (name, _, _))) => member (op =) new name) descr);
haftmann@32717
   251
haftmann@32717
   252
end;
haftmann@32717
   253
haftmann@32717
   254
(* translation rules for case *)
berghofe@5177
   255
haftmann@32717
   256
fun make_case ctxt = DatatypeCase.make_case
haftmann@32717
   257
  (info_of_constr (ProofContext.theory_of ctxt)) ctxt;
haftmann@32717
   258
haftmann@32717
   259
fun strip_case ctxt = DatatypeCase.strip_case
haftmann@32717
   260
  (info_of_case (ProofContext.theory_of ctxt));
berghofe@5177
   261
haftmann@32717
   262
fun add_case_tr' case_names thy =
haftmann@32717
   263
  Sign.add_advanced_trfuns ([], [],
haftmann@32717
   264
    map (fn case_name =>
haftmann@32717
   265
      let val case_name' = Sign.const_syntax_name thy case_name
haftmann@32717
   266
      in (case_name', DatatypeCase.case_tr' info_of_case case_name')
haftmann@32717
   267
      end) case_names, []) thy;
berghofe@5177
   268
haftmann@32717
   269
val trfun_setup =
haftmann@32717
   270
  Sign.add_advanced_trfuns ([],
haftmann@32717
   271
    [("_case_syntax", DatatypeCase.case_tr true info_of_constr)],
haftmann@32717
   272
    [], []);
haftmann@32717
   273
haftmann@32717
   274
(* document antiquotation *)
berghofe@5177
   275
haftmann@32717
   276
val _ = ThyOutput.antiquotation "datatype" Args.tyname
haftmann@32717
   277
  (fn {source = src, context = ctxt, ...} => fn dtco =>
haftmann@32717
   278
    let
haftmann@32717
   279
      val thy = ProofContext.theory_of ctxt;
haftmann@32717
   280
      val (vs, cos) = the_spec thy dtco;
haftmann@32717
   281
      val ty = Type (dtco, map TFree vs);
haftmann@32717
   282
      fun pretty_typ_bracket (ty as Type (_, _ :: _)) =
haftmann@32717
   283
            Pretty.enclose "(" ")" [Syntax.pretty_typ ctxt ty]
haftmann@32717
   284
        | pretty_typ_bracket ty =
haftmann@32717
   285
            Syntax.pretty_typ ctxt ty;
haftmann@32717
   286
      fun pretty_constr (co, tys) =
haftmann@32717
   287
        (Pretty.block o Pretty.breaks)
haftmann@32717
   288
          (Syntax.pretty_term ctxt (Const (co, tys ---> ty)) ::
haftmann@32717
   289
            map pretty_typ_bracket tys);
haftmann@32717
   290
      val pretty_datatype =
haftmann@32717
   291
        Pretty.block
haftmann@32717
   292
          (Pretty.command "datatype" :: Pretty.brk 1 ::
haftmann@32717
   293
           Syntax.pretty_typ ctxt ty ::
haftmann@32717
   294
           Pretty.str " =" :: Pretty.brk 1 ::
haftmann@32717
   295
           flat (separate [Pretty.brk 1, Pretty.str "| "]
haftmann@32717
   296
             (map (single o pretty_constr) cos)));
haftmann@32717
   297
    in ThyOutput.output (ThyOutput.maybe_pretty_source (K pretty_datatype) src [()]) end);
berghofe@5177
   298
berghofe@5177
   299
haftmann@32721
   300
(** abstract theory extensions relative to a datatype characterisation **)
haftmann@32721
   301
haftmann@32721
   302
structure DatatypeInterpretation = InterpretationFun
haftmann@32721
   303
  (type T = config * string list val eq: T * T -> bool = eq_snd op =);
haftmann@32721
   304
fun interpretation f = DatatypeInterpretation.interpretation (uncurry f);
haftmann@32721
   305
haftmann@32729
   306
fun make_dt_info alt_names descr sorts induct inducts rec_names rec_rewrites
haftmann@32729
   307
    (index, (((((((((((_, (tname, _, _))), inject), distinct),
haftmann@32729
   308
      exhaust), nchotomy), case_name), case_rewrites), case_cong), weak_case_cong), (split, split_asm))) =
haftmann@32729
   309
  (tname,
haftmann@32729
   310
   {index = index,
haftmann@32729
   311
    alt_names = alt_names,
haftmann@32729
   312
    descr = descr,
haftmann@32729
   313
    sorts = sorts,
haftmann@32729
   314
    inject = inject,
haftmann@32729
   315
    distinct = distinct,
haftmann@32729
   316
    induct = induct,
haftmann@32729
   317
    inducts = inducts,
haftmann@32729
   318
    exhaust = exhaust,
haftmann@32729
   319
    nchotomy = nchotomy,
haftmann@32729
   320
    rec_names = rec_names,
haftmann@32729
   321
    rec_rewrites = rec_rewrites,
haftmann@32729
   322
    case_name = case_name,
haftmann@32729
   323
    case_rewrites = case_rewrites,
haftmann@32729
   324
    case_cong = case_cong,
haftmann@32729
   325
    weak_case_cong = weak_case_cong,
haftmann@32729
   326
    split = split,
haftmann@32729
   327
    split_asm = split_asm});
haftmann@32729
   328
haftmann@32728
   329
fun derive_datatype_props config dt_names alt_names descr sorts
haftmann@32907
   330
    induct inject distinct thy1 =
haftmann@32721
   331
  let
haftmann@32729
   332
    val thy2 = thy1 |> Theory.checkpoint;
haftmann@32728
   333
    val flat_descr = flat descr;
haftmann@32719
   334
    val new_type_names = map Long_Name.base_name (the_default dt_names alt_names);
haftmann@32728
   335
    val _ = message config ("Deriving properties for datatype(s) " ^ commas_quote new_type_names);
haftmann@32729
   336
haftmann@32729
   337
    val (exhaust, thy3) = DatatypeAbsProofs.prove_casedist_thms config new_type_names
haftmann@32729
   338
      descr sorts induct (mk_case_names_exhausts flat_descr dt_names) thy2;
haftmann@32729
   339
    val (nchotomys, thy4) = DatatypeAbsProofs.prove_nchotomys config new_type_names
haftmann@32729
   340
      descr sorts exhaust thy3;
haftmann@32729
   341
    val ((rec_names, rec_rewrites), thy5) = DatatypeAbsProofs.prove_primrec_thms
haftmann@32729
   342
      config new_type_names descr sorts (#inject o the o Symtab.lookup (get_all thy4))
haftmann@32915
   343
      inject (distinct, all_distincts thy2 (get_rec_types flat_descr sorts))
haftmann@32911
   344
      induct thy4;
haftmann@32729
   345
    val ((case_rewrites, case_names), thy6) = DatatypeAbsProofs.prove_case_thms
haftmann@32729
   346
      config new_type_names descr sorts rec_names rec_rewrites thy5;
haftmann@32729
   347
    val (case_congs, thy7) = DatatypeAbsProofs.prove_case_congs new_type_names
haftmann@32729
   348
      descr sorts nchotomys case_rewrites thy6;
haftmann@32729
   349
    val (weak_case_congs, thy8) = DatatypeAbsProofs.prove_weak_case_congs new_type_names
haftmann@32729
   350
      descr sorts thy7;
haftmann@32731
   351
    val (splits, thy9) = DatatypeAbsProofs.prove_split_thms
haftmann@32907
   352
      config new_type_names descr sorts inject distinct exhaust case_rewrites thy8;
berghofe@5177
   353
haftmann@32731
   354
    val inducts = Project_Rule.projections (ProofContext.init thy2) induct;
haftmann@32729
   355
    val dt_infos = map_index (make_dt_info alt_names flat_descr sorts induct inducts rec_names rec_rewrites)
haftmann@32907
   356
      (hd descr ~~ inject ~~ distinct ~~ exhaust ~~ nchotomys ~~
haftmann@32731
   357
        case_names ~~ case_rewrites ~~ case_congs ~~ weak_case_congs ~~ splits);
haftmann@31781
   358
    val dt_names = map fst dt_infos;
haftmann@32731
   359
    val prfx = Binding.qualify true (space_implode "_" new_type_names);
haftmann@32907
   360
    val simps = flat (inject @ distinct @ case_rewrites) @ rec_rewrites;
haftmann@32731
   361
    val named_rules = flat (map_index (fn (index, tname) =>
haftmann@32731
   362
      [((Binding.empty, [nth inducts index]), [Induct.induct_type tname]),
haftmann@32731
   363
       ((Binding.empty, [nth exhaust index]), [Induct.cases_type tname])]) dt_names);
haftmann@32731
   364
    val unnamed_rules = map (fn induct =>
haftmann@32731
   365
      ((Binding.empty, [induct]), [Thm.kind_internal, Induct.induct_type ""]))
haftmann@32731
   366
        (Library.drop (length dt_names, inducts));
haftmann@32720
   367
  in
haftmann@32720
   368
    thy9
haftmann@32731
   369
    |> PureThy.add_thmss ([((prfx (Binding.name "simps"), simps), []),
haftmann@32731
   370
        ((prfx (Binding.name "inducts"), inducts), []),
haftmann@32731
   371
        ((prfx (Binding.name "splits"), maps (fn (x, y) => [x, y]) splits), []),
haftmann@32907
   372
        ((Binding.empty, flat case_rewrites @ flat distinct @ rec_rewrites),
haftmann@32731
   373
          [Simplifier.simp_add]),
haftmann@32731
   374
        ((Binding.empty, rec_rewrites), [Code.add_default_eqn_attribute]),
haftmann@32731
   375
        ((Binding.empty, flat inject), [iff_add]),
haftmann@32907
   376
        ((Binding.empty, map (fn th => th RS notE) (flat distinct)),
haftmann@32731
   377
          [Classical.safe_elim NONE]),
haftmann@32731
   378
        ((Binding.empty, weak_case_congs), [Simplifier.attrib (op addcongs)])]
haftmann@32731
   379
        @ named_rules @ unnamed_rules)
haftmann@32720
   380
    |> snd
haftmann@32730
   381
    |> add_case_tr' case_names
haftmann@32730
   382
    |> register dt_infos
haftmann@32720
   383
    |> DatatypeInterpretation.data (config, dt_names)
haftmann@32720
   384
    |> pair dt_names
haftmann@32720
   385
  end;
berghofe@5177
   386
haftmann@32721
   387
haftmann@32721
   388
(** declare existing type as datatype **)
haftmann@32721
   389
haftmann@32729
   390
fun prove_rep_datatype config dt_names alt_names descr sorts raw_inject half_distinct raw_induct thy1 =
haftmann@32721
   391
  let
haftmann@32721
   392
    val raw_distinct = (map o maps) (fn thm => [thm, thm RS not_sym]) half_distinct;
haftmann@32721
   393
    val new_type_names = map Long_Name.base_name (the_default dt_names alt_names);
haftmann@32721
   394
    val (((inject, distinct), [induct]), thy2) =
haftmann@32721
   395
      thy1
haftmann@32721
   396
      |> store_thmss "inject" new_type_names raw_inject
haftmann@32721
   397
      ||>> store_thmss "distinct" new_type_names raw_distinct
haftmann@32721
   398
      ||> Sign.add_path (space_implode "_" new_type_names)
haftmann@32729
   399
      ||>> PureThy.add_thms [((Binding.name "induct", raw_induct), [mk_case_names_induct descr])]
haftmann@32729
   400
      ||> Sign.restore_naming thy1;
haftmann@32722
   401
  in
haftmann@32722
   402
    thy2
haftmann@32728
   403
    |> derive_datatype_props config dt_names alt_names [descr] sorts
haftmann@32907
   404
         induct inject distinct
haftmann@32722
   405
 end;
haftmann@32721
   406
haftmann@32721
   407
fun gen_rep_datatype prep_term config after_qed alt_names raw_ts thy =
haftmann@27104
   408
  let
haftmann@27104
   409
    fun constr_of_term (Const (c, T)) = (c, T)
haftmann@27104
   410
      | constr_of_term t =
haftmann@27104
   411
          error ("Not a constant: " ^ Syntax.string_of_term_global thy t);
haftmann@27104
   412
    fun no_constr (c, T) = error ("Bad constructor: "
haftmann@27104
   413
      ^ Sign.extern_const thy c ^ "::"
haftmann@27104
   414
      ^ Syntax.string_of_typ_global thy T);
haftmann@27104
   415
    fun type_of_constr (cT as (_, T)) =
haftmann@27104
   416
      let
wenzelm@29270
   417
        val frees = OldTerm.typ_tfrees T;
haftmann@27104
   418
        val (tyco, vs) = ((apsnd o map) (dest_TFree) o dest_Type o snd o strip_type) T
haftmann@27104
   419
          handle TYPE _ => no_constr cT
haftmann@27104
   420
        val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
haftmann@27104
   421
        val _ = if length frees <> length vs then no_constr cT else ();
haftmann@27104
   422
      in (tyco, (vs, cT)) end;
haftmann@27104
   423
haftmann@27104
   424
    val raw_cs = AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
haftmann@27104
   425
    val _ = case map_filter (fn (tyco, _) =>
haftmann@31784
   426
        if Symtab.defined (get_all thy) tyco then SOME tyco else NONE) raw_cs
haftmann@27104
   427
     of [] => ()
haftmann@27104
   428
      | tycos => error ("Type(s) " ^ commas (map quote tycos)
haftmann@27104
   429
          ^ " already represented inductivly");
haftmann@27104
   430
    val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
haftmann@27104
   431
    val ms = case distinct (op =) (map length raw_vss)
haftmann@27104
   432
     of [n] => 0 upto n - 1
haftmann@27104
   433
      | _ => error ("Different types in given constructors");
haftmann@27104
   434
    fun inter_sort m = map (fn xs => nth xs m) raw_vss
haftmann@27104
   435
      |> Library.foldr1 (Sorts.inter_sort (Sign.classes_of thy))
haftmann@27104
   436
    val sorts = map inter_sort ms;
haftmann@27104
   437
    val vs = Name.names Name.context Name.aT sorts;
haftmann@27104
   438
haftmann@27104
   439
    fun norm_constr (raw_vs, (c, T)) = (c, map_atyps
haftmann@27104
   440
      (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
haftmann@27104
   441
haftmann@27104
   442
    val cs = map (apsnd (map norm_constr)) raw_cs;
haftmann@27104
   443
    val dtyps_of_typ = map (dtyp_of_typ (map (rpair (map fst vs) o fst) cs))
haftmann@27104
   444
      o fst o strip_type;
haftmann@32719
   445
    val dt_names = map fst cs;
haftmann@27104
   446
haftmann@27104
   447
    fun mk_spec (i, (tyco, constr)) = (i, (tyco,
haftmann@27104
   448
      map (DtTFree o fst) vs,
haftmann@27104
   449
      (map o apsnd) dtyps_of_typ constr))
haftmann@27104
   450
    val descr = map_index mk_spec cs;
haftmann@27104
   451
    val injs = DatatypeProp.make_injs [descr] vs;
haftmann@27300
   452
    val half_distincts = map snd (DatatypeProp.make_distincts [descr] vs);
haftmann@27104
   453
    val ind = DatatypeProp.make_ind [descr] vs;
haftmann@27300
   454
    val rules = (map o map o map) Logic.close_form [[[ind]], injs, half_distincts];
haftmann@27104
   455
haftmann@27104
   456
    fun after_qed' raw_thms =
haftmann@27104
   457
      let
haftmann@32729
   458
        val [[[raw_induct]], raw_inject, half_distinct] =
haftmann@27104
   459
          unflat rules (map Drule.zero_var_indexes_list raw_thms);
haftmann@27104
   460
            (*FIXME somehow dubious*)
haftmann@27104
   461
      in
haftmann@27104
   462
        ProofContext.theory_result
haftmann@32729
   463
          (prove_rep_datatype config dt_names alt_names descr vs raw_inject half_distinct raw_induct)
haftmann@27104
   464
        #-> after_qed
haftmann@27104
   465
      end;
haftmann@27104
   466
  in
haftmann@27104
   467
    thy
haftmann@27104
   468
    |> ProofContext.init
haftmann@27104
   469
    |> Proof.theorem_i NONE after_qed' ((map o map) (rpair []) (flat rules))
haftmann@27104
   470
  end;
haftmann@27104
   471
haftmann@27104
   472
val rep_datatype = gen_rep_datatype Sign.cert_term;
haftmann@31735
   473
val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global default_config (K I);
wenzelm@6385
   474
berghofe@5177
   475
haftmann@32717
   476
(** definitional introduction of datatypes **)
wenzelm@11958
   477
haftmann@32721
   478
fun gen_add_datatype prep_typ config new_type_names dts thy =
berghofe@5177
   479
  let
wenzelm@20820
   480
    val _ = Theory.requires thy "Datatype" "datatype definitions";
berghofe@5177
   481
berghofe@5177
   482
    (* this theory is used just for parsing *)
berghofe@5177
   483
    val tmp_thy = thy |>
wenzelm@5892
   484
      Theory.copy |>
wenzelm@24712
   485
      Sign.add_types (map (fn (tvs, tname, mx, _) =>
berghofe@5177
   486
        (tname, length tvs, mx)) dts);
berghofe@5177
   487
berghofe@5661
   488
    val (tyvars, _, _, _)::_ = dts;
berghofe@5177
   489
    val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
wenzelm@30345
   490
      let val full_tname = Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname)
wenzelm@18964
   491
      in (case duplicates (op =) tvs of
haftmann@33037
   492
            [] => if gen_eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
berghofe@5661
   493
                  else error ("Mutually recursive datatypes must have same type parameters")
wenzelm@30345
   494
          | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
berghofe@5177
   495
              " : " ^ commas dups))
berghofe@5177
   496
      end) dts);
haftmann@32728
   497
    val dt_names = map fst new_dts;
berghofe@5177
   498
wenzelm@18964
   499
    val _ = (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
berghofe@5177
   500
      [] => () | dups => error ("Duplicate datatypes: " ^ commas dups));
berghofe@5177
   501
berghofe@31361
   502
    fun prep_dt_spec ((tvs, tname, mx, constrs), tname') (dts', constr_syntax, sorts, i) =
berghofe@5177
   503
      let
haftmann@21045
   504
        fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
berghofe@5279
   505
          let
haftmann@20597
   506
            val (cargs', sorts'') = Library.foldl (prep_typ tmp_thy) (([], sorts'), cargs);
wenzelm@29270
   507
            val _ = (case fold (curry OldTerm.add_typ_tfree_names) cargs' [] \\ tvs of
berghofe@5279
   508
                [] => ()
berghofe@5279
   509
              | vs => error ("Extra type variables on rhs: " ^ commas vs))
haftmann@32124
   510
          in (constrs @ [(Sign.full_name_path tmp_thy tname'
wenzelm@30345
   511
                  (Binding.map_name (Syntax.const_name mx') cname),
berghofe@5177
   512
                   map (dtyp_of_typ new_dts) cargs')],
berghofe@5177
   513
              constr_syntax' @ [(cname, mx')], sorts'')
wenzelm@30345
   514
          end handle ERROR msg => cat_error msg
wenzelm@30345
   515
           ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
wenzelm@30345
   516
            " of datatype " ^ quote (Binding.str_of tname));
berghofe@5177
   517
berghofe@5177
   518
        val (constrs', constr_syntax', sorts') =
haftmann@21045
   519
          fold prep_constr constrs ([], [], sorts)
berghofe@5177
   520
wenzelm@8405
   521
      in
wenzelm@18964
   522
        case duplicates (op =) (map fst constrs') of
berghofe@5177
   523
           [] =>
wenzelm@30345
   524
             (dts' @ [(i, (Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname),
berghofe@5177
   525
                map DtTFree tvs, constrs'))],
berghofe@5177
   526
              constr_syntax @ [constr_syntax'], sorts', i + 1)
berghofe@5177
   527
         | dups => error ("Duplicate constructors " ^ commas dups ^
wenzelm@30345
   528
             " in datatype " ^ quote (Binding.str_of tname))
berghofe@5177
   529
      end;
berghofe@5177
   530
berghofe@31361
   531
    val (dts', constr_syntax, sorts', i) =
berghofe@31361
   532
      fold prep_dt_spec (dts ~~ new_type_names) ([], [], [], 0);
haftmann@20597
   533
    val sorts = sorts' @ (map (rpair (Sign.defaultS tmp_thy)) (tyvars \\ map fst sorts'));
haftmann@31784
   534
    val dt_info = get_all thy;
haftmann@20597
   535
    val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
berghofe@14887
   536
    val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
haftmann@31668
   537
      if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
berghofe@14887
   538
      else raise exn;
haftmann@32729
   539
haftmann@32729
   540
    val _ = message config ("Constructing datatype(s) " ^ commas_quote new_type_names);
haftmann@32907
   541
    val ((inject, distinct, induct), thy') = thy |>
haftmann@32729
   542
      DatatypeRepProofs.representation_proofs config dt_info new_type_names descr sorts
haftmann@32729
   543
        types_syntax constr_syntax (mk_case_names_induct (flat descr));
berghofe@5177
   544
  in
haftmann@32729
   545
    derive_datatype_props config dt_names (SOME new_type_names) descr sorts
haftmann@32907
   546
      induct inject distinct thy'
berghofe@5177
   547
  end;
berghofe@5177
   548
haftmann@27104
   549
val add_datatype = gen_add_datatype cert_typ;
haftmann@31735
   550
val datatype_cmd = snd ooo gen_add_datatype read_typ default_config;
berghofe@5177
   551
wenzelm@6360
   552
wenzelm@6360
   553
(** package setup **)
wenzelm@6360
   554
wenzelm@6360
   555
(* setup theory *)
wenzelm@6360
   556
wenzelm@18708
   557
val setup =
haftmann@24626
   558
  trfun_setup #>
wenzelm@24711
   559
  DatatypeInterpretation.init;
wenzelm@6360
   560
wenzelm@6360
   561
(* outer syntax *)
wenzelm@6360
   562
haftmann@31735
   563
local
wenzelm@6360
   564
haftmann@31735
   565
structure P = OuterParse and K = OuterKeyword
wenzelm@6360
   566
haftmann@31735
   567
fun prep_datatype_decls args =
wenzelm@6360
   568
  let
wenzelm@30345
   569
    val names = map
wenzelm@30345
   570
      (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
wenzelm@12876
   571
    val specs = map (fn ((((_, vs), t), mx), cons) =>
wenzelm@12876
   572
      (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
haftmann@31735
   573
  in (names, specs) end;
haftmann@31735
   574
haftmann@31735
   575
val parse_datatype_decl =
haftmann@31735
   576
  (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_infix --
haftmann@31735
   577
    (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
haftmann@31735
   578
haftmann@31735
   579
val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
haftmann@31735
   580
haftmann@31735
   581
in
wenzelm@6360
   582
wenzelm@24867
   583
val _ =
wenzelm@6723
   584
  OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
haftmann@31735
   585
    (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
wenzelm@6360
   586
wenzelm@24867
   587
val _ =
haftmann@27104
   588
  OuterSyntax.command "rep_datatype" "represent existing types inductively" K.thy_goal
haftmann@27104
   589
    (Scan.option (P.$$$ "(" |-- Scan.repeat1 P.name --| P.$$$ ")") -- Scan.repeat1 P.term
haftmann@27104
   590
      >> (fn (alt_names, ts) => Toplevel.print
haftmann@27104
   591
           o Toplevel.theory_to_proof (rep_datatype_cmd alt_names ts)));
wenzelm@6385
   592
wenzelm@30391
   593
end;
wenzelm@30391
   594
wenzelm@6385
   595
end;
wenzelm@6385
   596