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