src/HOL/Tools/datatype_package/datatype_abs_proofs.ML
author haftmann
Fri Jun 19 17:23:21 2009 +0200 (2009-06-19)
changeset 31723 f5cafe803b55
parent 31668 a616e56a5ec8
child 31737 b3f63611784e
permissions -rw-r--r--
discontinued ancient tradition to suffix certain ML module names with "_package"
     1 (*  Title:      HOL/Tools/datatype_abs_proofs.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Proofs and defintions independent of concrete representation
     5 of datatypes  (i.e. requiring only abstract properties such as
     6 injectivity / distinctness of constructors and induction)
     7 
     8  - case distinction (exhaustion) theorems
     9  - characteristic equations for primrec combinators
    10  - characteristic equations for case combinators
    11  - equations for splitting "P (case ...)" expressions
    12  - "nchotomy" and "case_cong" theorems for TFL
    13 *)
    14 
    15 signature DATATYPE_ABS_PROOFS =
    16 sig
    17   type datatype_config = DatatypeAux.datatype_config
    18   type descr = DatatypeAux.descr
    19   type datatype_info = DatatypeAux.datatype_info
    20   val prove_casedist_thms : datatype_config -> string list ->
    21     descr list -> (string * sort) list -> thm ->
    22     attribute list -> theory -> thm list * theory
    23   val prove_primrec_thms : datatype_config -> string list ->
    24     descr list -> (string * sort) list ->
    25       datatype_info Symtab.table -> thm list list -> thm list list ->
    26         simpset -> thm -> theory -> (string list * thm list) * theory
    27   val prove_case_thms : datatype_config -> string list ->
    28     descr list -> (string * sort) list ->
    29       string list -> thm list -> theory -> (thm list list * string list) * theory
    30   val prove_split_thms : datatype_config -> string list ->
    31     descr list -> (string * sort) list ->
    32       thm list list -> thm list list -> thm list -> thm list list -> theory ->
    33         (thm * thm) list * theory
    34   val prove_nchotomys : datatype_config -> string list -> descr list ->
    35     (string * sort) list -> thm list -> theory -> thm list * theory
    36   val prove_weak_case_congs : string list -> descr list ->
    37     (string * sort) list -> theory -> thm list * theory
    38   val prove_case_congs : string list ->
    39     descr list -> (string * sort) list ->
    40       thm list -> thm list list -> theory -> thm list * theory
    41 end;
    42 
    43 structure DatatypeAbsProofs: DATATYPE_ABS_PROOFS =
    44 struct
    45 
    46 open DatatypeAux;
    47 
    48 (************************ case distinction theorems ***************************)
    49 
    50 fun prove_casedist_thms (config : datatype_config) new_type_names descr sorts induct case_names_exhausts thy =
    51   let
    52     val _ = message config "Proving case distinction theorems ...";
    53 
    54     val descr' = List.concat descr;
    55     val recTs = get_rec_types descr' sorts;
    56     val newTs = Library.take (length (hd descr), recTs);
    57 
    58     val {maxidx, ...} = rep_thm induct;
    59     val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
    60 
    61     fun prove_casedist_thm ((i, t), T) =
    62       let
    63         val dummyPs = map (fn (Var (_, Type (_, [T', T'']))) =>
    64           Abs ("z", T', Const ("True", T''))) induct_Ps;
    65         val P = Abs ("z", T, HOLogic.imp $ HOLogic.mk_eq (Var (("a", maxidx+1), T), Bound 0) $
    66           Var (("P", 0), HOLogic.boolT))
    67         val insts = Library.take (i, dummyPs) @ (P::(Library.drop (i + 1, dummyPs)));
    68         val cert = cterm_of thy;
    69         val insts' = (map cert induct_Ps) ~~ (map cert insts);
    70         val induct' = refl RS ((List.nth
    71           (split_conj_thm (cterm_instantiate insts' induct), i)) RSN (2, rev_mp))
    72 
    73       in
    74         SkipProof.prove_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
    75           (fn {prems, ...} => EVERY
    76             [rtac induct' 1,
    77              REPEAT (rtac TrueI 1),
    78              REPEAT ((rtac impI 1) THEN (eresolve_tac prems 1)),
    79              REPEAT (rtac TrueI 1)])
    80       end;
    81 
    82     val casedist_thms = map prove_casedist_thm ((0 upto (length newTs - 1)) ~~
    83       (DatatypeProp.make_casedists descr sorts) ~~ newTs)
    84   in
    85     thy
    86     |> store_thms_atts "exhaust" new_type_names (map single case_names_exhausts) casedist_thms
    87   end;
    88 
    89 
    90 (*************************** primrec combinators ******************************)
    91 
    92 fun prove_primrec_thms (config : datatype_config) new_type_names descr sorts
    93     (dt_info : datatype_info Symtab.table) constr_inject dist_rewrites dist_ss induct thy =
    94   let
    95     val _ = message config "Constructing primrec combinators ...";
    96 
    97     val big_name = space_implode "_" new_type_names;
    98     val thy0 = add_path (#flat_names config) big_name thy;
    99 
   100     val descr' = List.concat descr;
   101     val recTs = get_rec_types descr' sorts;
   102     val used = List.foldr OldTerm.add_typ_tfree_names [] recTs;
   103     val newTs = Library.take (length (hd descr), recTs);
   104 
   105     val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
   106 
   107     val big_rec_name' = big_name ^ "_rec_set";
   108     val rec_set_names' =
   109       if length descr' = 1 then [big_rec_name'] else
   110         map ((curry (op ^) (big_rec_name' ^ "_")) o string_of_int)
   111           (1 upto (length descr'));
   112     val rec_set_names = map (Sign.full_bname thy0) rec_set_names';
   113 
   114     val (rec_result_Ts, reccomb_fn_Ts) = DatatypeProp.make_primrec_Ts descr sorts used;
   115 
   116     val rec_set_Ts = map (fn (T1, T2) =>
   117       reccomb_fn_Ts @ [T1, T2] ---> HOLogic.boolT) (recTs ~~ rec_result_Ts);
   118 
   119     val rec_fns = map (uncurry (mk_Free "f"))
   120       (reccomb_fn_Ts ~~ (1 upto (length reccomb_fn_Ts)));
   121     val rec_sets' = map (fn c => list_comb (Free c, rec_fns))
   122       (rec_set_names' ~~ rec_set_Ts);
   123     val rec_sets = map (fn c => list_comb (Const c, rec_fns))
   124       (rec_set_names ~~ rec_set_Ts);
   125 
   126     (* introduction rules for graph of primrec function *)
   127 
   128     fun make_rec_intr T rec_set ((rec_intr_ts, l), (cname, cargs)) =
   129       let
   130         fun mk_prem ((dt, U), (j, k, prems, t1s, t2s)) =
   131           let val free1 = mk_Free "x" U j
   132           in (case (strip_dtyp dt, strip_type U) of
   133              ((_, DtRec m), (Us, _)) =>
   134                let
   135                  val free2 = mk_Free "y" (Us ---> List.nth (rec_result_Ts, m)) k;
   136                  val i = length Us
   137                in (j + 1, k + 1, HOLogic.mk_Trueprop (HOLogic.list_all
   138                      (map (pair "x") Us, List.nth (rec_sets', m) $
   139                        app_bnds free1 i $ app_bnds free2 i)) :: prems,
   140                    free1::t1s, free2::t2s)
   141                end
   142            | _ => (j + 1, k, prems, free1::t1s, t2s))
   143           end;
   144 
   145         val Ts = map (typ_of_dtyp descr' sorts) cargs;
   146         val (_, _, prems, t1s, t2s) = List.foldr mk_prem (1, 1, [], [], []) (cargs ~~ Ts)
   147 
   148       in (rec_intr_ts @ [Logic.list_implies (prems, HOLogic.mk_Trueprop
   149         (rec_set $ list_comb (Const (cname, Ts ---> T), t1s) $
   150           list_comb (List.nth (rec_fns, l), t1s @ t2s)))], l + 1)
   151       end;
   152 
   153     val (rec_intr_ts, _) = Library.foldl (fn (x, ((d, T), set_name)) =>
   154       Library.foldl (make_rec_intr T set_name) (x, #3 (snd d)))
   155         (([], 0), descr' ~~ recTs ~~ rec_sets');
   156 
   157     val ({intrs = rec_intrs, elims = rec_elims, ...}, thy1) =
   158         Inductive.add_inductive_global (serial_string ())
   159           {quiet_mode = #quiet config, verbose = false, kind = Thm.internalK,
   160             alt_name = Binding.name big_rec_name', coind = false, no_elim = false, no_ind = true,
   161             skip_mono = true, fork_mono = false}
   162           (map (fn (s, T) => ((Binding.name s, T), NoSyn)) (rec_set_names' ~~ rec_set_Ts))
   163           (map dest_Free rec_fns)
   164           (map (fn x => (Attrib.empty_binding, x)) rec_intr_ts) [] thy0;
   165 
   166     (* prove uniqueness and termination of primrec combinators *)
   167 
   168     val _ = message config "Proving termination and uniqueness of primrec functions ...";
   169 
   170     fun mk_unique_tac ((tac, intrs), ((((i, (tname, _, constrs)), elim), T), T')) =
   171       let
   172         val distinct_tac =
   173           (if i < length newTs then
   174              full_simp_tac (HOL_ss addsimps (List.nth (dist_rewrites, i))) 1
   175            else full_simp_tac dist_ss 1);
   176 
   177         val inject = map (fn r => r RS iffD1)
   178           (if i < length newTs then List.nth (constr_inject, i)
   179             else #inject (the (Symtab.lookup dt_info tname)));
   180 
   181         fun mk_unique_constr_tac n ((tac, intr::intrs, j), (cname, cargs)) =
   182           let
   183             val k = length (List.filter is_rec_type cargs)
   184 
   185           in (EVERY [DETERM tac,
   186                 REPEAT (etac ex1E 1), rtac ex1I 1,
   187                 DEPTH_SOLVE_1 (ares_tac [intr] 1),
   188                 REPEAT_DETERM_N k (etac thin_rl 1 THEN rotate_tac 1 1),
   189                 etac elim 1,
   190                 REPEAT_DETERM_N j distinct_tac,
   191                 TRY (dresolve_tac inject 1),
   192                 REPEAT (etac conjE 1), hyp_subst_tac 1,
   193                 REPEAT (EVERY [etac allE 1, dtac mp 1, atac 1]),
   194                 TRY (hyp_subst_tac 1),
   195                 rtac refl 1,
   196                 REPEAT_DETERM_N (n - j - 1) distinct_tac],
   197               intrs, j + 1)
   198           end;
   199 
   200         val (tac', intrs', _) = Library.foldl (mk_unique_constr_tac (length constrs))
   201           ((tac, intrs, 0), constrs);
   202 
   203       in (tac', intrs') end;
   204 
   205     val rec_unique_thms =
   206       let
   207         val rec_unique_ts = map (fn (((set_t, T1), T2), i) =>
   208           Const ("Ex1", (T2 --> HOLogic.boolT) --> HOLogic.boolT) $
   209             absfree ("y", T2, set_t $ mk_Free "x" T1 i $ Free ("y", T2)))
   210               (rec_sets ~~ recTs ~~ rec_result_Ts ~~ (1 upto length recTs));
   211         val cert = cterm_of thy1
   212         val insts = map (fn ((i, T), t) => absfree ("x" ^ (string_of_int i), T, t))
   213           ((1 upto length recTs) ~~ recTs ~~ rec_unique_ts);
   214         val induct' = cterm_instantiate ((map cert induct_Ps) ~~
   215           (map cert insts)) induct;
   216         val (tac, _) = Library.foldl mk_unique_tac
   217           (((rtac induct' THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1
   218               THEN rewrite_goals_tac [mk_meta_eq choice_eq], rec_intrs),
   219             descr' ~~ rec_elims ~~ recTs ~~ rec_result_Ts);
   220 
   221       in split_conj_thm (SkipProof.prove_global thy1 [] []
   222         (HOLogic.mk_Trueprop (mk_conj rec_unique_ts)) (K tac))
   223       end;
   224 
   225     val rec_total_thms = map (fn r => r RS theI') rec_unique_thms;
   226 
   227     (* define primrec combinators *)
   228 
   229     val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
   230     val reccomb_names = map (Sign.full_bname thy1)
   231       (if length descr' = 1 then [big_reccomb_name] else
   232         (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
   233           (1 upto (length descr'))));
   234     val reccombs = map (fn ((name, T), T') => list_comb
   235       (Const (name, reccomb_fn_Ts @ [T] ---> T'), rec_fns))
   236         (reccomb_names ~~ recTs ~~ rec_result_Ts);
   237 
   238     val (reccomb_defs, thy2) =
   239       thy1
   240       |> Sign.add_consts_i (map (fn ((name, T), T') =>
   241           (Binding.name (Long_Name.base_name name), reccomb_fn_Ts @ [T] ---> T', NoSyn))
   242           (reccomb_names ~~ recTs ~~ rec_result_Ts))
   243       |> (PureThy.add_defs false o map Thm.no_attributes) (map (fn ((((name, comb), set), T), T') =>
   244           (Binding.name (Long_Name.base_name name ^ "_def"), Logic.mk_equals (comb, absfree ("x", T,
   245            Const ("The", (T' --> HOLogic.boolT) --> T') $ absfree ("y", T',
   246              set $ Free ("x", T) $ Free ("y", T'))))))
   247                (reccomb_names ~~ reccombs ~~ rec_sets ~~ recTs ~~ rec_result_Ts))
   248       ||> parent_path (#flat_names config) 
   249       ||> Theory.checkpoint;
   250 
   251 
   252     (* prove characteristic equations for primrec combinators *)
   253 
   254     val _ = message config "Proving characteristic theorems for primrec combinators ..."
   255 
   256     val rec_thms = map (fn t => SkipProof.prove_global thy2 [] [] t
   257       (fn _ => EVERY
   258         [rewrite_goals_tac reccomb_defs,
   259          rtac the1_equality 1,
   260          resolve_tac rec_unique_thms 1,
   261          resolve_tac rec_intrs 1,
   262          REPEAT (rtac allI 1 ORELSE resolve_tac rec_total_thms 1)]))
   263            (DatatypeProp.make_primrecs new_type_names descr sorts thy2)
   264 
   265   in
   266     thy2
   267     |> Sign.add_path (space_implode "_" new_type_names)
   268     |> PureThy.add_thmss [((Binding.name "recs", rec_thms),
   269          [Nitpick_Const_Simp_Thms.add])]
   270     ||> Sign.parent_path
   271     ||> Theory.checkpoint
   272     |-> (fn thms => pair (reccomb_names, Library.flat thms))
   273   end;
   274 
   275 
   276 (***************************** case combinators *******************************)
   277 
   278 fun prove_case_thms (config : datatype_config) new_type_names descr sorts reccomb_names primrec_thms thy =
   279   let
   280     val _ = message config "Proving characteristic theorems for case combinators ...";
   281 
   282     val thy1 = add_path (#flat_names config) (space_implode "_" new_type_names) thy;
   283 
   284     val descr' = List.concat descr;
   285     val recTs = get_rec_types descr' sorts;
   286     val used = List.foldr OldTerm.add_typ_tfree_names [] recTs;
   287     val newTs = Library.take (length (hd descr), recTs);
   288     val T' = TFree (Name.variant used "'t", HOLogic.typeS);
   289 
   290     fun mk_dummyT dt = binder_types (typ_of_dtyp descr' sorts dt) ---> T';
   291 
   292     val case_dummy_fns = map (fn (_, (_, _, constrs)) => map (fn (_, cargs) =>
   293       let
   294         val Ts = map (typ_of_dtyp descr' sorts) cargs;
   295         val Ts' = map mk_dummyT (List.filter is_rec_type cargs)
   296       in Const (@{const_name undefined}, Ts @ Ts' ---> T')
   297       end) constrs) descr';
   298 
   299     val case_names = map (fn s => Sign.full_bname thy1 (s ^ "_case")) new_type_names;
   300 
   301     (* define case combinators via primrec combinators *)
   302 
   303     val (case_defs, thy2) = Library.foldl (fn ((defs, thy),
   304       ((((i, (_, _, constrs)), T), name), recname)) =>
   305         let
   306           val (fns1, fns2) = ListPair.unzip (map (fn ((_, cargs), j) =>
   307             let
   308               val Ts = map (typ_of_dtyp descr' sorts) cargs;
   309               val Ts' = Ts @ map mk_dummyT (List.filter is_rec_type cargs);
   310               val frees' = map (uncurry (mk_Free "x")) (Ts' ~~ (1 upto length Ts'));
   311               val frees = Library.take (length cargs, frees');
   312               val free = mk_Free "f" (Ts ---> T') j
   313             in
   314              (free, list_abs_free (map dest_Free frees',
   315                list_comb (free, frees)))
   316             end) (constrs ~~ (1 upto length constrs)));
   317 
   318           val caseT = (map (snd o dest_Free) fns1) @ [T] ---> T';
   319           val fns = (List.concat (Library.take (i, case_dummy_fns))) @
   320             fns2 @ (List.concat (Library.drop (i + 1, case_dummy_fns)));
   321           val reccomb = Const (recname, (map fastype_of fns) @ [T] ---> T');
   322           val decl = ((Binding.name (Long_Name.base_name name), caseT), NoSyn);
   323           val def = (Binding.name (Long_Name.base_name name ^ "_def"),
   324             Logic.mk_equals (list_comb (Const (name, caseT), fns1),
   325               list_comb (reccomb, (List.concat (Library.take (i, case_dummy_fns))) @
   326                 fns2 @ (List.concat (Library.drop (i + 1, case_dummy_fns))) )));
   327           val ([def_thm], thy') =
   328             thy
   329             |> Sign.declare_const [] decl |> snd
   330             |> (PureThy.add_defs false o map Thm.no_attributes) [def];
   331 
   332         in (defs @ [def_thm], thy')
   333         end) (([], thy1), (hd descr) ~~ newTs ~~ case_names ~~
   334           (Library.take (length newTs, reccomb_names)))
   335       ||> Theory.checkpoint;
   336 
   337     val case_thms = map (map (fn t => SkipProof.prove_global thy2 [] [] t
   338       (fn _ => EVERY [rewrite_goals_tac (case_defs @ map mk_meta_eq primrec_thms), rtac refl 1])))
   339           (DatatypeProp.make_cases new_type_names descr sorts thy2)
   340   in
   341     thy2
   342     |> Context.the_theory o fold (fold Nitpick_Const_Simp_Thms.add_thm) case_thms
   343        o Context.Theory
   344     |> parent_path (#flat_names config)
   345     |> store_thmss "cases" new_type_names case_thms
   346     |-> (fn thmss => pair (thmss, case_names))
   347   end;
   348 
   349 
   350 (******************************* case splitting *******************************)
   351 
   352 fun prove_split_thms (config : datatype_config) new_type_names descr sorts constr_inject dist_rewrites
   353     casedist_thms case_thms thy =
   354   let
   355     val _ = message config "Proving equations for case splitting ...";
   356 
   357     val descr' = flat descr;
   358     val recTs = get_rec_types descr' sorts;
   359     val newTs = Library.take (length (hd descr), recTs);
   360 
   361     fun prove_split_thms ((((((t1, t2), inject), dist_rewrites'),
   362         exhaustion), case_thms'), T) =
   363       let
   364         val cert = cterm_of thy;
   365         val _ $ (_ $ lhs $ _) = hd (Logic.strip_assums_hyp (hd (prems_of exhaustion)));
   366         val exhaustion' = cterm_instantiate
   367           [(cert lhs, cert (Free ("x", T)))] exhaustion;
   368         val tacf = K (EVERY [rtac exhaustion' 1, ALLGOALS (asm_simp_tac
   369           (HOL_ss addsimps (dist_rewrites' @ inject @ case_thms')))])
   370       in
   371         (SkipProof.prove_global thy [] [] t1 tacf,
   372          SkipProof.prove_global thy [] [] t2 tacf)
   373       end;
   374 
   375     val split_thm_pairs = map prove_split_thms
   376       ((DatatypeProp.make_splits new_type_names descr sorts thy) ~~ constr_inject ~~
   377         dist_rewrites ~~ casedist_thms ~~ case_thms ~~ newTs);
   378 
   379     val (split_thms, split_asm_thms) = ListPair.unzip split_thm_pairs
   380 
   381   in
   382     thy
   383     |> store_thms "split" new_type_names split_thms
   384     ||>> store_thms "split_asm" new_type_names split_asm_thms
   385     |-> (fn (thms1, thms2) => pair (thms1 ~~ thms2))
   386   end;
   387 
   388 fun prove_weak_case_congs new_type_names descr sorts thy =
   389   let
   390     fun prove_weak_case_cong t =
   391        SkipProof.prove_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
   392          (fn {prems, ...} => EVERY [rtac ((hd prems) RS arg_cong) 1])
   393 
   394     val weak_case_congs = map prove_weak_case_cong (DatatypeProp.make_weak_case_congs
   395       new_type_names descr sorts thy)
   396 
   397   in thy |> store_thms "weak_case_cong" new_type_names weak_case_congs end;
   398 
   399 (************************* additional theorems for TFL ************************)
   400 
   401 fun prove_nchotomys (config : datatype_config) new_type_names descr sorts casedist_thms thy =
   402   let
   403     val _ = message config "Proving additional theorems for TFL ...";
   404 
   405     fun prove_nchotomy (t, exhaustion) =
   406       let
   407         (* For goal i, select the correct disjunct to attack, then prove it *)
   408         fun tac i 0 = EVERY [TRY (rtac disjI1 i),
   409               hyp_subst_tac i, REPEAT (rtac exI i), rtac refl i]
   410           | tac i n = rtac disjI2 i THEN tac i (n - 1)
   411       in 
   412         SkipProof.prove_global thy [] [] t (fn _ =>
   413           EVERY [rtac allI 1,
   414            exh_tac (K exhaustion) 1,
   415            ALLGOALS (fn i => tac i (i-1))])
   416       end;
   417 
   418     val nchotomys =
   419       map prove_nchotomy (DatatypeProp.make_nchotomys descr sorts ~~ casedist_thms)
   420 
   421   in thy |> store_thms "nchotomy" new_type_names nchotomys end;
   422 
   423 fun prove_case_congs new_type_names descr sorts nchotomys case_thms thy =
   424   let
   425     fun prove_case_cong ((t, nchotomy), case_rewrites) =
   426       let
   427         val (Const ("==>", _) $ tm $ _) = t;
   428         val (Const ("Trueprop", _) $ (Const ("op =", _) $ _ $ Ma)) = tm;
   429         val cert = cterm_of thy;
   430         val nchotomy' = nchotomy RS spec;
   431         val [v] = Term.add_vars (concl_of nchotomy') [];
   432         val nchotomy'' = cterm_instantiate [(cert (Var v), cert Ma)] nchotomy'
   433       in
   434         SkipProof.prove_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
   435           (fn {prems, ...} => 
   436             let val simplify = asm_simp_tac (HOL_ss addsimps (prems @ case_rewrites))
   437             in EVERY [simp_tac (HOL_ss addsimps [hd prems]) 1,
   438                 cut_facts_tac [nchotomy''] 1,
   439                 REPEAT (etac disjE 1 THEN REPEAT (etac exE 1) THEN simplify 1),
   440                 REPEAT (etac exE 1) THEN simplify 1 (* Get last disjunct *)]
   441             end)
   442       end;
   443 
   444     val case_congs = map prove_case_cong (DatatypeProp.make_case_congs
   445       new_type_names descr sorts thy ~~ nchotomys ~~ case_thms)
   446 
   447   in thy |> store_thms "case_cong" new_type_names case_congs end;
   448 
   449 end;