src/HOL/Tools/function_package/size.ML
author wenzelm
Tue, 02 Sep 2008 14:10:45 +0200
changeset 28083 103d9282a946
parent 27691 ce171cbd4b93
child 28361 232fcbba2e4e
permissions -rw-r--r--
explicit type Name.binding for higher-specification elements;
     1 (*  Title:      HOL/Tools/function_package/size.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, Florian Haftmann, TU Muenchen
     4 
     5 Size functions for datatypes.
     6 *)
     7 
     8 signature SIZE =
     9 sig
    10   val size_thms: theory -> string -> thm list
    11   val setup: theory -> theory
    12 end;
    13 
    14 structure Size: SIZE =
    15 struct
    16 
    17 open DatatypeAux;
    18 
    19 structure SizeData = TheoryDataFun
    20 (
    21   type T = (string * thm list) Symtab.table;
    22   val empty = Symtab.empty;
    23   val copy = I
    24   val extend = I
    25   fun merge _ = Symtab.merge (K true);
    26 );
    27 
    28 val lookup_size = SizeData.get #> Symtab.lookup;
    29 
    30 fun plus (t1, t2) = Const ("HOL.plus_class.plus",
    31   HOLogic.natT --> HOLogic.natT --> HOLogic.natT) $ t1 $ t2;
    32 
    33 fun size_of_type f g h (T as Type (s, Ts)) =
    34       (case f s of
    35          SOME t => SOME t
    36        | NONE => (case g s of
    37            SOME size_name =>
    38              SOME (list_comb (Const (size_name,
    39                map (fn U => U --> HOLogic.natT) Ts @ [T] ---> HOLogic.natT),
    40                  map (size_of_type' f g h) Ts))
    41          | NONE => NONE))
    42   | size_of_type f g h (TFree (s, _)) = h s
    43 and size_of_type' f g h T = (case size_of_type f g h T of
    44       NONE => Abs ("x", T, HOLogic.zero)
    45     | SOME t => t);
    46 
    47 fun is_poly thy (DtType (name, dts)) =
    48       (case DatatypePackage.get_datatype thy name of
    49          NONE => false
    50        | SOME _ => exists (is_poly thy) dts)
    51   | is_poly _ _ = true;
    52 
    53 fun constrs_of thy name =
    54   let
    55     val {descr, index, ...} = DatatypePackage.the_datatype thy name
    56     val SOME (_, _, constrs) = AList.lookup op = descr index
    57   in constrs end;
    58 
    59 val app = curry (list_comb o swap);
    60 
    61 fun prove_size_thms (info : datatype_info) new_type_names thy =
    62   let
    63     val {descr, alt_names, sorts, rec_names, rec_rewrites, induction, ...} = info;
    64     val l = length new_type_names;
    65     val alt_names' = (case alt_names of
    66       NONE => replicate l NONE | SOME names => map SOME names);
    67     val descr' = List.take (descr, l);
    68     val (rec_names1, rec_names2) = chop l rec_names;
    69     val recTs = get_rec_types descr sorts;
    70     val (recTs1, recTs2) = chop l recTs;
    71     val (_, (_, paramdts, _)) :: _ = descr;
    72     val paramTs = map (typ_of_dtyp descr sorts) paramdts;
    73     val ((param_size_fs, param_size_fTs), f_names) = paramTs |>
    74       map (fn T as TFree (s, _) =>
    75         let
    76           val name = "f" ^ implode (tl (explode s));
    77           val U = T --> HOLogic.natT
    78         in
    79           (((s, Free (name, U)), U), name)
    80         end) |> split_list |>> split_list;
    81     val param_size = AList.lookup op = param_size_fs;
    82 
    83     val extra_rewrites = descr |> map (#1 o snd) |> distinct op = |>
    84       List.mapPartial (Option.map snd o lookup_size thy) |> flat;
    85     val extra_size = Option.map fst o lookup_size thy;
    86 
    87     val (((size_names, size_fns), def_names), def_names') =
    88       recTs1 ~~ alt_names' |>
    89       map (fn (T as Type (s, _), optname) =>
    90         let
    91           val s' = the_default (Sign.base_name s) optname ^ "_size";
    92           val s'' = Sign.full_name thy s'
    93         in
    94           (s'',
    95            (list_comb (Const (s'', param_size_fTs @ [T] ---> HOLogic.natT),
    96               map snd param_size_fs),
    97             (s' ^ "_def", s' ^ "_overloaded_def")))
    98         end) |> split_list ||>> split_list ||>> split_list;
    99     val overloaded_size_fns = map HOLogic.size_const recTs1;
   100 
   101     (* instantiation for primrec combinator *)
   102     fun size_of_constr b size_ofp ((_, cargs), (_, cargs')) =
   103       let
   104         val Ts = map (typ_of_dtyp descr sorts) cargs;
   105         val k = length (filter is_rec_type cargs);
   106         val (ts, _, _) = fold_rev (fn ((dt, dt'), T) => fn (us, i, j) =>
   107           if is_rec_type dt then (Bound i :: us, i + 1, j + 1)
   108           else
   109             (if b andalso is_poly thy dt' then
   110                case size_of_type (K NONE) extra_size size_ofp T of
   111                  NONE => us | SOME sz => sz $ Bound j :: us
   112              else us, i, j + 1))
   113               (cargs ~~ cargs' ~~ Ts) ([], 0, k);
   114         val t =
   115           if null ts andalso (not b orelse not (exists (is_poly thy) cargs'))
   116           then HOLogic.zero
   117           else foldl1 plus (ts @ [HOLogic.Suc_zero])
   118       in
   119         foldr (fn (T, t') => Abs ("x", T, t')) t (Ts @ replicate k HOLogic.natT)
   120       end;
   121 
   122     val fs = maps (fn (_, (name, _, constrs)) =>
   123       map (size_of_constr true param_size) (constrs ~~ constrs_of thy name)) descr;
   124     val fs' = maps (fn (n, (name, _, constrs)) =>
   125       map (size_of_constr (l <= n) (K NONE)) (constrs ~~ constrs_of thy name)) descr;
   126     val fTs = map fastype_of fs;
   127 
   128     val (rec_combs1, rec_combs2) = chop l (map (fn (T, rec_name) =>
   129       Const (rec_name, fTs @ [T] ---> HOLogic.natT))
   130         (recTs ~~ rec_names));
   131 
   132     fun define_overloaded (def_name, eq) lthy =
   133       let
   134         val (Free (c, _), rhs) = (Logic.dest_equals o Syntax.check_term lthy) eq;
   135         val ((_, (_, thm)), lthy') = lthy |> LocalTheory.define Thm.definitionK
   136           ((Name.binding c, NoSyn), ((Name.binding def_name, []), rhs));
   137         val ctxt_thy = ProofContext.init (ProofContext.theory_of lthy');
   138         val thm' = singleton (ProofContext.export lthy' ctxt_thy) thm;
   139       in (thm', lthy') end;
   140 
   141     val ((size_def_thms, size_def_thms'), thy') =
   142       thy
   143       |> Sign.add_consts_i (map (fn (s, T) =>
   144            (Sign.base_name s, param_size_fTs @ [T] ---> HOLogic.natT, NoSyn))
   145            (size_names ~~ recTs1))
   146       |> PureThy.add_defs false
   147         (map (Thm.no_attributes o apsnd (Logic.mk_equals o apsnd (app fs)))
   148            (def_names ~~ (size_fns ~~ rec_combs1)))
   149       ||> TheoryTarget.instantiation
   150            (map (#1 o snd) descr', map dest_TFree paramTs, [HOLogic.class_size])
   151       ||>> fold_map define_overloaded
   152         (def_names' ~~ map Logic.mk_equals (overloaded_size_fns ~~ map (app fs') rec_combs1))
   153       ||> Class.prove_instantiation_instance (K (Class.intro_classes_tac []))
   154       ||> LocalTheory.exit
   155       ||> ProofContext.theory_of;
   156 
   157     val ctxt = ProofContext.init thy';
   158 
   159     val simpset1 = HOL_basic_ss addsimps @{thm add_0} :: @{thm add_0_right} ::
   160       size_def_thms @ size_def_thms' @ rec_rewrites @ extra_rewrites;
   161     val xs = map (fn i => "x" ^ string_of_int i) (1 upto length recTs2);
   162 
   163     fun mk_unfolded_size_eq tab size_ofp fs (p as (x, T), r) =
   164       HOLogic.mk_eq (app fs r $ Free p,
   165         the (size_of_type tab extra_size size_ofp T) $ Free p);
   166 
   167     fun prove_unfolded_size_eqs size_ofp fs =
   168       if null recTs2 then []
   169       else split_conj_thm (SkipProof.prove ctxt xs []
   170         (HOLogic.mk_Trueprop (mk_conj (replicate l HOLogic.true_const @
   171            map (mk_unfolded_size_eq (AList.lookup op =
   172                (new_type_names ~~ map (app fs) rec_combs1)) size_ofp fs)
   173              (xs ~~ recTs2 ~~ rec_combs2))))
   174         (fn _ => (indtac induction xs THEN_ALL_NEW asm_simp_tac simpset1) 1));
   175 
   176     val unfolded_size_eqs1 = prove_unfolded_size_eqs param_size fs;
   177     val unfolded_size_eqs2 = prove_unfolded_size_eqs (K NONE) fs';
   178 
   179     (* characteristic equations for size functions *)
   180     fun gen_mk_size_eq p size_of size_ofp size_const T (cname, cargs) =
   181       let
   182         val Ts = map (typ_of_dtyp descr sorts) cargs;
   183         val tnames = Name.variant_list f_names (DatatypeProp.make_tnames Ts);
   184         val ts = List.mapPartial (fn (sT as (s, T), dt) =>
   185           Option.map (fn sz => sz $ Free sT)
   186             (if p dt then size_of_type size_of extra_size size_ofp T
   187              else NONE)) (tnames ~~ Ts ~~ cargs)
   188       in
   189         HOLogic.mk_Trueprop (HOLogic.mk_eq
   190           (size_const $ list_comb (Const (cname, Ts ---> T),
   191              map2 (curry Free) tnames Ts),
   192            if null ts then HOLogic.zero
   193            else foldl1 plus (ts @ [HOLogic.Suc_zero])))
   194       end;
   195 
   196     val simpset2 = HOL_basic_ss addsimps
   197       rec_rewrites @ size_def_thms @ unfolded_size_eqs1;
   198     val simpset3 = HOL_basic_ss addsimps
   199       rec_rewrites @ size_def_thms' @ unfolded_size_eqs2;
   200 
   201     fun prove_size_eqs p size_fns size_ofp simpset =
   202       maps (fn (((_, (_, _, constrs)), size_const), T) =>
   203         map (fn constr => standard (SkipProof.prove ctxt [] []
   204           (gen_mk_size_eq p (AList.lookup op = (new_type_names ~~ size_fns))
   205              size_ofp size_const T constr)
   206           (fn _ => simp_tac simpset 1))) constrs)
   207         (descr' ~~ size_fns ~~ recTs1);
   208 
   209     val size_eqns = prove_size_eqs (is_poly thy') size_fns param_size simpset2 @
   210       prove_size_eqs is_rec_type overloaded_size_fns (K NONE) simpset3;
   211 
   212     val ([size_thms], thy'') =  PureThy.add_thmss
   213       [(("size", size_eqns),
   214         [Simplifier.simp_add, Thm.declaration_attribute
   215               (fn thm => Context.mapping (Code.add_default_func thm) I)])] thy'
   216 
   217   in
   218     SizeData.map (fold (Symtab.update_new o apsnd (rpair size_thms))
   219       (new_type_names ~~ size_names)) thy''
   220   end;
   221 
   222 fun add_size_thms (new_type_names as name :: _) thy =
   223   let
   224     val info as {descr, alt_names, ...} = DatatypePackage.the_datatype thy name;
   225     val prefix = NameSpace.map_base (K (space_implode "_"
   226       (the_default (map Sign.base_name new_type_names) alt_names))) name;
   227     val no_size = exists (fn (_, (_, _, constrs)) => exists (fn (_, cargs) => exists (fn dt =>
   228       is_rec_type dt andalso not (null (fst (strip_dtyp dt)))) cargs) constrs) descr
   229   in if no_size then thy
   230     else
   231       thy
   232       |> Sign.root_path
   233       |> Sign.add_path prefix
   234       |> prove_size_thms info new_type_names
   235       |> Sign.restore_naming thy
   236   end;
   237 
   238 val size_thms = snd oo (the oo lookup_size);
   239 
   240 val setup = DatatypePackage.interpretation add_size_thms;
   241 
   242 end;