src/HOL/Tools/Datatype/datatype_aux.ML
author haftmann
Tue Oct 20 16:13:01 2009 +0200 (2009-10-20)
changeset 33037 b22e44496dc2
parent 32964 2d7e1ab55037
child 33038 8f9594c31de4
permissions -rw-r--r--
replaced old_style infixes eq_set, subset, union, inter and variants by generic versions
     1 (*  Title:      HOL/Tools/datatype_aux.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Auxiliary functions for defining datatypes.
     5 *)
     6 
     7 signature DATATYPE_COMMON =
     8 sig
     9   type config = {strict : bool, quiet : bool}
    10   val default_config : config
    11   datatype dtyp =
    12       DtTFree of string
    13     | DtType of string * dtyp list
    14     | DtRec of int
    15   type descr = (int * (string * dtyp list * (string * dtyp list) list)) list
    16   type info =
    17    {index : int,
    18     alt_names : string list option,
    19     descr : descr,
    20     sorts : (string * sort) list,
    21     inject : thm list,
    22     distinct : thm list,
    23     induct : thm,
    24     inducts : thm list,
    25     exhaust : thm,
    26     nchotomy : thm,
    27     rec_names : string list,
    28     rec_rewrites : thm list,
    29     case_name : string,
    30     case_rewrites : thm list,
    31     case_cong : thm,
    32     weak_case_cong : thm,
    33     split : thm,
    34     split_asm: thm}
    35 end
    36 
    37 signature DATATYPE_AUX =
    38 sig
    39   include DATATYPE_COMMON
    40 
    41   val message : config -> string -> unit
    42   
    43   val store_thmss_atts : string -> string list -> attribute list list -> thm list list
    44     -> theory -> thm list list * theory
    45   val store_thmss : string -> string list -> thm list list -> theory -> thm list list * theory
    46   val store_thms_atts : string -> string list -> attribute list list -> thm list
    47     -> theory -> thm list * theory
    48   val store_thms : string -> string list -> thm list -> theory -> thm list * theory
    49 
    50   val split_conj_thm : thm -> thm list
    51   val mk_conj : term list -> term
    52   val mk_disj : term list -> term
    53 
    54   val app_bnds : term -> int -> term
    55 
    56   val indtac : thm -> string list -> int -> tactic
    57   val exh_tac : (string -> thm) -> int -> tactic
    58 
    59   exception Datatype
    60   exception Datatype_Empty of string
    61   val name_of_typ : typ -> string
    62   val dtyp_of_typ : (string * string list) list -> typ -> dtyp
    63   val mk_Free : string -> typ -> int -> term
    64   val is_rec_type : dtyp -> bool
    65   val typ_of_dtyp : descr -> (string * sort) list -> dtyp -> typ
    66   val dest_DtTFree : dtyp -> string
    67   val dest_DtRec : dtyp -> int
    68   val strip_dtyp : dtyp -> dtyp list * dtyp
    69   val body_index : dtyp -> int
    70   val mk_fun_dtyp : dtyp list -> dtyp -> dtyp
    71   val get_nonrec_types : descr -> (string * sort) list -> typ list
    72   val get_branching_types : descr -> (string * sort) list -> typ list
    73   val get_arities : descr -> int list
    74   val get_rec_types : descr -> (string * sort) list -> typ list
    75   val interpret_construction : descr -> (string * sort) list
    76     -> { atyp: typ -> 'a, dtyp: typ list -> int * bool -> string * typ list -> 'a }
    77     -> ((string * Term.typ list) * (string * 'a list) list) list
    78   val check_nonempty : descr list -> unit
    79   val unfold_datatypes : 
    80     theory -> descr -> (string * sort) list -> info Symtab.table ->
    81       descr -> int -> descr list * int
    82 end;
    83 
    84 structure DatatypeAux : DATATYPE_AUX =
    85 struct
    86 
    87 (* datatype option flags *)
    88 
    89 type config = {strict : bool, quiet : bool};
    90 val default_config : config = {strict = true, quiet = false};
    91 
    92 fun message ({quiet = true, ...} : config) s = writeln s
    93   | message _ _ = ();
    94 
    95 
    96 (* store theorems in theory *)
    97 
    98 fun store_thmss_atts label tnames attss thmss =
    99   fold_map (fn ((tname, atts), thms) =>
   100     Sign.add_path tname
   101     #> PureThy.add_thmss [((Binding.name label, thms), atts)]
   102     #-> (fn thm::_ => Sign.parent_path #> pair thm)) (tnames ~~ attss ~~ thmss)
   103   ##> Theory.checkpoint;
   104 
   105 fun store_thmss label tnames = store_thmss_atts label tnames (replicate (length tnames) []);
   106 
   107 fun store_thms_atts label tnames attss thmss =
   108   fold_map (fn ((tname, atts), thms) =>
   109     Sign.add_path tname
   110     #> PureThy.add_thms [((Binding.name label, thms), atts)]
   111     #-> (fn thm::_ => Sign.parent_path #> pair thm)) (tnames ~~ attss ~~ thmss)
   112   ##> Theory.checkpoint;
   113 
   114 fun store_thms label tnames = store_thms_atts label tnames (replicate (length tnames) []);
   115 
   116 
   117 (* split theorem thm_1 & ... & thm_n into n theorems *)
   118 
   119 fun split_conj_thm th =
   120   ((th RS conjunct1)::(split_conj_thm (th RS conjunct2))) handle THM _ => [th];
   121 
   122 val mk_conj = foldr1 (HOLogic.mk_binop "op &");
   123 val mk_disj = foldr1 (HOLogic.mk_binop "op |");
   124 
   125 fun app_bnds t i = list_comb (t, map Bound (i - 1 downto 0));
   126 
   127 
   128 (* instantiate induction rule *)
   129 
   130 fun indtac indrule indnames i st =
   131   let
   132     val ts = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule));
   133     val ts' = HOLogic.dest_conj (HOLogic.dest_Trueprop
   134       (Logic.strip_imp_concl (List.nth (prems_of st, i - 1))));
   135     val getP = if can HOLogic.dest_imp (hd ts) then
   136       (apfst SOME) o HOLogic.dest_imp else pair NONE;
   137     val flt = if null indnames then I else
   138       filter (fn Free (s, _) => s mem indnames | _ => false);
   139     fun abstr (t1, t2) = (case t1 of
   140         NONE => (case flt (OldTerm.term_frees t2) of
   141             [Free (s, T)] => SOME (absfree (s, T, t2))
   142           | _ => NONE)
   143       | SOME (_ $ t') => SOME (Abs ("x", fastype_of t', abstract_over (t', t2))))
   144     val cert = cterm_of (Thm.theory_of_thm st);
   145     val insts = map_filter (fn (t, u) => case abstr (getP u) of
   146         NONE => NONE
   147       | SOME u' => SOME (t |> getP |> snd |> head_of |> cert, cert u')) (ts ~~ ts');
   148     val indrule' = cterm_instantiate insts indrule
   149   in
   150     rtac indrule' i st
   151   end;
   152 
   153 (* perform exhaustive case analysis on last parameter of subgoal i *)
   154 
   155 fun exh_tac exh_thm_of i state =
   156   let
   157     val thy = Thm.theory_of_thm state;
   158     val prem = nth (prems_of state) (i - 1);
   159     val params = Logic.strip_params prem;
   160     val (_, Type (tname, _)) = hd (rev params);
   161     val exhaustion = Thm.lift_rule (Thm.cprem_of state i) (exh_thm_of tname);
   162     val prem' = hd (prems_of exhaustion);
   163     val _ $ (_ $ lhs $ _) = hd (rev (Logic.strip_assums_hyp prem'));
   164     val exhaustion' = cterm_instantiate [(cterm_of thy (head_of lhs),
   165       cterm_of thy (List.foldr (fn ((_, T), t) => Abs ("z", T, t))
   166         (Bound 0) params))] exhaustion
   167   in compose_tac (false, exhaustion', nprems_of exhaustion) i state
   168   end;
   169 
   170 
   171 (********************** Internal description of datatypes *********************)
   172 
   173 datatype dtyp =
   174     DtTFree of string
   175   | DtType of string * (dtyp list)
   176   | DtRec of int;
   177 
   178 (* information about datatypes *)
   179 
   180 (* index, datatype name, type arguments, constructor name, types of constructor's arguments *)
   181 type descr = (int * (string * dtyp list * (string * dtyp list) list)) list;
   182 
   183 type info =
   184   {index : int,
   185    alt_names : string list option,
   186    descr : descr,
   187    sorts : (string * sort) list,
   188    inject : thm list,
   189    distinct : thm list,
   190    induct : thm,
   191    inducts : thm list,
   192    exhaust : thm,
   193    nchotomy : thm,
   194    rec_names : string list,
   195    rec_rewrites : thm list,
   196    case_name : string,
   197    case_rewrites : thm list,
   198    case_cong : thm,
   199    weak_case_cong : thm,
   200    split : thm,
   201    split_asm: thm};
   202 
   203 fun mk_Free s T i = Free (s ^ (string_of_int i), T);
   204 
   205 fun subst_DtTFree _ substs (T as (DtTFree name)) =
   206       AList.lookup (op =) substs name |> the_default T
   207   | subst_DtTFree i substs (DtType (name, ts)) =
   208       DtType (name, map (subst_DtTFree i substs) ts)
   209   | subst_DtTFree i _ (DtRec j) = DtRec (i + j);
   210 
   211 exception Datatype;
   212 exception Datatype_Empty of string;
   213 
   214 fun dest_DtTFree (DtTFree a) = a
   215   | dest_DtTFree _ = raise Datatype;
   216 
   217 fun dest_DtRec (DtRec i) = i
   218   | dest_DtRec _ = raise Datatype;
   219 
   220 fun is_rec_type (DtType (_, dts)) = exists is_rec_type dts
   221   | is_rec_type (DtRec _) = true
   222   | is_rec_type _ = false;
   223 
   224 fun strip_dtyp (DtType ("fun", [T, U])) = apfst (cons T) (strip_dtyp U)
   225   | strip_dtyp T = ([], T);
   226 
   227 val body_index = dest_DtRec o snd o strip_dtyp;
   228 
   229 fun mk_fun_dtyp [] U = U
   230   | mk_fun_dtyp (T :: Ts) U = DtType ("fun", [T, mk_fun_dtyp Ts U]);
   231 
   232 fun name_of_typ (Type (s, Ts)) =
   233       let val s' = Long_Name.base_name s
   234       in space_implode "_" (List.filter (not o equal "") (map name_of_typ Ts) @
   235         [if Syntax.is_identifier s' then s' else "x"])
   236       end
   237   | name_of_typ _ = "";
   238 
   239 fun dtyp_of_typ _ (TFree (n, _)) = DtTFree n
   240   | dtyp_of_typ _ (TVar _) = error "Illegal schematic type variable(s)"
   241   | dtyp_of_typ new_dts (Type (tname, Ts)) =
   242       (case AList.lookup (op =) new_dts tname of
   243          NONE => DtType (tname, map (dtyp_of_typ new_dts) Ts)
   244        | SOME vs => if map (try (fst o dest_TFree)) Ts = map SOME vs then
   245              DtRec (find_index (curry op = tname o fst) new_dts)
   246            else error ("Illegal occurrence of recursive type " ^ tname));
   247 
   248 fun typ_of_dtyp descr sorts (DtTFree a) = TFree (a, (the o AList.lookup (op =) sorts) a)
   249   | typ_of_dtyp descr sorts (DtRec i) =
   250       let val (s, ds, _) = (the o AList.lookup (op =) descr) i
   251       in Type (s, map (typ_of_dtyp descr sorts) ds) end
   252   | typ_of_dtyp descr sorts (DtType (s, ds)) =
   253       Type (s, map (typ_of_dtyp descr sorts) ds);
   254 
   255 (* find all non-recursive types in datatype description *)
   256 
   257 fun get_nonrec_types descr sorts =
   258   map (typ_of_dtyp descr sorts) (Library.foldl (fn (Ts, (_, (_, _, constrs))) =>
   259     Library.foldl (fn (Ts', (_, cargs)) =>
   260       gen_union (op =) (filter_out is_rec_type cargs, Ts')) (Ts, constrs)) ([], descr));
   261 
   262 (* get all recursive types in datatype description *)
   263 
   264 fun get_rec_types descr sorts = map (fn (_ , (s, ds, _)) =>
   265   Type (s, map (typ_of_dtyp descr sorts) ds)) descr;
   266 
   267 (* get all branching types *)
   268 
   269 fun get_branching_types descr sorts =
   270   map (typ_of_dtyp descr sorts) (fold (fn (_, (_, _, constrs)) =>
   271     fold (fn (_, cargs) => fold (strip_dtyp #> fst #> fold (insert op =)) cargs)
   272       constrs) descr []);
   273 
   274 fun get_arities descr = fold (fn (_, (_, _, constrs)) =>
   275   fold (fn (_, cargs) => fold (insert op =) (map (length o fst o strip_dtyp)
   276     (List.filter is_rec_type cargs))) constrs) descr [];
   277 
   278 (* interpret construction of datatype *)
   279 
   280 fun interpret_construction descr vs { atyp, dtyp } =
   281   let
   282     val typ_of_dtyp = typ_of_dtyp descr vs;
   283     fun interpT dT = case strip_dtyp dT
   284      of (dTs, DtRec l) =>
   285           let
   286             val (tyco, dTs', _) = (the o AList.lookup (op =) descr) l;
   287             val Ts = map typ_of_dtyp dTs;
   288             val Ts' = map typ_of_dtyp dTs';
   289             val is_proper = forall (can dest_TFree) Ts';
   290           in dtyp Ts (l, is_proper) (tyco, Ts') end
   291       | _ => atyp (typ_of_dtyp dT);
   292     fun interpC (c, dTs) = (c, map interpT dTs);
   293     fun interpD (_, (tyco, dTs, cs)) = ((tyco, map typ_of_dtyp dTs), map interpC cs);
   294   in map interpD descr end;
   295 
   296 (* nonemptiness check for datatypes *)
   297 
   298 fun check_nonempty descr =
   299   let
   300     val descr' = flat descr;
   301     fun is_nonempty_dt is i =
   302       let
   303         val (_, _, constrs) = (the o AList.lookup (op =) descr') i;
   304         fun arg_nonempty (_, DtRec i) = if i mem is then false
   305               else is_nonempty_dt (i::is) i
   306           | arg_nonempty _ = true;
   307       in exists ((forall (arg_nonempty o strip_dtyp)) o snd) constrs
   308       end
   309   in assert_all (fn (i, _) => is_nonempty_dt [i] i) (hd descr)
   310     (fn (_, (s, _, _)) => raise Datatype_Empty s)
   311   end;
   312 
   313 (* unfold a list of mutually recursive datatype specifications *)
   314 (* all types of the form DtType (dt_name, [..., DtRec _, ...]) *)
   315 (* need to be unfolded                                         *)
   316 
   317 fun unfold_datatypes sign orig_descr sorts (dt_info : info Symtab.table) descr i =
   318   let
   319     fun typ_error T msg = error ("Non-admissible type expression\n" ^
   320       Syntax.string_of_typ_global sign (typ_of_dtyp (orig_descr @ descr) sorts T) ^ "\n" ^ msg);
   321 
   322     fun get_dt_descr T i tname dts =
   323       (case Symtab.lookup dt_info tname of
   324          NONE => typ_error T (tname ^ " is not a datatype - can't use it in\
   325            \ nested recursion")
   326        | (SOME {index, descr, ...}) =>
   327            let val (_, vars, _) = (the o AList.lookup (op =) descr) index;
   328                val subst = ((map dest_DtTFree vars) ~~ dts) handle Library.UnequalLengths =>
   329                  typ_error T ("Type constructor " ^ tname ^ " used with wrong\
   330                   \ number of arguments")
   331            in (i + index, map (fn (j, (tn, args, cs)) => (i + j,
   332              (tn, map (subst_DtTFree i subst) args,
   333               map (apsnd (map (subst_DtTFree i subst))) cs))) descr)
   334            end);
   335 
   336     (* unfold a single constructor argument *)
   337 
   338     fun unfold_arg ((i, Ts, descrs), T) =
   339       if is_rec_type T then
   340         let val (Us, U) = strip_dtyp T
   341         in if exists is_rec_type Us then
   342             typ_error T "Non-strictly positive recursive occurrence of type"
   343           else (case U of
   344               DtType (tname, dts) =>  
   345                 let
   346                   val (index, descr) = get_dt_descr T i tname dts;
   347                   val (descr', i') = unfold_datatypes sign orig_descr sorts
   348                     dt_info descr (i + length descr)
   349                 in (i', Ts @ [mk_fun_dtyp Us (DtRec index)], descrs @ descr') end
   350             | _ => (i, Ts @ [T], descrs))
   351         end
   352       else (i, Ts @ [T], descrs);
   353 
   354     (* unfold a constructor *)
   355 
   356     fun unfold_constr ((i, constrs, descrs), (cname, cargs)) =
   357       let val (i', cargs', descrs') = Library.foldl unfold_arg ((i, [], descrs), cargs)
   358       in (i', constrs @ [(cname, cargs')], descrs') end;
   359 
   360     (* unfold a single datatype *)
   361 
   362     fun unfold_datatype ((i, dtypes, descrs), (j, (tname, tvars, constrs))) =
   363       let val (i', constrs', descrs') =
   364         Library.foldl unfold_constr ((i, [], descrs), constrs)
   365       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs')
   366       end;
   367 
   368     val (i', descr', descrs) = Library.foldl unfold_datatype ((i, [],[]), descr);
   369 
   370   in (descr' :: descrs, i') end;
   371 
   372 end;