src/HOL/Tools/Datatype/datatype_aux.ML
author haftmann
Wed May 05 18:25:34 2010 +0200 (2010-05-05)
changeset 36692 54b64d4ad524
parent 35364 b8c62d60195c
child 38795 848be46708dc
permissions -rw-r--r--
farewell to old-style mem infixes -- type inference in situations with mem_int and mem_string should provide enough information to resolve the type of (op =)
     1 (*  Title:      HOL/Tools/Datatype/datatype_aux.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Datatype package: auxiliary data structures and functions.
     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 * 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   val find_shortest_path : descr -> int -> (string * int) option
    83 end;
    84 
    85 structure Datatype_Aux : DATATYPE_AUX =
    86 struct
    87 
    88 (* datatype option flags *)
    89 
    90 type config = {strict : bool, quiet : bool};
    91 val default_config : config = {strict = true, quiet = false};
    92 
    93 fun message ({quiet = true, ...} : config) s = writeln s
    94   | message _ _ = ();
    95 
    96 
    97 (* store theorems in theory *)
    98 
    99 fun store_thmss_atts label tnames attss thmss =
   100   fold_map (fn ((tname, atts), thms) =>
   101     Sign.add_path tname
   102     #> PureThy.add_thmss [((Binding.name label, thms), atts)]
   103     #-> (fn thm::_ => Sign.parent_path #> pair thm)) (tnames ~~ attss ~~ thmss)
   104   ##> Theory.checkpoint;
   105 
   106 fun store_thmss label tnames = store_thmss_atts label tnames (replicate (length tnames) []);
   107 
   108 fun store_thms_atts label tnames attss thmss =
   109   fold_map (fn ((tname, atts), thms) =>
   110     Sign.add_path tname
   111     #> PureThy.add_thms [((Binding.name label, thms), atts)]
   112     #-> (fn thm::_ => Sign.parent_path #> pair thm)) (tnames ~~ attss ~~ thmss)
   113   ##> Theory.checkpoint;
   114 
   115 fun store_thms label tnames = store_thms_atts label tnames (replicate (length tnames) []);
   116 
   117 
   118 (* split theorem thm_1 & ... & thm_n into n theorems *)
   119 
   120 fun split_conj_thm th =
   121   ((th RS conjunct1)::(split_conj_thm (th RS conjunct2))) handle THM _ => [th];
   122 
   123 val mk_conj = foldr1 (HOLogic.mk_binop @{const_name "op &"});
   124 val mk_disj = foldr1 (HOLogic.mk_binop @{const_name "op |"});
   125 
   126 fun app_bnds t i = list_comb (t, map Bound (i - 1 downto 0));
   127 
   128 
   129 (* instantiate induction rule *)
   130 
   131 fun indtac indrule indnames i st =
   132   let
   133     val ts = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule));
   134     val ts' = HOLogic.dest_conj (HOLogic.dest_Trueprop
   135       (Logic.strip_imp_concl (List.nth (prems_of st, i - 1))));
   136     val getP = if can HOLogic.dest_imp (hd ts) then
   137       (apfst SOME) o HOLogic.dest_imp else pair NONE;
   138     val flt = if null indnames then I else
   139       filter (fn Free (s, _) => member (op =) indnames s | _ => false);
   140     fun abstr (t1, t2) = (case t1 of
   141         NONE => (case flt (OldTerm.term_frees t2) of
   142             [Free (s, T)] => SOME (absfree (s, T, t2))
   143           | _ => NONE)
   144       | SOME (_ $ t') => SOME (Abs ("x", fastype_of t', abstract_over (t', t2))))
   145     val cert = cterm_of (Thm.theory_of_thm st);
   146     val insts = map_filter (fn (t, u) => case abstr (getP u) of
   147         NONE => NONE
   148       | SOME u' => SOME (t |> getP |> snd |> head_of |> cert, cert u')) (ts ~~ ts');
   149     val indrule' = cterm_instantiate insts indrule
   150   in
   151     rtac indrule' i st
   152   end;
   153 
   154 (* perform exhaustive case analysis on last parameter of subgoal i *)
   155 
   156 fun exh_tac exh_thm_of i state =
   157   let
   158     val thy = Thm.theory_of_thm state;
   159     val prem = nth (prems_of state) (i - 1);
   160     val params = Logic.strip_params prem;
   161     val (_, Type (tname, _)) = hd (rev params);
   162     val exhaustion = Thm.lift_rule (Thm.cprem_of state i) (exh_thm_of tname);
   163     val prem' = hd (prems_of exhaustion);
   164     val _ $ (_ $ lhs $ _) = hd (rev (Logic.strip_assums_hyp prem'));
   165     val exhaustion' = cterm_instantiate [(cterm_of thy (head_of lhs),
   166       cterm_of thy (fold_rev (fn (_, T) => fn t => Abs ("z", T, t)) params (Bound 0)))] 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 "_" (filter_out (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) (fold (fn (_, (_, _, constrs)) =>
   259     fold (fn (_, cargs) => union (op =) (filter_out is_rec_type cargs)) constrs) descr []);
   260 
   261 (* get all recursive types in datatype description *)
   262 
   263 fun get_rec_types descr sorts = map (fn (_ , (s, ds, _)) =>
   264   Type (s, map (typ_of_dtyp descr sorts) ds)) descr;
   265 
   266 (* get all branching types *)
   267 
   268 fun get_branching_types descr sorts =
   269   map (typ_of_dtyp descr sorts) (fold (fn (_, (_, _, constrs)) =>
   270     fold (fn (_, cargs) => fold (strip_dtyp #> fst #> fold (insert op =)) cargs)
   271       constrs) descr []);
   272 
   273 fun get_arities descr = fold (fn (_, (_, _, constrs)) =>
   274   fold (fn (_, cargs) => fold (insert op =) (map (length o fst o strip_dtyp)
   275     (filter is_rec_type cargs))) constrs) descr [];
   276 
   277 (* interpret construction of datatype *)
   278 
   279 fun interpret_construction descr vs { atyp, dtyp } =
   280   let
   281     val typ_of_dtyp = typ_of_dtyp descr vs;
   282     fun interpT dT = case strip_dtyp dT
   283      of (dTs, DtRec l) =>
   284           let
   285             val (tyco, dTs', _) = (the o AList.lookup (op =) descr) l;
   286             val Ts = map typ_of_dtyp dTs;
   287             val Ts' = map typ_of_dtyp dTs';
   288             val is_proper = forall (can dest_TFree) Ts';
   289           in dtyp Ts (l, is_proper) (tyco, Ts') end
   290       | _ => atyp (typ_of_dtyp dT);
   291     fun interpC (c, dTs) = (c, map interpT dTs);
   292     fun interpD (_, (tyco, dTs, cs)) = ((tyco, map typ_of_dtyp dTs), map interpC cs);
   293   in map interpD descr end;
   294 
   295 (* nonemptiness check for datatypes *)
   296 
   297 fun check_nonempty descr =
   298   let
   299     val descr' = flat descr;
   300     fun is_nonempty_dt is i =
   301       let
   302         val (_, _, constrs) = (the o AList.lookup (op =) descr') i;
   303         fun arg_nonempty (_, DtRec i) = if member (op =) is i then false
   304               else is_nonempty_dt (i::is) i
   305           | arg_nonempty _ = true;
   306       in exists ((forall (arg_nonempty o strip_dtyp)) o snd) constrs
   307       end
   308   in assert_all (fn (i, _) => is_nonempty_dt [i] i) (hd descr)
   309     (fn (_, (s, _, _)) => raise Datatype_Empty s)
   310   end;
   311 
   312 (* unfold a list of mutually recursive datatype specifications *)
   313 (* all types of the form DtType (dt_name, [..., DtRec _, ...]) *)
   314 (* need to be unfolded                                         *)
   315 
   316 fun unfold_datatypes sign orig_descr sorts (dt_info : info Symtab.table) descr i =
   317   let
   318     fun typ_error T msg = error ("Non-admissible type expression\n" ^
   319       Syntax.string_of_typ_global sign (typ_of_dtyp (orig_descr @ descr) sorts T) ^ "\n" ^ msg);
   320 
   321     fun get_dt_descr T i tname dts =
   322       (case Symtab.lookup dt_info tname of
   323          NONE => typ_error T (tname ^ " is not a datatype - can't use it in\
   324            \ nested recursion")
   325        | (SOME {index, descr, ...}) =>
   326            let val (_, vars, _) = (the o AList.lookup (op =) descr) index;
   327                val subst = ((map dest_DtTFree vars) ~~ dts) handle Library.UnequalLengths =>
   328                  typ_error T ("Type constructor " ^ tname ^ " used with wrong\
   329                   \ number of arguments")
   330            in (i + index, map (fn (j, (tn, args, cs)) => (i + j,
   331              (tn, map (subst_DtTFree i subst) args,
   332               map (apsnd (map (subst_DtTFree i subst))) cs))) descr)
   333            end);
   334 
   335     (* unfold a single constructor argument *)
   336 
   337     fun unfold_arg T (i, Ts, descrs) =
   338       if is_rec_type T then
   339         let val (Us, U) = strip_dtyp T
   340         in if exists is_rec_type Us then
   341             typ_error T "Non-strictly positive recursive occurrence of type"
   342           else (case U of
   343               DtType (tname, dts) =>  
   344                 let
   345                   val (index, descr) = get_dt_descr T i tname dts;
   346                   val (descr', i') = unfold_datatypes sign orig_descr sorts
   347                     dt_info descr (i + length descr)
   348                 in (i', Ts @ [mk_fun_dtyp Us (DtRec index)], descrs @ descr') end
   349             | _ => (i, Ts @ [T], descrs))
   350         end
   351       else (i, Ts @ [T], descrs);
   352 
   353     (* unfold a constructor *)
   354 
   355     fun unfold_constr (cname, cargs) (i, constrs, descrs) =
   356       let val (i', cargs', descrs') = fold unfold_arg cargs (i, [], descrs)
   357       in (i', constrs @ [(cname, cargs')], descrs') end;
   358 
   359     (* unfold a single datatype *)
   360 
   361     fun unfold_datatype (j, (tname, tvars, constrs)) (i, dtypes, descrs) =
   362       let val (i', constrs', descrs') = fold unfold_constr constrs (i, [], descrs)
   363       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs') end;
   364 
   365     val (i', descr', descrs) = fold unfold_datatype descr (i, [], []);
   366 
   367   in (descr' :: descrs, i') end;
   368 
   369 (* find shortest path to constructor with no recursive arguments *)
   370 
   371 fun find_nonempty descr is i =
   372   let
   373     fun arg_nonempty (_, DtRec i) = if member (op =) is i
   374           then NONE
   375           else Option.map (Integer.add 1 o snd) (find_nonempty descr (i::is) i)
   376       | arg_nonempty _ = SOME 0;
   377     fun max_inf (SOME i) (SOME j) = SOME (Integer.max i j)
   378       | max_inf _ _ = NONE;
   379     fun max xs = fold max_inf xs (SOME 0);
   380     val (_, _, constrs) = the (AList.lookup (op =) descr i);
   381     val xs = sort (int_ord o pairself snd)
   382       (map_filter (fn (s, dts) => Option.map (pair s)
   383         (max (map (arg_nonempty o strip_dtyp) dts))) constrs)
   384   in if null xs then NONE else SOME (hd xs) end;
   385 
   386 fun find_shortest_path descr i = find_nonempty descr [i] i;
   387 
   388 end;