src/HOL/Tools/Datatype/rep_datatype.ML
author wenzelm
Fri Mar 16 18:20:12 2012 +0100 (2012-03-16)
changeset 46961 5c6955f487e5
parent 46909 3c73a121a387
child 49020 f379cf5d71bd
permissions -rw-r--r--
outer syntax command definitions based on formal command_spec derived from theory header declarations;
wenzelm@45890
     1
(*  Title:      HOL/Tools/Datatype/rep_datatype.ML
wenzelm@45890
     2
    Author:     Stefan Berghofer, TU Muenchen
wenzelm@45890
     3
wenzelm@45907
     4
Representation of existing types as datatypes: proofs and definitions
wenzelm@45907
     5
independent of concrete representation of datatypes (i.e. requiring
wenzelm@45907
     6
only abstract properties: injectivity / distinctness of constructors
wenzelm@45907
     7
and induction).
wenzelm@45890
     8
*)
wenzelm@45890
     9
wenzelm@45890
    10
signature REP_DATATYPE =
wenzelm@45890
    11
sig
wenzelm@45890
    12
  val derive_datatype_props : Datatype_Aux.config -> string list -> Datatype_Aux.descr list ->
wenzelm@45890
    13
    thm -> thm list list -> thm list list -> theory -> string list * theory
wenzelm@45890
    14
  val rep_datatype : Datatype_Aux.config -> (string list -> Proof.context -> Proof.context) ->
wenzelm@45890
    15
    term list -> theory -> Proof.state
wenzelm@45890
    16
  val rep_datatype_cmd : Datatype_Aux.config -> (string list -> Proof.context -> Proof.context) ->
wenzelm@45890
    17
    string list -> theory -> Proof.state
wenzelm@45890
    18
end;
wenzelm@45890
    19
wenzelm@45890
    20
structure Rep_Datatype: REP_DATATYPE =
wenzelm@45890
    21
struct
wenzelm@45890
    22
wenzelm@45907
    23
(** derived definitions and proofs **)
wenzelm@45907
    24
wenzelm@45907
    25
(* case distinction theorems *)
wenzelm@45907
    26
wenzelm@45909
    27
fun prove_casedist_thms (config : Datatype_Aux.config)
wenzelm@45909
    28
    new_type_names descr induct case_names_exhausts thy =
wenzelm@45907
    29
  let
wenzelm@45907
    30
    val _ = Datatype_Aux.message config "Proving case distinction theorems ...";
wenzelm@45907
    31
wenzelm@45907
    32
    val descr' = flat descr;
wenzelm@45907
    33
    val recTs = Datatype_Aux.get_rec_types descr';
wenzelm@45907
    34
    val newTs = take (length (hd descr)) recTs;
wenzelm@45907
    35
wenzelm@45907
    36
    val maxidx = Thm.maxidx_of induct;
wenzelm@45907
    37
    val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
wenzelm@45907
    38
wenzelm@45907
    39
    fun prove_casedist_thm (i, (T, t)) =
wenzelm@45907
    40
      let
wenzelm@45907
    41
        val dummyPs = map (fn (Var (_, Type (_, [T', T'']))) =>
wenzelm@45907
    42
          Abs ("z", T', Const (@{const_name True}, T''))) induct_Ps;
wenzelm@45907
    43
        val P =
wenzelm@45907
    44
          Abs ("z", T, HOLogic.imp $ HOLogic.mk_eq (Var (("a", maxidx + 1), T), Bound 0) $
wenzelm@45907
    45
            Var (("P", 0), HOLogic.boolT));
wenzelm@45907
    46
        val insts = take i dummyPs @ (P :: drop (i + 1) dummyPs);
wenzelm@45907
    47
        val cert = cterm_of thy;
wenzelm@45907
    48
        val insts' = map cert induct_Ps ~~ map cert insts;
wenzelm@45907
    49
        val induct' =
wenzelm@45907
    50
          refl RS
wenzelm@45907
    51
            (nth (Datatype_Aux.split_conj_thm (cterm_instantiate insts' induct)) i RSN (2, rev_mp));
wenzelm@45907
    52
      in
wenzelm@45907
    53
        Skip_Proof.prove_global thy []
wenzelm@45907
    54
          (Logic.strip_imp_prems t)
wenzelm@45907
    55
          (Logic.strip_imp_concl t)
wenzelm@45907
    56
          (fn {prems, ...} =>
wenzelm@45907
    57
            EVERY
wenzelm@45907
    58
              [rtac induct' 1,
wenzelm@45907
    59
               REPEAT (rtac TrueI 1),
wenzelm@45907
    60
               REPEAT ((rtac impI 1) THEN (eresolve_tac prems 1)),
wenzelm@45907
    61
               REPEAT (rtac TrueI 1)])
wenzelm@45907
    62
      end;
wenzelm@45907
    63
wenzelm@45907
    64
    val casedist_thms =
wenzelm@45907
    65
      map_index prove_casedist_thm (newTs ~~ Datatype_Prop.make_casedists descr);
wenzelm@45907
    66
  in
wenzelm@45907
    67
    thy
wenzelm@45907
    68
    |> Datatype_Aux.store_thms_atts "exhaust" new_type_names
wenzelm@45907
    69
        (map single case_names_exhausts) casedist_thms
wenzelm@45907
    70
  end;
wenzelm@45907
    71
wenzelm@45907
    72
wenzelm@45907
    73
(* primrec combinators *)
wenzelm@45907
    74
wenzelm@45909
    75
fun prove_primrec_thms (config : Datatype_Aux.config) new_type_names descr
wenzelm@45907
    76
    injects_of constr_inject (dist_rewrites, other_dist_rewrites) induct thy =
wenzelm@45907
    77
  let
wenzelm@45907
    78
    val _ = Datatype_Aux.message config "Constructing primrec combinators ...";
wenzelm@45907
    79
wenzelm@45907
    80
    val big_name = space_implode "_" new_type_names;
wenzelm@45907
    81
    val thy0 = Sign.add_path big_name thy;
wenzelm@45907
    82
wenzelm@45907
    83
    val descr' = flat descr;
wenzelm@45907
    84
    val recTs = Datatype_Aux.get_rec_types descr';
wenzelm@45907
    85
    val used = fold Term.add_tfree_namesT recTs [];
wenzelm@45907
    86
    val newTs = take (length (hd descr)) recTs;
wenzelm@45907
    87
wenzelm@45907
    88
    val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
wenzelm@45907
    89
wenzelm@45907
    90
    val big_rec_name' = big_name ^ "_rec_set";
wenzelm@45907
    91
    val rec_set_names' =
wenzelm@45907
    92
      if length descr' = 1 then [big_rec_name']
wenzelm@45907
    93
      else map (prefix (big_rec_name' ^ "_") o string_of_int) (1 upto length descr');
wenzelm@45907
    94
    val rec_set_names = map (Sign.full_bname thy0) rec_set_names';
wenzelm@45907
    95
wenzelm@45907
    96
    val (rec_result_Ts, reccomb_fn_Ts) = Datatype_Prop.make_primrec_Ts descr used;
wenzelm@45907
    97
wenzelm@45907
    98
    val rec_set_Ts =
wenzelm@45907
    99
      map (fn (T1, T2) => (reccomb_fn_Ts @ [T1, T2]) ---> HOLogic.boolT) (recTs ~~ rec_result_Ts);
wenzelm@45907
   100
wenzelm@45907
   101
    val rec_fns =
wenzelm@45907
   102
      map (uncurry (Datatype_Aux.mk_Free "f")) (reccomb_fn_Ts ~~ (1 upto length reccomb_fn_Ts));
wenzelm@45907
   103
    val rec_sets' =
wenzelm@45907
   104
      map (fn c => list_comb (Free c, rec_fns)) (rec_set_names' ~~ rec_set_Ts);
wenzelm@45907
   105
    val rec_sets =
wenzelm@45907
   106
      map (fn c => list_comb (Const c, rec_fns)) (rec_set_names ~~ rec_set_Ts);
wenzelm@45907
   107
wenzelm@45907
   108
    (* introduction rules for graph of primrec function *)
wenzelm@45907
   109
wenzelm@45907
   110
    fun make_rec_intr T rec_set (cname, cargs) (rec_intr_ts, l) =
wenzelm@45907
   111
      let
wenzelm@45907
   112
        fun mk_prem (dt, U) (j, k, prems, t1s, t2s) =
wenzelm@45907
   113
          let val free1 = Datatype_Aux.mk_Free "x" U j in
wenzelm@45907
   114
            (case (Datatype_Aux.strip_dtyp dt, strip_type U) of
wenzelm@45907
   115
              ((_, Datatype_Aux.DtRec m), (Us, _)) =>
wenzelm@45907
   116
                let
wenzelm@45907
   117
                  val free2 = Datatype_Aux.mk_Free "y" (Us ---> nth rec_result_Ts m) k;
wenzelm@45907
   118
                  val i = length Us;
wenzelm@45907
   119
                in
wenzelm@45907
   120
                  (j + 1, k + 1,
wenzelm@45907
   121
                    HOLogic.mk_Trueprop (HOLogic.list_all
wenzelm@45907
   122
                      (map (pair "x") Us, nth rec_sets' m $
wenzelm@45907
   123
                        Datatype_Aux.app_bnds free1 i $ Datatype_Aux.app_bnds free2 i)) :: prems,
wenzelm@45907
   124
                    free1 :: t1s, free2 :: t2s)
wenzelm@45907
   125
                end
wenzelm@45907
   126
            | _ => (j + 1, k, prems, free1 :: t1s, t2s))
wenzelm@45907
   127
          end;
wenzelm@45907
   128
wenzelm@45907
   129
        val Ts = map (Datatype_Aux.typ_of_dtyp descr') cargs;
wenzelm@45907
   130
        val (_, _, prems, t1s, t2s) = fold_rev mk_prem (cargs ~~ Ts) (1, 1, [], [], []);
wenzelm@45907
   131
wenzelm@45907
   132
      in
wenzelm@45907
   133
        (rec_intr_ts @
wenzelm@45907
   134
          [Logic.list_implies (prems, HOLogic.mk_Trueprop
wenzelm@45907
   135
            (rec_set $ list_comb (Const (cname, Ts ---> T), t1s) $
wenzelm@45907
   136
              list_comb (nth rec_fns l, t1s @ t2s)))], l + 1)
wenzelm@45907
   137
      end;
wenzelm@45907
   138
wenzelm@45907
   139
    val (rec_intr_ts, _) =
wenzelm@45907
   140
      fold (fn ((d, T), set_name) =>
wenzelm@45907
   141
        fold (make_rec_intr T set_name) (#3 (snd d))) (descr' ~~ recTs ~~ rec_sets') ([], 0);
wenzelm@45907
   142
wenzelm@45907
   143
    val ({intrs = rec_intrs, elims = rec_elims, ...}, thy1) =
wenzelm@45907
   144
      thy0
wenzelm@45907
   145
      |> Sign.map_naming Name_Space.conceal
wenzelm@45907
   146
      |> Inductive.add_inductive_global
wenzelm@45907
   147
          {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name',
wenzelm@45907
   148
            coind = false, no_elim = false, no_ind = true, skip_mono = true, fork_mono = false}
wenzelm@45907
   149
          (map (fn (s, T) => ((Binding.name s, T), NoSyn)) (rec_set_names' ~~ rec_set_Ts))
wenzelm@45907
   150
          (map dest_Free rec_fns)
wenzelm@45907
   151
          (map (fn x => (Attrib.empty_binding, x)) rec_intr_ts) []
wenzelm@45907
   152
      ||> Sign.restore_naming thy0
wenzelm@45907
   153
      ||> Theory.checkpoint;
wenzelm@45907
   154
wenzelm@45907
   155
    (* prove uniqueness and termination of primrec combinators *)
wenzelm@45907
   156
wenzelm@45907
   157
    val _ = Datatype_Aux.message config "Proving termination and uniqueness of primrec functions ...";
wenzelm@45907
   158
wenzelm@45907
   159
    fun mk_unique_tac ((((i, (tname, _, constrs)), elim), T), T') (tac, intrs) =
wenzelm@45907
   160
      let
wenzelm@45907
   161
        val distinct_tac =
wenzelm@45907
   162
          if i < length newTs then
wenzelm@45907
   163
            full_simp_tac (HOL_ss addsimps (nth dist_rewrites i)) 1
wenzelm@45907
   164
          else full_simp_tac (HOL_ss addsimps (flat other_dist_rewrites)) 1;
wenzelm@45907
   165
wenzelm@45907
   166
        val inject =
wenzelm@45907
   167
          map (fn r => r RS iffD1)
wenzelm@45907
   168
            (if i < length newTs then nth constr_inject i else injects_of tname);
wenzelm@45907
   169
wenzelm@45907
   170
        fun mk_unique_constr_tac n (cname, cargs) (tac, intr :: intrs, j) =
wenzelm@45907
   171
          let
wenzelm@45907
   172
            val k = length (filter Datatype_Aux.is_rec_type cargs);
wenzelm@45907
   173
          in
wenzelm@45907
   174
            (EVERY
wenzelm@45907
   175
              [DETERM tac,
wenzelm@45907
   176
                REPEAT (etac ex1E 1), rtac ex1I 1,
wenzelm@45907
   177
                DEPTH_SOLVE_1 (ares_tac [intr] 1),
wenzelm@45907
   178
                REPEAT_DETERM_N k (etac thin_rl 1 THEN rotate_tac 1 1),
wenzelm@45907
   179
                etac elim 1,
wenzelm@45907
   180
                REPEAT_DETERM_N j distinct_tac,
wenzelm@45907
   181
                TRY (dresolve_tac inject 1),
wenzelm@45907
   182
                REPEAT (etac conjE 1), hyp_subst_tac 1,
wenzelm@45907
   183
                REPEAT (EVERY [etac allE 1, dtac mp 1, atac 1]),
wenzelm@45907
   184
                TRY (hyp_subst_tac 1),
wenzelm@45907
   185
                rtac refl 1,
wenzelm@45907
   186
                REPEAT_DETERM_N (n - j - 1) distinct_tac],
wenzelm@45907
   187
              intrs, j + 1)
wenzelm@45907
   188
          end;
wenzelm@45907
   189
wenzelm@45907
   190
        val (tac', intrs', _) =
wenzelm@45907
   191
          fold (mk_unique_constr_tac (length constrs)) constrs (tac, intrs, 0);
wenzelm@45907
   192
      in (tac', intrs') end;
wenzelm@45907
   193
wenzelm@45907
   194
    val rec_unique_thms =
wenzelm@45907
   195
      let
wenzelm@45907
   196
        val rec_unique_ts =
wenzelm@45907
   197
          map (fn (((set_t, T1), T2), i) =>
wenzelm@45907
   198
            Const (@{const_name Ex1}, (T2 --> HOLogic.boolT) --> HOLogic.boolT) $
wenzelm@45907
   199
              absfree ("y", T2) (set_t $ Datatype_Aux.mk_Free "x" T1 i $ Free ("y", T2)))
wenzelm@45907
   200
                (rec_sets ~~ recTs ~~ rec_result_Ts ~~ (1 upto length recTs));
wenzelm@45907
   201
        val cert = cterm_of thy1;
wenzelm@45907
   202
        val insts =
wenzelm@45907
   203
          map (fn ((i, T), t) => absfree ("x" ^ string_of_int i, T) t)
wenzelm@45907
   204
            ((1 upto length recTs) ~~ recTs ~~ rec_unique_ts);
wenzelm@45907
   205
        val induct' = cterm_instantiate (map cert induct_Ps ~~ map cert insts) induct;
wenzelm@45907
   206
        val (tac, _) =
wenzelm@45907
   207
          fold mk_unique_tac (descr' ~~ rec_elims ~~ recTs ~~ rec_result_Ts)
wenzelm@45907
   208
            (((rtac induct' THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1 THEN
wenzelm@45907
   209
                rewrite_goals_tac [mk_meta_eq @{thm choice_eq}], rec_intrs));
wenzelm@45907
   210
      in
wenzelm@45907
   211
        Datatype_Aux.split_conj_thm (Skip_Proof.prove_global thy1 [] []
wenzelm@45907
   212
          (HOLogic.mk_Trueprop (Datatype_Aux.mk_conj rec_unique_ts)) (K tac))
wenzelm@45907
   213
      end;
wenzelm@45907
   214
wenzelm@45907
   215
    val rec_total_thms = map (fn r => r RS @{thm theI'}) rec_unique_thms;
wenzelm@45907
   216
wenzelm@45907
   217
    (* define primrec combinators *)
wenzelm@45907
   218
wenzelm@45907
   219
    val big_reccomb_name = space_implode "_" new_type_names ^ "_rec";
wenzelm@45907
   220
    val reccomb_names =
wenzelm@45907
   221
      map (Sign.full_bname thy1)
wenzelm@45907
   222
        (if length descr' = 1 then [big_reccomb_name]
wenzelm@45907
   223
         else map (prefix (big_reccomb_name ^ "_") o string_of_int) (1 upto length descr'));
wenzelm@45907
   224
    val reccombs =
wenzelm@45907
   225
      map (fn ((name, T), T') => Const (name, reccomb_fn_Ts @ [T] ---> T'))
wenzelm@45907
   226
        (reccomb_names ~~ recTs ~~ rec_result_Ts);
wenzelm@45907
   227
wenzelm@45907
   228
    val (reccomb_defs, thy2) =
wenzelm@45907
   229
      thy1
wenzelm@45907
   230
      |> Sign.add_consts_i (map (fn ((name, T), T') =>
wenzelm@45907
   231
            (Binding.name (Long_Name.base_name name), reccomb_fn_Ts @ [T] ---> T', NoSyn))
wenzelm@45907
   232
            (reccomb_names ~~ recTs ~~ rec_result_Ts))
wenzelm@45907
   233
      |> (Global_Theory.add_defs false o map Thm.no_attributes)
wenzelm@45907
   234
          (map
wenzelm@45907
   235
            (fn ((((name, comb), set), T), T') =>
wenzelm@46909
   236
              (Binding.name (Thm.def_name (Long_Name.base_name name)),
wenzelm@45907
   237
                Logic.mk_equals (comb, fold_rev lambda rec_fns (absfree ("x", T)
wenzelm@45907
   238
                 (Const (@{const_name The}, (T' --> HOLogic.boolT) --> T') $ absfree ("y", T')
wenzelm@45907
   239
                   (set $ Free ("x", T) $ Free ("y", T')))))))
wenzelm@45907
   240
            (reccomb_names ~~ reccombs ~~ rec_sets ~~ recTs ~~ rec_result_Ts))
wenzelm@45907
   241
      ||> Sign.parent_path
wenzelm@45907
   242
      ||> Theory.checkpoint;
wenzelm@45907
   243
wenzelm@45907
   244
wenzelm@45907
   245
    (* prove characteristic equations for primrec combinators *)
wenzelm@45907
   246
wenzelm@45907
   247
    val _ = Datatype_Aux.message config "Proving characteristic theorems for primrec combinators ...";
wenzelm@45907
   248
wenzelm@45907
   249
    val rec_thms =
wenzelm@45907
   250
      map (fn t =>
wenzelm@45907
   251
        Skip_Proof.prove_global thy2 [] [] t
wenzelm@45907
   252
          (fn _ => EVERY
wenzelm@45907
   253
            [rewrite_goals_tac reccomb_defs,
wenzelm@45907
   254
             rtac @{thm the1_equality} 1,
wenzelm@45907
   255
             resolve_tac rec_unique_thms 1,
wenzelm@45907
   256
             resolve_tac rec_intrs 1,
wenzelm@45907
   257
             REPEAT (rtac allI 1 ORELSE resolve_tac rec_total_thms 1)]))
wenzelm@45907
   258
       (Datatype_Prop.make_primrecs reccomb_names descr thy2);
wenzelm@45907
   259
  in
wenzelm@45907
   260
    thy2
wenzelm@45907
   261
    |> Sign.add_path (space_implode "_" new_type_names)
wenzelm@45907
   262
    |> Global_Theory.note_thmss ""
wenzelm@45907
   263
      [((Binding.name "recs", [Nitpick_Simps.add]), [(rec_thms, [])])]
wenzelm@45907
   264
    ||> Sign.parent_path
wenzelm@45907
   265
    ||> Theory.checkpoint
wenzelm@45907
   266
    |-> (fn thms => pair (reccomb_names, maps #2 thms))
wenzelm@45907
   267
  end;
wenzelm@45907
   268
wenzelm@45907
   269
wenzelm@45907
   270
(* case combinators *)
wenzelm@45907
   271
wenzelm@45909
   272
fun prove_case_thms (config : Datatype_Aux.config)
wenzelm@45909
   273
    new_type_names descr reccomb_names primrec_thms thy =
wenzelm@45907
   274
  let
wenzelm@45907
   275
    val _ = Datatype_Aux.message config "Proving characteristic theorems for case combinators ...";
wenzelm@45907
   276
wenzelm@45907
   277
    val thy1 = Sign.add_path (space_implode "_" new_type_names) thy;
wenzelm@45907
   278
wenzelm@45907
   279
    val descr' = flat descr;
wenzelm@45907
   280
    val recTs = Datatype_Aux.get_rec_types descr';
wenzelm@45907
   281
    val used = fold Term.add_tfree_namesT recTs [];
wenzelm@45907
   282
    val newTs = take (length (hd descr)) recTs;
wenzelm@45907
   283
    val T' = TFree (singleton (Name.variant_list used) "'t", HOLogic.typeS);
wenzelm@45907
   284
wenzelm@45907
   285
    fun mk_dummyT dt = binder_types (Datatype_Aux.typ_of_dtyp descr' dt) ---> T';
wenzelm@45907
   286
wenzelm@45907
   287
    val case_dummy_fns =
wenzelm@45907
   288
      map (fn (_, (_, _, constrs)) => map (fn (_, cargs) =>
wenzelm@45907
   289
        let
wenzelm@45907
   290
          val Ts = map (Datatype_Aux.typ_of_dtyp descr') cargs;
wenzelm@45907
   291
          val Ts' = map mk_dummyT (filter Datatype_Aux.is_rec_type cargs)
wenzelm@45907
   292
        in Const (@{const_name undefined}, Ts @ Ts' ---> T') end) constrs) descr';
wenzelm@45907
   293
wenzelm@45907
   294
    val case_names = map (fn s => Sign.full_bname thy1 (s ^ "_case")) new_type_names;
wenzelm@45907
   295
wenzelm@45907
   296
    (* define case combinators via primrec combinators *)
wenzelm@45907
   297
wenzelm@45907
   298
    val (case_defs, thy2) =
wenzelm@45907
   299
      fold (fn ((((i, (_, _, constrs)), T), name), recname) => fn (defs, thy) =>
wenzelm@45907
   300
          let
wenzelm@45907
   301
            val (fns1, fns2) = split_list (map (fn ((_, cargs), j) =>
wenzelm@45907
   302
              let
wenzelm@45907
   303
                val Ts = map (Datatype_Aux.typ_of_dtyp descr') cargs;
wenzelm@45907
   304
                val Ts' = Ts @ map mk_dummyT (filter Datatype_Aux.is_rec_type cargs);
wenzelm@45907
   305
                val frees' = map2 (Datatype_Aux.mk_Free "x") Ts' (1 upto length Ts');
wenzelm@45907
   306
                val frees = take (length cargs) frees';
wenzelm@45907
   307
                val free = Datatype_Aux.mk_Free "f" (Ts ---> T') j;
wenzelm@45907
   308
              in
wenzelm@45907
   309
                (free, fold_rev (absfree o dest_Free) frees' (list_comb (free, frees)))
wenzelm@45907
   310
              end) (constrs ~~ (1 upto length constrs)));
wenzelm@45907
   311
wenzelm@45907
   312
            val caseT = map (snd o dest_Free) fns1 @ [T] ---> T';
wenzelm@45907
   313
            val fns = flat (take i case_dummy_fns) @ fns2 @ flat (drop (i + 1) case_dummy_fns);
wenzelm@45907
   314
            val reccomb = Const (recname, (map fastype_of fns) @ [T] ---> T');
wenzelm@45907
   315
            val decl = ((Binding.name (Long_Name.base_name name), caseT), NoSyn);
wenzelm@45907
   316
            val def =
wenzelm@46909
   317
              (Binding.name (Thm.def_name (Long_Name.base_name name)),
wenzelm@45907
   318
                Logic.mk_equals (Const (name, caseT),
wenzelm@45907
   319
                  fold_rev lambda fns1
wenzelm@45907
   320
                    (list_comb (reccomb,
wenzelm@45907
   321
                      flat (take i case_dummy_fns) @ fns2 @ flat (drop (i + 1) case_dummy_fns)))));
wenzelm@45907
   322
            val ([def_thm], thy') =
wenzelm@45907
   323
              thy
wenzelm@45907
   324
              |> Sign.declare_const_global decl |> snd
wenzelm@45907
   325
              |> (Global_Theory.add_defs false o map Thm.no_attributes) [def];
wenzelm@45907
   326
wenzelm@45907
   327
          in (defs @ [def_thm], thy') end)
wenzelm@45907
   328
        (hd descr ~~ newTs ~~ case_names ~~ take (length newTs) reccomb_names) ([], thy1)
wenzelm@45907
   329
      ||> Theory.checkpoint;
wenzelm@45907
   330
wenzelm@45907
   331
    val case_thms =
wenzelm@45907
   332
      (map o map) (fn t =>
wenzelm@45907
   333
          Skip_Proof.prove_global thy2 [] [] t
wenzelm@45907
   334
            (fn _ =>
wenzelm@45907
   335
              EVERY [rewrite_goals_tac (case_defs @ map mk_meta_eq primrec_thms), rtac refl 1]))
wenzelm@45907
   336
        (Datatype_Prop.make_cases case_names descr thy2);
wenzelm@45907
   337
  in
wenzelm@45907
   338
    thy2
wenzelm@45907
   339
    |> Context.theory_map ((fold o fold) Nitpick_Simps.add_thm case_thms)
wenzelm@45907
   340
    |> Sign.parent_path
wenzelm@45907
   341
    |> Datatype_Aux.store_thmss "cases" new_type_names case_thms
wenzelm@45907
   342
    |-> (fn thmss => pair (thmss, case_names))
wenzelm@45907
   343
  end;
wenzelm@45907
   344
wenzelm@45907
   345
wenzelm@45907
   346
(* case splitting *)
wenzelm@45907
   347
wenzelm@45909
   348
fun prove_split_thms (config : Datatype_Aux.config)
wenzelm@45907
   349
    new_type_names case_names descr constr_inject dist_rewrites casedist_thms case_thms thy =
wenzelm@45907
   350
  let
wenzelm@45907
   351
    val _ = Datatype_Aux.message config "Proving equations for case splitting ...";
wenzelm@45907
   352
wenzelm@45907
   353
    val descr' = flat descr;
wenzelm@45907
   354
    val recTs = Datatype_Aux.get_rec_types descr';
wenzelm@45907
   355
    val newTs = take (length (hd descr)) recTs;
wenzelm@45907
   356
wenzelm@45907
   357
    fun prove_split_thms ((((((t1, t2), inject), dist_rewrites'), exhaustion), case_thms'), T) =
wenzelm@45907
   358
      let
wenzelm@45907
   359
        val cert = cterm_of thy;
wenzelm@45907
   360
        val _ $ (_ $ lhs $ _) = hd (Logic.strip_assums_hyp (hd (prems_of exhaustion)));
wenzelm@45907
   361
        val exhaustion' = cterm_instantiate [(cert lhs, cert (Free ("x", T)))] exhaustion;
wenzelm@45907
   362
        val tac =
wenzelm@45907
   363
          EVERY [rtac exhaustion' 1,
wenzelm@45907
   364
            ALLGOALS (asm_simp_tac (HOL_ss addsimps (dist_rewrites' @ inject @ case_thms')))];
wenzelm@45907
   365
      in
wenzelm@45907
   366
        (Skip_Proof.prove_global thy [] [] t1 (K tac),
wenzelm@45907
   367
         Skip_Proof.prove_global thy [] [] t2 (K tac))
wenzelm@45907
   368
      end;
wenzelm@45907
   369
wenzelm@45907
   370
    val split_thm_pairs =
wenzelm@45907
   371
      map prove_split_thms
wenzelm@45907
   372
        (Datatype_Prop.make_splits case_names descr thy ~~ constr_inject ~~
wenzelm@45907
   373
          dist_rewrites ~~ casedist_thms ~~ case_thms ~~ newTs);
wenzelm@45907
   374
wenzelm@45907
   375
    val (split_thms, split_asm_thms) = split_list split_thm_pairs
wenzelm@45907
   376
wenzelm@45907
   377
  in
wenzelm@45907
   378
    thy
wenzelm@45907
   379
    |> Datatype_Aux.store_thms "split" new_type_names split_thms
wenzelm@45907
   380
    ||>> Datatype_Aux.store_thms "split_asm" new_type_names split_asm_thms
wenzelm@45907
   381
    |-> (fn (thms1, thms2) => pair (thms1 ~~ thms2))
wenzelm@45907
   382
  end;
wenzelm@45907
   383
wenzelm@45907
   384
fun prove_weak_case_congs new_type_names case_names descr thy =
wenzelm@45907
   385
  let
wenzelm@45907
   386
    fun prove_weak_case_cong t =
wenzelm@45907
   387
     Skip_Proof.prove_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
wenzelm@45907
   388
       (fn {prems, ...} => EVERY [rtac (hd prems RS arg_cong) 1]);
wenzelm@45907
   389
wenzelm@45907
   390
    val weak_case_congs =
wenzelm@45907
   391
      map prove_weak_case_cong (Datatype_Prop.make_weak_case_congs case_names descr thy);
wenzelm@45907
   392
wenzelm@45907
   393
  in thy |> Datatype_Aux.store_thms "weak_case_cong" new_type_names weak_case_congs end;
wenzelm@45907
   394
wenzelm@45907
   395
wenzelm@45907
   396
(* additional theorems for TFL *)
wenzelm@45907
   397
wenzelm@45909
   398
fun prove_nchotomys (config : Datatype_Aux.config) new_type_names descr casedist_thms thy =
wenzelm@45907
   399
  let
wenzelm@45907
   400
    val _ = Datatype_Aux.message config "Proving additional theorems for TFL ...";
wenzelm@45907
   401
wenzelm@45907
   402
    fun prove_nchotomy (t, exhaustion) =
wenzelm@45907
   403
      let
wenzelm@45907
   404
        (* For goal i, select the correct disjunct to attack, then prove it *)
wenzelm@45907
   405
        fun tac i 0 = EVERY [TRY (rtac disjI1 i), hyp_subst_tac i, REPEAT (rtac exI i), rtac refl i]
wenzelm@45907
   406
          | tac i n = rtac disjI2 i THEN tac i (n - 1);
wenzelm@45907
   407
      in
wenzelm@45907
   408
        Skip_Proof.prove_global thy [] [] t
wenzelm@45907
   409
          (fn _ =>
wenzelm@45907
   410
            EVERY [rtac allI 1,
wenzelm@45907
   411
             Datatype_Aux.exh_tac (K exhaustion) 1,
wenzelm@45907
   412
             ALLGOALS (fn i => tac i (i - 1))])
wenzelm@45907
   413
      end;
wenzelm@45907
   414
wenzelm@45907
   415
    val nchotomys =
wenzelm@45907
   416
      map prove_nchotomy (Datatype_Prop.make_nchotomys descr ~~ casedist_thms);
wenzelm@45907
   417
wenzelm@45907
   418
  in thy |> Datatype_Aux.store_thms "nchotomy" new_type_names nchotomys end;
wenzelm@45907
   419
wenzelm@45907
   420
fun prove_case_congs new_type_names case_names descr nchotomys case_thms thy =
wenzelm@45907
   421
  let
wenzelm@45907
   422
    fun prove_case_cong ((t, nchotomy), case_rewrites) =
wenzelm@45907
   423
      let
wenzelm@45907
   424
        val Const ("==>", _) $ tm $ _ = t;
wenzelm@45907
   425
        val Const (@{const_name Trueprop}, _) $ (Const (@{const_name HOL.eq}, _) $ _ $ Ma) = tm;
wenzelm@45907
   426
        val cert = cterm_of thy;
wenzelm@45907
   427
        val nchotomy' = nchotomy RS spec;
wenzelm@45907
   428
        val [v] = Term.add_vars (concl_of nchotomy') [];
wenzelm@45907
   429
        val nchotomy'' = cterm_instantiate [(cert (Var v), cert Ma)] nchotomy';
wenzelm@45907
   430
      in
wenzelm@45907
   431
        Skip_Proof.prove_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
wenzelm@45907
   432
          (fn {prems, ...} =>
wenzelm@45907
   433
            let val simplify = asm_simp_tac (HOL_ss addsimps (prems @ case_rewrites)) in
wenzelm@45907
   434
              EVERY [
wenzelm@45907
   435
                simp_tac (HOL_ss addsimps [hd prems]) 1,
wenzelm@46708
   436
                cut_tac nchotomy'' 1,
wenzelm@45907
   437
                REPEAT (etac disjE 1 THEN REPEAT (etac exE 1) THEN simplify 1),
wenzelm@45907
   438
                REPEAT (etac exE 1) THEN simplify 1 (* Get last disjunct *)]
wenzelm@45907
   439
            end)
wenzelm@45907
   440
      end;
wenzelm@45907
   441
wenzelm@45907
   442
    val case_congs =
wenzelm@45907
   443
      map prove_case_cong
wenzelm@45907
   444
        (Datatype_Prop.make_case_congs case_names descr thy ~~ nchotomys ~~ case_thms);
wenzelm@45907
   445
wenzelm@45907
   446
  in thy |> Datatype_Aux.store_thms "case_cong" new_type_names case_congs end;
wenzelm@45907
   447
wenzelm@45907
   448
wenzelm@45907
   449
wenzelm@45907
   450
(** derive datatype props **)
wenzelm@45907
   451
wenzelm@45907
   452
local
wenzelm@45907
   453
wenzelm@45890
   454
fun make_dt_info descr induct inducts rec_names rec_rewrites
wenzelm@45890
   455
    (index, (((((((((((_, (tname, _, _))), inject), distinct),
wenzelm@45890
   456
      exhaust), nchotomy), case_name), case_rewrites), case_cong), weak_case_cong),
wenzelm@45890
   457
        (split, split_asm))) =
wenzelm@45890
   458
  (tname,
wenzelm@45890
   459
   {index = index,
wenzelm@45890
   460
    descr = descr,
wenzelm@45890
   461
    inject = inject,
wenzelm@45890
   462
    distinct = distinct,
wenzelm@45890
   463
    induct = induct,
wenzelm@45890
   464
    inducts = inducts,
wenzelm@45890
   465
    exhaust = exhaust,
wenzelm@45890
   466
    nchotomy = nchotomy,
wenzelm@45890
   467
    rec_names = rec_names,
wenzelm@45890
   468
    rec_rewrites = rec_rewrites,
wenzelm@45890
   469
    case_name = case_name,
wenzelm@45890
   470
    case_rewrites = case_rewrites,
wenzelm@45890
   471
    case_cong = case_cong,
wenzelm@45890
   472
    weak_case_cong = weak_case_cong,
wenzelm@45890
   473
    split = split,
wenzelm@45890
   474
    split_asm = split_asm});
wenzelm@45890
   475
wenzelm@45907
   476
in
wenzelm@45907
   477
wenzelm@45890
   478
fun derive_datatype_props config dt_names descr induct inject distinct thy1 =
wenzelm@45890
   479
  let
wenzelm@45890
   480
    val thy2 = thy1 |> Theory.checkpoint;
wenzelm@45890
   481
    val flat_descr = flat descr;
wenzelm@45890
   482
    val new_type_names = map Long_Name.base_name dt_names;
wenzelm@45890
   483
    val _ =
wenzelm@45890
   484
      Datatype_Aux.message config
wenzelm@45890
   485
        ("Deriving properties for datatype(s) " ^ commas_quote new_type_names);
wenzelm@45890
   486
wenzelm@45890
   487
    val (exhaust, thy3) = thy2
wenzelm@45907
   488
      |> prove_casedist_thms config new_type_names descr induct
wenzelm@45907
   489
        (Datatype_Data.mk_case_names_exhausts flat_descr dt_names);
wenzelm@45890
   490
    val (nchotomys, thy4) = thy3
wenzelm@45907
   491
      |> prove_nchotomys config new_type_names descr exhaust;
wenzelm@45890
   492
    val ((rec_names, rec_rewrites), thy5) = thy4
wenzelm@45907
   493
      |> prove_primrec_thms config new_type_names descr
wenzelm@45907
   494
        (#inject o the o Symtab.lookup (Datatype_Data.get_all thy4)) inject
wenzelm@45907
   495
        (distinct, Datatype_Data.all_distincts thy2 (Datatype_Aux.get_rec_types flat_descr)) induct;
wenzelm@45890
   496
    val ((case_rewrites, case_names), thy6) = thy5
wenzelm@45907
   497
      |> prove_case_thms config new_type_names descr rec_names rec_rewrites;
wenzelm@45890
   498
    val (case_congs, thy7) = thy6
wenzelm@45907
   499
      |> prove_case_congs new_type_names case_names descr nchotomys case_rewrites;
wenzelm@45890
   500
    val (weak_case_congs, thy8) = thy7
wenzelm@45907
   501
      |> prove_weak_case_congs new_type_names case_names descr;
wenzelm@45890
   502
    val (splits, thy9) = thy8
wenzelm@45907
   503
      |> prove_split_thms config new_type_names case_names descr
wenzelm@45907
   504
        inject distinct exhaust case_rewrites;
wenzelm@45890
   505
wenzelm@45890
   506
    val inducts = Project_Rule.projections (Proof_Context.init_global thy2) induct;
wenzelm@45890
   507
    val dt_infos =
wenzelm@45890
   508
      map_index
wenzelm@45890
   509
        (make_dt_info flat_descr induct inducts rec_names rec_rewrites)
wenzelm@45890
   510
        (hd descr ~~ inject ~~ distinct ~~ exhaust ~~ nchotomys ~~
wenzelm@45890
   511
          case_names ~~ case_rewrites ~~ case_congs ~~ weak_case_congs ~~ splits);
wenzelm@45890
   512
    val dt_names = map fst dt_infos;
wenzelm@45890
   513
    val prfx = Binding.qualify true (space_implode "_" new_type_names);
wenzelm@45890
   514
    val simps = flat (inject @ distinct @ case_rewrites) @ rec_rewrites;
wenzelm@45901
   515
    val named_rules = flat (map_index (fn (i, tname) =>
wenzelm@45901
   516
      [((Binding.empty, [Induct.induct_type tname]), [([nth inducts i], [])]),
wenzelm@45901
   517
       ((Binding.empty, [Induct.cases_type tname]), [([nth exhaust i], [])])]) dt_names);
wenzelm@45890
   518
    val unnamed_rules = map (fn induct =>
wenzelm@45901
   519
      ((Binding.empty, [Rule_Cases.inner_rule, Induct.induct_type ""]), [([induct], [])]))
wenzelm@45890
   520
        (drop (length dt_names) inducts);
wenzelm@45890
   521
  in
wenzelm@45890
   522
    thy9
wenzelm@45901
   523
    |> Global_Theory.note_thmss ""
wenzelm@45901
   524
      ([((prfx (Binding.name "simps"), []), [(simps, [])]),
wenzelm@45901
   525
        ((prfx (Binding.name "inducts"), []), [(inducts, [])]),
wenzelm@45901
   526
        ((prfx (Binding.name "splits"), []), [(maps (fn (x, y) => [x, y]) splits, [])]),
wenzelm@45901
   527
        ((Binding.empty, [Simplifier.simp_add]),
wenzelm@45901
   528
          [(flat case_rewrites @ flat distinct @ rec_rewrites, [])]),
wenzelm@45901
   529
        ((Binding.empty, [Code.add_default_eqn_attribute]), [(rec_rewrites, [])]),
wenzelm@45901
   530
        ((Binding.empty, [iff_add]), [(flat inject, [])]),
wenzelm@45901
   531
        ((Binding.empty, [Classical.safe_elim NONE]),
wenzelm@45901
   532
          [(map (fn th => th RS notE) (flat distinct), [])]),
wenzelm@45901
   533
        ((Binding.empty, [Simplifier.cong_add]), [(weak_case_congs, [])]),
wenzelm@45901
   534
        ((Binding.empty, [Induct.induct_simp_add]), [(flat (distinct @ inject), [])])] @
wenzelm@45890
   535
          named_rules @ unnamed_rules)
wenzelm@45890
   536
    |> snd
wenzelm@45890
   537
    |> Datatype_Data.register dt_infos
wenzelm@45890
   538
    |> Datatype_Data.interpretation_data (config, dt_names)
wenzelm@45891
   539
    |> Datatype_Case.add_case_tr' case_names
wenzelm@45890
   540
    |> pair dt_names
wenzelm@45890
   541
  end;
wenzelm@45890
   542
wenzelm@45907
   543
end;
wenzelm@45907
   544
wenzelm@45890
   545
wenzelm@45890
   546
wenzelm@45890
   547
(** declare existing type as datatype **)
wenzelm@45890
   548
wenzelm@45890
   549
local
wenzelm@45890
   550
wenzelm@45890
   551
fun prove_rep_datatype config dt_names descr raw_inject half_distinct raw_induct thy1 =
wenzelm@45890
   552
  let
wenzelm@45890
   553
    val raw_distinct = (map o maps) (fn thm => [thm, thm RS not_sym]) half_distinct;
wenzelm@45890
   554
    val new_type_names = map Long_Name.base_name dt_names;
wenzelm@45890
   555
    val prfx = Binding.qualify true (space_implode "_" new_type_names);
wenzelm@45901
   556
    val (((inject, distinct), [(_, [induct])]), thy2) =
wenzelm@45890
   557
      thy1
wenzelm@45890
   558
      |> Datatype_Aux.store_thmss "inject" new_type_names raw_inject
wenzelm@45890
   559
      ||>> Datatype_Aux.store_thmss "distinct" new_type_names raw_distinct
wenzelm@45901
   560
      ||>> Global_Theory.note_thmss ""
wenzelm@45901
   561
        [((prfx (Binding.name "induct"), [Datatype_Data.mk_case_names_induct descr]),
wenzelm@45901
   562
          [([raw_induct], [])])];
wenzelm@45890
   563
  in
wenzelm@45890
   564
    thy2
wenzelm@45890
   565
    |> derive_datatype_props config dt_names [descr] induct inject distinct
wenzelm@45890
   566
 end;
wenzelm@45890
   567
wenzelm@45890
   568
fun gen_rep_datatype prep_term config after_qed raw_ts thy =
wenzelm@45890
   569
  let
wenzelm@45890
   570
    val ctxt = Proof_Context.init_global thy;
wenzelm@45890
   571
wenzelm@45890
   572
    fun constr_of_term (Const (c, T)) = (c, T)
wenzelm@45890
   573
      | constr_of_term t = error ("Not a constant: " ^ Syntax.string_of_term ctxt t);
wenzelm@45890
   574
    fun no_constr (c, T) =
wenzelm@45890
   575
      error ("Bad constructor: " ^ Proof_Context.extern_const ctxt c ^ "::" ^
wenzelm@45890
   576
        Syntax.string_of_typ ctxt T);
wenzelm@45890
   577
    fun type_of_constr (cT as (_, T)) =
wenzelm@45890
   578
      let
wenzelm@45890
   579
        val frees = Term.add_tfreesT T [];
wenzelm@45890
   580
        val (tyco, vs) = (apsnd o map) dest_TFree (dest_Type (body_type T))
wenzelm@45890
   581
          handle TYPE _ => no_constr cT
wenzelm@45890
   582
        val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
wenzelm@45890
   583
        val _ = if length frees <> length vs then no_constr cT else ();
wenzelm@45890
   584
      in (tyco, (vs, cT)) end;
wenzelm@45890
   585
wenzelm@45890
   586
    val raw_cs =
wenzelm@45890
   587
      AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
wenzelm@45890
   588
    val _ =
wenzelm@45890
   589
      (case map_filter (fn (tyco, _) =>
wenzelm@45890
   590
          if Symtab.defined (Datatype_Data.get_all thy) tyco then SOME tyco else NONE) raw_cs of
wenzelm@45890
   591
        [] => ()
wenzelm@45890
   592
      | tycos => error ("Type(s) " ^ commas_quote tycos ^ " already represented inductivly"));
wenzelm@45890
   593
    val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
wenzelm@45890
   594
    val ms =
wenzelm@45890
   595
      (case distinct (op =) (map length raw_vss) of
wenzelm@45890
   596
         [n] => 0 upto n - 1
wenzelm@45890
   597
      | _ => error "Different types in given constructors");
wenzelm@45890
   598
    fun inter_sort m =
wenzelm@45890
   599
      map (fn xs => nth xs m) raw_vss
wenzelm@45890
   600
      |> foldr1 (Sorts.inter_sort (Sign.classes_of thy));
wenzelm@45890
   601
    val sorts = map inter_sort ms;
wenzelm@45890
   602
    val vs = Name.invent_names Name.context Name.aT sorts;
wenzelm@45890
   603
wenzelm@45890
   604
    fun norm_constr (raw_vs, (c, T)) =
wenzelm@45890
   605
      (c, map_atyps
wenzelm@45890
   606
        (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
wenzelm@45890
   607
wenzelm@45890
   608
    val cs = map (apsnd (map norm_constr)) raw_cs;
wenzelm@45890
   609
    val dtyps_of_typ = map (Datatype_Aux.dtyp_of_typ (map (rpair vs o fst) cs)) o binder_types;
wenzelm@45890
   610
    val dt_names = map fst cs;
wenzelm@45890
   611
wenzelm@45890
   612
    fun mk_spec (i, (tyco, constr)) =
wenzelm@45890
   613
      (i, (tyco, map Datatype_Aux.DtTFree vs, (map o apsnd) dtyps_of_typ constr));
wenzelm@45890
   614
    val descr = map_index mk_spec cs;
wenzelm@45890
   615
    val injs = Datatype_Prop.make_injs [descr];
wenzelm@45890
   616
    val half_distincts = Datatype_Prop.make_distincts [descr];
wenzelm@45890
   617
    val ind = Datatype_Prop.make_ind [descr];
wenzelm@45890
   618
    val rules = (map o map o map) Logic.close_form [[[ind]], injs, half_distincts];
wenzelm@45890
   619
wenzelm@45890
   620
    fun after_qed' raw_thms =
wenzelm@45890
   621
      let
wenzelm@45890
   622
        val [[[raw_induct]], raw_inject, half_distinct] =
wenzelm@45890
   623
          unflat rules (map Drule.zero_var_indexes_list raw_thms);
wenzelm@45890
   624
            (*FIXME somehow dubious*)
wenzelm@45890
   625
      in
wenzelm@45890
   626
        Proof_Context.background_theory_result  (* FIXME !? *)
wenzelm@45890
   627
          (prove_rep_datatype config dt_names descr raw_inject half_distinct raw_induct)
wenzelm@45890
   628
        #-> after_qed
wenzelm@45890
   629
      end;
wenzelm@45890
   630
  in
wenzelm@45890
   631
    ctxt
wenzelm@45890
   632
    |> Proof.theorem NONE after_qed' ((map o map) (rpair []) (flat rules))
wenzelm@45890
   633
  end;
wenzelm@45890
   634
wenzelm@45890
   635
in
wenzelm@45890
   636
wenzelm@45890
   637
val rep_datatype = gen_rep_datatype Sign.cert_term;
wenzelm@45890
   638
val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global;
wenzelm@45890
   639
wenzelm@45890
   640
end;
wenzelm@45890
   641
wenzelm@45890
   642
wenzelm@45890
   643
(* outer syntax *)
wenzelm@45890
   644
wenzelm@45890
   645
val _ =
wenzelm@46961
   646
  Outer_Syntax.command @{command_spec "rep_datatype"} "represent existing types inductively"
wenzelm@45890
   647
    (Scan.repeat1 Parse.term >> (fn ts =>
wenzelm@45890
   648
      Toplevel.print o
wenzelm@45890
   649
      Toplevel.theory_to_proof (rep_datatype_cmd Datatype_Aux.default_config (K I) ts)));
wenzelm@45890
   650
wenzelm@45890
   651
end;