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