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