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