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