src/HOL/Tools/datatype_aux.ML
author wenzelm
Sun Feb 27 15:26:47 2000 +0100 (2000-02-27)
changeset 8305 93aa21ec5494
parent 7015 85be09eb136c
child 8324 df7dccddc3de
permissions -rw-r--r--
HOLogic.dest_conj;
     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 *
   158      (string * dtyp list) list)) list,
   159    rec_names : string list,
   160    rec_rewrites : thm list,
   161    case_name : string,
   162    case_rewrites : thm list,
   163    induction : thm,
   164    exhaustion : thm,
   165    distinct : simproc_dist,
   166    inject : thm list,
   167    nchotomy : thm,
   168    case_cong : thm};
   169 
   170 fun mk_Free s T i = Free (s ^ (string_of_int i), T);
   171 
   172 fun subst_DtTFree _ substs (T as (DtTFree name)) =
   173       (case assoc (substs, name) of
   174          None => T
   175        | Some U => U)
   176   | subst_DtTFree i substs (DtType (name, ts)) =
   177       DtType (name, map (subst_DtTFree i substs) ts)
   178   | subst_DtTFree i _ (DtRec j) = DtRec (i + j);
   179 
   180 exception Datatype;
   181 
   182 fun dest_DtTFree (DtTFree a) = a
   183   | dest_DtTFree _ = raise Datatype;
   184 
   185 fun dest_DtRec (DtRec i) = i
   186   | dest_DtRec _ = raise Datatype;
   187 
   188 fun is_rec_type (DtType (_, dts)) = exists is_rec_type dts
   189   | is_rec_type (DtRec _) = true
   190   | is_rec_type _ = false;
   191 
   192 fun dest_TFree (TFree (n, _)) = n;
   193 
   194 fun dtyp_of_typ _ (TFree (n, _)) = DtTFree n
   195   | dtyp_of_typ _ (TVar _) = error "Illegal schematic type variable(s)"
   196   | dtyp_of_typ new_dts (Type (tname, Ts)) =
   197       (case assoc (new_dts, tname) of
   198          None => DtType (tname, map (dtyp_of_typ new_dts) Ts)
   199        | Some vs => if map (try dest_TFree) Ts = map Some vs then
   200              DtRec (find_index (curry op = tname o fst) new_dts)
   201            else error ("Illegal occurence of recursive type " ^ tname));
   202 
   203 fun typ_of_dtyp descr sorts (DtTFree a) = TFree (a, the (assoc (sorts, a)))
   204   | typ_of_dtyp descr sorts (DtRec i) =
   205       let val (s, ds, _) = the (assoc (descr, i))
   206       in Type (s, map (typ_of_dtyp descr sorts) ds) end
   207   | typ_of_dtyp descr sorts (DtType (s, ds)) =
   208       Type (s, map (typ_of_dtyp descr sorts) ds);
   209 
   210 (* find all non-recursive types in datatype description *)
   211 
   212 fun get_nonrec_types descr sorts =
   213   let fun add (Ts, T as DtTFree _) = T ins Ts
   214         | add (Ts, T as DtType ("fun", [_, DtRec _])) = Ts
   215         | add (Ts, T as DtType _) = T ins Ts
   216         | add (Ts, _) = Ts
   217   in map (typ_of_dtyp descr sorts) (foldl (fn (Ts, (_, (_, _, constrs))) =>
   218     foldl (fn (Ts', (_, cargs)) =>
   219       foldl add (Ts', cargs)) (Ts, constrs)) ([], descr))
   220   end;
   221 
   222 (* get all recursive types in datatype description *)
   223 
   224 fun get_rec_types descr sorts = map (fn (_ , (s, ds, _)) =>
   225   Type (s, map (typ_of_dtyp descr sorts) ds)) descr;
   226 
   227 (* get all branching types *)
   228 
   229 fun get_branching_types descr sorts = 
   230   let fun add (Ts, DtType ("fun", [T, DtRec _])) = T ins Ts
   231         | add (Ts, _) = Ts
   232   in map (typ_of_dtyp descr sorts) (foldl (fn (Ts, (_, (_, _, constrs))) =>
   233     foldl (fn (Ts', (_, cargs)) =>
   234       foldl add (Ts', cargs)) (Ts, constrs)) ([], descr))
   235   end;
   236 
   237 (* nonemptiness check for datatypes *)
   238 
   239 fun check_nonempty descr =
   240   let
   241     val descr' = flat descr;
   242     fun is_nonempty_dt is i =
   243       let
   244         val (_, _, constrs) = the (assoc (descr', i));
   245         fun arg_nonempty (DtRec i) = if i mem is then false
   246               else is_nonempty_dt (i::is) i
   247           | arg_nonempty (DtType ("fun", [_, T])) = arg_nonempty T
   248           | arg_nonempty _ = true;
   249       in exists ((forall arg_nonempty) o snd) constrs
   250       end
   251   in assert_all (fn (i, _) => is_nonempty_dt [i] i) (hd descr)
   252     (fn (_, (s, _, _)) => "Nonemptiness check failed for datatype " ^ s)
   253   end;
   254 
   255 (* unfold a list of mutually recursive datatype specifications *)
   256 (* all types of the form DtType (dt_name, [..., DtRec _, ...]) *)
   257 (* need to be unfolded                                         *)
   258 
   259 fun unfold_datatypes sign orig_descr sorts (dt_info : datatype_info Symtab.table) descr i =
   260   let
   261     fun typ_error T msg = error ("Non-admissible type expression\n" ^
   262       Sign.string_of_typ sign (typ_of_dtyp (orig_descr @ descr) sorts T) ^ "\n" ^ msg);
   263 
   264     fun get_dt_descr T i tname dts =
   265       (case Symtab.lookup (dt_info, tname) of
   266          None => typ_error T (tname ^ " is not a datatype - can't use it in\
   267            \ nested recursion")
   268        | (Some {index, descr, ...}) =>
   269            let val (_, vars, _) = the (assoc (descr, index));
   270                val subst = ((map dest_DtTFree vars) ~~ dts) handle LIST _ =>
   271                  typ_error T ("Type constructor " ^ tname ^ " used with wrong\
   272                   \ number of arguments")
   273            in (i + index, map (fn (j, (tn, args, cs)) => (i + j,
   274              (tn, map (subst_DtTFree i subst) args,
   275               map (apsnd (map (subst_DtTFree i subst))) cs))) descr)
   276            end);
   277 
   278     (* unfold a single constructor argument *)
   279 
   280     fun unfold_arg ((i, Ts, descrs), T as (DtType (tname, dts))) =
   281           if is_rec_type T then
   282             if tname = "fun" then
   283               if is_rec_type (hd dts) then
   284                 typ_error T "Non-strictly positive recursive occurrence of type"
   285               else
   286                 (case hd (tl dts) of
   287                    DtType ("fun", _) => typ_error T "Curried function types not allowed"
   288                  | T' => let val (i', [T''], descrs') = unfold_arg ((i, [], descrs), T')
   289                          in (i', Ts @ [DtType (tname, [hd dts, T''])], descrs') end)
   290             else
   291               let val (index, descr) = get_dt_descr T i tname dts;
   292                   val (descr', i') = unfold_datatypes sign orig_descr sorts dt_info descr (i + length descr)
   293               in (i', Ts @ [DtRec index], descrs @ descr') end
   294           else (i, Ts @ [T], descrs)
   295       | unfold_arg ((i, Ts, descrs), T) = (i, Ts @ [T], descrs);
   296 
   297     (* unfold a constructor *)
   298 
   299     fun unfold_constr ((i, constrs, descrs), (cname, cargs)) =
   300       let val (i', cargs', descrs') = foldl unfold_arg ((i, [], descrs), cargs)
   301       in (i', constrs @ [(cname, cargs')], descrs') end;
   302 
   303     (* unfold a single datatype *)
   304 
   305     fun unfold_datatype ((i, dtypes, descrs), (j, (tname, tvars, constrs))) =
   306       let val (i', constrs', descrs') =
   307         foldl unfold_constr ((i, [], descrs), constrs)
   308       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs')
   309       end;
   310 
   311     val (i', descr', descrs) = foldl unfold_datatype ((i, [],[]), descr);
   312 
   313   in (descr' :: descrs, i') end;
   314 
   315 end;