src/HOL/Tools/datatype_aux.ML
author wenzelm
Mon Mar 13 13:22:31 2000 +0100 (2000-03-13)
changeset 8435 51a040fd2200
parent 8404 4b39358f9810
child 9740 1c5b0f27de56
permissions -rw-r--r--
adapted to new PureThy.add_thms etc.;
added store_thms_atts;
     1 (*  Title:      HOL/Tools/datatype_aux.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer
     4     Copyright   1998  TU Muenchen
     5 
     6 Auxiliary functions for defining datatypes
     7 *)
     8 
     9 signature DATATYPE_AUX =
    10 sig
    11   val quiet_mode : bool ref
    12   val message : string -> unit
    13   
    14   val foldl1 : ('a * 'a -> 'a) -> 'a list -> 'a
    15 
    16   val add_path : bool -> string -> theory -> theory
    17   val parent_path : bool -> theory -> theory
    18 
    19   val store_thmss : string -> string list -> thm list list -> theory -> theory * thm list list
    20   val store_thms_atts : string -> string list -> theory attribute list list -> thm list
    21     -> theory -> theory * thm list
    22   val store_thms : string -> string list -> thm list -> theory -> theory * thm list
    23 
    24   val split_conj_thm : thm -> thm list
    25   val mk_conj : term list -> term
    26   val mk_disj : term list -> term
    27 
    28   val indtac : thm -> int -> tactic
    29   val exh_tac : (string -> thm) -> int -> tactic
    30 
    31   datatype simproc_dist = QuickAndDirty
    32                         | FewConstrs of thm list
    33                         | ManyConstrs of thm * simpset;
    34 
    35   datatype dtyp =
    36       DtTFree of string
    37     | DtType of string * (dtyp list)
    38     | DtRec of int;
    39   type descr
    40   type datatype_info
    41 
    42   exception Datatype
    43   val dtyp_of_typ : (string * string list) list -> typ -> dtyp
    44   val mk_Free : string -> typ -> int -> term
    45   val is_rec_type : dtyp -> bool
    46   val typ_of_dtyp : (int * (string * dtyp list *
    47     (string * dtyp list) list)) list -> (string * sort) list -> dtyp -> typ
    48   val dest_DtTFree : dtyp -> string
    49   val dest_DtRec : dtyp -> int
    50   val dest_TFree : typ -> string
    51   val get_nonrec_types : (int * (string * dtyp list *
    52     (string * dtyp list) list)) list -> (string * sort) list -> typ list
    53   val get_branching_types : (int * (string * dtyp list *
    54     (string * dtyp list) list)) list -> (string * sort) list -> typ list
    55   val get_rec_types : (int * (string * dtyp list *
    56     (string * dtyp list) list)) list -> (string * sort) list -> typ list
    57   val check_nonempty : (int * (string * dtyp list *
    58     (string * dtyp list) list)) list list -> unit
    59   val unfold_datatypes : 
    60     Sign.sg -> (int * (string * dtyp list * (string * dtyp list) list)) list ->
    61       (string * sort) list -> datatype_info Symtab.table ->
    62         (int * (string * dtyp list * (string * dtyp list) list)) list -> int ->
    63           (int * (string * dtyp list *
    64             (string * dtyp list) list)) list list * int
    65 end;
    66 
    67 structure DatatypeAux : DATATYPE_AUX =
    68 struct
    69 
    70 val quiet_mode = ref false;
    71 fun message s = if !quiet_mode then () else writeln s;
    72 
    73 (* FIXME: move to library ? *)
    74 fun foldl1 f (x::xs) = foldl f (x, xs);
    75 
    76 fun add_path flat_names s = if flat_names then I else Theory.add_path s;
    77 fun parent_path flat_names = if flat_names then I else Theory.parent_path;
    78 
    79 
    80 (* store theorems in theory *)
    81 
    82 fun store_thmss label tnames thmss thy =
    83   (thy, tnames ~~ thmss) |>
    84   foldl_map (fn (thy', (tname, thms)) => thy' |>
    85     Theory.add_path tname |>
    86     (apsnd hd o PureThy.add_thmss [((label, thms), [])]) |>>
    87     Theory.parent_path);
    88 
    89 fun store_thms_atts label tnames attss thms thy =
    90   (thy, tnames ~~ attss ~~ thms) |>
    91   foldl_map (fn (thy', ((tname, atts), thm)) => thy' |>
    92     Theory.add_path tname |>
    93     (apsnd hd o PureThy.add_thms [((label, thm), atts)]) |>>
    94     Theory.parent_path);
    95 
    96 fun store_thms label tnames = store_thms_atts label tnames (replicate (length tnames) []);
    97 
    98 
    99 (* split theorem thm_1 & ... & thm_n into n theorems *)
   100 
   101 fun split_conj_thm th =
   102   ((th RS conjunct1)::(split_conj_thm (th RS conjunct2))) handle THM _ => [th];
   103 
   104 val mk_conj = foldr1 (HOLogic.mk_binop "op &");
   105 val mk_disj = foldr1 (HOLogic.mk_binop "op |");
   106 
   107 
   108 (* instantiate induction rule *)
   109 
   110 fun indtac indrule i st =
   111   let
   112     val ts = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule));
   113     val ts' = HOLogic.dest_conj (HOLogic.dest_Trueprop
   114       (Logic.strip_imp_concl (nth_elem (i - 1, prems_of st))));
   115     val getP = if can HOLogic.dest_imp (hd ts) then
   116       (apfst Some) o HOLogic.dest_imp else pair None;
   117     fun abstr (t1, t2) = (case t1 of
   118         None => let val [Free (s, T)] = add_term_frees (t2, [])
   119           in absfree (s, T, t2) end
   120       | Some (_ $ t' $ _) => Abs ("x", fastype_of t', abstract_over (t', t2)))
   121     val cert = cterm_of (Thm.sign_of_thm st);
   122     val Ps = map (cert o head_of o snd o getP) ts;
   123     val indrule' = cterm_instantiate (Ps ~~
   124       (map (cert o abstr o getP) ts')) indrule
   125   in
   126     rtac indrule' i st
   127   end;
   128 
   129 (* perform exhaustive case analysis on last parameter of subgoal i *)
   130 
   131 fun exh_tac exh_thm_of i state =
   132   let
   133     val sg = Thm.sign_of_thm state;
   134     val prem = nth_elem (i - 1, prems_of state);
   135     val params = Logic.strip_params prem;
   136     val (_, Type (tname, _)) = hd (rev params);
   137     val exhaustion = lift_rule (state, i) (exh_thm_of tname);
   138     val prem' = hd (prems_of exhaustion);
   139     val _ $ (_ $ lhs $ _) = hd (rev (Logic.strip_assums_hyp prem'));
   140     val exhaustion' = cterm_instantiate [(cterm_of sg (head_of lhs),
   141       cterm_of sg (foldr (fn ((_, T), t) => Abs ("z", T, t))
   142         (params, Bound 0)))] exhaustion
   143   in compose_tac (false, exhaustion', nprems_of exhaustion) i state
   144   end;
   145 
   146 (* handling of distinctness theorems *)
   147 
   148 datatype simproc_dist = QuickAndDirty
   149                       | FewConstrs of thm list
   150                       | ManyConstrs of thm * simpset;
   151 
   152 (********************** Internal description of datatypes *********************)
   153 
   154 datatype dtyp =
   155     DtTFree of string
   156   | DtType of string * (dtyp list)
   157   | DtRec of int;
   158 
   159 (* information about datatypes *)
   160 
   161 type descr = (int * (string * dtyp list * (string * dtyp list) list)) list;
   162 
   163 type datatype_info =
   164   {index : int,
   165    descr : descr,
   166    rec_names : string list,
   167    rec_rewrites : thm list,
   168    case_name : string,
   169    case_rewrites : thm list,
   170    induction : thm,
   171    exhaustion : thm,
   172    distinct : simproc_dist,
   173    inject : thm list,
   174    nchotomy : thm,
   175    case_cong : thm};
   176 
   177 fun mk_Free s T i = Free (s ^ (string_of_int i), T);
   178 
   179 fun subst_DtTFree _ substs (T as (DtTFree name)) =
   180       (case assoc (substs, name) of
   181          None => T
   182        | Some U => U)
   183   | subst_DtTFree i substs (DtType (name, ts)) =
   184       DtType (name, map (subst_DtTFree i substs) ts)
   185   | subst_DtTFree i _ (DtRec j) = DtRec (i + j);
   186 
   187 exception Datatype;
   188 
   189 fun dest_DtTFree (DtTFree a) = a
   190   | dest_DtTFree _ = raise Datatype;
   191 
   192 fun dest_DtRec (DtRec i) = i
   193   | dest_DtRec _ = raise Datatype;
   194 
   195 fun is_rec_type (DtType (_, dts)) = exists is_rec_type dts
   196   | is_rec_type (DtRec _) = true
   197   | is_rec_type _ = false;
   198 
   199 fun dest_TFree (TFree (n, _)) = n;
   200 
   201 fun dtyp_of_typ _ (TFree (n, _)) = DtTFree n
   202   | dtyp_of_typ _ (TVar _) = error "Illegal schematic type variable(s)"
   203   | dtyp_of_typ new_dts (Type (tname, Ts)) =
   204       (case assoc (new_dts, tname) of
   205          None => DtType (tname, map (dtyp_of_typ new_dts) Ts)
   206        | Some vs => if map (try dest_TFree) Ts = map Some vs then
   207              DtRec (find_index (curry op = tname o fst) new_dts)
   208            else error ("Illegal occurence of recursive type " ^ tname));
   209 
   210 fun typ_of_dtyp descr sorts (DtTFree a) = TFree (a, the (assoc (sorts, a)))
   211   | typ_of_dtyp descr sorts (DtRec i) =
   212       let val (s, ds, _) = the (assoc (descr, i))
   213       in Type (s, map (typ_of_dtyp descr sorts) ds) end
   214   | typ_of_dtyp descr sorts (DtType (s, ds)) =
   215       Type (s, map (typ_of_dtyp descr sorts) ds);
   216 
   217 (* find all non-recursive types in datatype description *)
   218 
   219 fun get_nonrec_types descr sorts =
   220   let fun add (Ts, T as DtTFree _) = T ins Ts
   221         | add (Ts, T as DtType ("fun", [_, DtRec _])) = Ts
   222         | add (Ts, T as DtType _) = T ins Ts
   223         | add (Ts, _) = Ts
   224   in map (typ_of_dtyp descr sorts) (foldl (fn (Ts, (_, (_, _, constrs))) =>
   225     foldl (fn (Ts', (_, cargs)) =>
   226       foldl add (Ts', cargs)) (Ts, constrs)) ([], descr))
   227   end;
   228 
   229 (* get all recursive types in datatype description *)
   230 
   231 fun get_rec_types descr sorts = map (fn (_ , (s, ds, _)) =>
   232   Type (s, map (typ_of_dtyp descr sorts) ds)) descr;
   233 
   234 (* get all branching types *)
   235 
   236 fun get_branching_types descr sorts = 
   237   let fun add (Ts, DtType ("fun", [T, DtRec _])) = T ins Ts
   238         | add (Ts, _) = Ts
   239   in map (typ_of_dtyp descr sorts) (foldl (fn (Ts, (_, (_, _, constrs))) =>
   240     foldl (fn (Ts', (_, cargs)) =>
   241       foldl add (Ts', cargs)) (Ts, constrs)) ([], descr))
   242   end;
   243 
   244 (* nonemptiness check for datatypes *)
   245 
   246 fun check_nonempty descr =
   247   let
   248     val descr' = flat descr;
   249     fun is_nonempty_dt is i =
   250       let
   251         val (_, _, constrs) = the (assoc (descr', i));
   252         fun arg_nonempty (DtRec i) = if i mem is then false
   253               else is_nonempty_dt (i::is) i
   254           | arg_nonempty (DtType ("fun", [_, T])) = arg_nonempty T
   255           | arg_nonempty _ = true;
   256       in exists ((forall arg_nonempty) o snd) constrs
   257       end
   258   in assert_all (fn (i, _) => is_nonempty_dt [i] i) (hd descr)
   259     (fn (_, (s, _, _)) => "Nonemptiness check failed for datatype " ^ s)
   260   end;
   261 
   262 (* unfold a list of mutually recursive datatype specifications *)
   263 (* all types of the form DtType (dt_name, [..., DtRec _, ...]) *)
   264 (* need to be unfolded                                         *)
   265 
   266 fun unfold_datatypes sign orig_descr sorts (dt_info : datatype_info Symtab.table) descr i =
   267   let
   268     fun typ_error T msg = error ("Non-admissible type expression\n" ^
   269       Sign.string_of_typ sign (typ_of_dtyp (orig_descr @ descr) sorts T) ^ "\n" ^ msg);
   270 
   271     fun get_dt_descr T i tname dts =
   272       (case Symtab.lookup (dt_info, tname) of
   273          None => typ_error T (tname ^ " is not a datatype - can't use it in\
   274            \ nested recursion")
   275        | (Some {index, descr, ...}) =>
   276            let val (_, vars, _) = the (assoc (descr, index));
   277                val subst = ((map dest_DtTFree vars) ~~ dts) handle LIST _ =>
   278                  typ_error T ("Type constructor " ^ tname ^ " used with wrong\
   279                   \ number of arguments")
   280            in (i + index, map (fn (j, (tn, args, cs)) => (i + j,
   281              (tn, map (subst_DtTFree i subst) args,
   282               map (apsnd (map (subst_DtTFree i subst))) cs))) descr)
   283            end);
   284 
   285     (* unfold a single constructor argument *)
   286 
   287     fun unfold_arg ((i, Ts, descrs), T as (DtType (tname, dts))) =
   288           if is_rec_type T then
   289             if tname = "fun" then
   290               if is_rec_type (hd dts) then
   291                 typ_error T "Non-strictly positive recursive occurrence of type"
   292               else
   293                 (case hd (tl dts) of
   294                    DtType ("fun", _) => typ_error T "Curried function types not allowed"
   295                  | T' => let val (i', [T''], descrs') = unfold_arg ((i, [], descrs), T')
   296                          in (i', Ts @ [DtType (tname, [hd dts, T''])], descrs') end)
   297             else
   298               let val (index, descr) = get_dt_descr T i tname dts;
   299                   val (descr', i') = unfold_datatypes sign orig_descr sorts dt_info descr (i + length descr)
   300               in (i', Ts @ [DtRec index], descrs @ descr') end
   301           else (i, Ts @ [T], descrs)
   302       | unfold_arg ((i, Ts, descrs), T) = (i, Ts @ [T], descrs);
   303 
   304     (* unfold a constructor *)
   305 
   306     fun unfold_constr ((i, constrs, descrs), (cname, cargs)) =
   307       let val (i', cargs', descrs') = foldl unfold_arg ((i, [], descrs), cargs)
   308       in (i', constrs @ [(cname, cargs')], descrs') end;
   309 
   310     (* unfold a single datatype *)
   311 
   312     fun unfold_datatype ((i, dtypes, descrs), (j, (tname, tvars, constrs))) =
   313       let val (i', constrs', descrs') =
   314         foldl unfold_constr ((i, [], descrs), constrs)
   315       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs')
   316       end;
   317 
   318     val (i', descr', descrs) = foldl unfold_datatype ((i, [],[]), descr);
   319 
   320   in (descr' :: descrs, i') end;
   321 
   322 end;