src/HOL/Tools/Old_Datatype/old_datatype_aux.ML
author wenzelm
Sat Jul 18 21:44:18 2015 +0200 (2015-07-18)
changeset 60757 c09598a97436
parent 60328 9c94e6a30d29
child 60781 2da59cdf531c
permissions -rw-r--r--
prefer tactics with explicit context;
     1 (*  Title:      HOL/Tools/Old_Datatype/old_datatype_aux.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Datatype package: auxiliary data structures and functions.
     5 *)
     6 
     7 signature OLD_DATATYPE_COMMON =
     8 sig
     9   type config = {strict : bool, quiet : bool}
    10   val default_config : config
    11   datatype dtyp =
    12       DtTFree of string * sort
    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     descr : descr,
    19     inject : thm list,
    20     distinct : thm list,
    21     induct : thm,
    22     inducts : thm list,
    23     exhaust : thm,
    24     nchotomy : thm,
    25     rec_names : string list,
    26     rec_rewrites : thm list,
    27     case_name : string,
    28     case_rewrites : thm list,
    29     case_cong : thm,
    30     case_cong_weak : thm,
    31     split : thm,
    32     split_asm: thm}
    33   type spec = (binding * (string * sort) list * mixfix) * (binding * typ list * mixfix) list
    34 end
    35 
    36 signature OLD_DATATYPE_AUX =
    37 sig
    38   include OLD_DATATYPE_COMMON
    39 
    40   val message : config -> string -> unit
    41 
    42   val store_thmss_atts : string -> string list -> attribute list list -> thm list list
    43     -> theory -> thm list list * theory
    44   val store_thmss : string -> string list -> thm list list -> theory -> thm list list * theory
    45   val store_thms_atts : string -> string list -> attribute list list -> thm list
    46     -> theory -> thm list * theory
    47   val store_thms : string -> string list -> thm list -> theory -> thm list * theory
    48 
    49   val split_conj_thm : thm -> thm list
    50   val mk_conj : term list -> term
    51   val mk_disj : term list -> term
    52 
    53   val app_bnds : term -> int -> term
    54 
    55   val ind_tac : Proof.context -> thm -> string list -> int -> tactic
    56   val exh_tac : Proof.context -> (string -> thm) -> int -> tactic
    57 
    58   exception Datatype
    59   exception Datatype_Empty of string
    60   val name_of_typ : typ -> string
    61   val dtyp_of_typ : (string * (string * sort) list) list -> typ -> dtyp
    62   val mk_Free : string -> typ -> int -> term
    63   val is_rec_type : dtyp -> bool
    64   val typ_of_dtyp : descr -> dtyp -> typ
    65   val dest_DtTFree : dtyp -> string * sort
    66   val dest_DtRec : dtyp -> int
    67   val strip_dtyp : dtyp -> dtyp list * dtyp
    68   val body_index : dtyp -> int
    69   val mk_fun_dtyp : dtyp list -> dtyp -> dtyp
    70   val get_nonrec_types : descr -> typ list
    71   val get_branching_types : descr -> typ list
    72   val get_arities : descr -> int list
    73   val get_rec_types : descr -> typ list
    74   val interpret_construction : descr -> (string * sort) list ->
    75     {atyp: typ -> 'a, dtyp: typ list -> int * bool -> string * typ list -> 'a} ->
    76     ((string * typ list) * (string * 'a list) list) list
    77   val check_nonempty : descr list -> unit
    78   val unfold_datatypes : Proof.context -> descr -> info Symtab.table ->
    79     descr -> int -> descr list * int
    80   val find_shortest_path : descr -> int -> (string * int) option
    81 end;
    82 
    83 structure Old_Datatype_Aux : OLD_DATATYPE_AUX =
    84 struct
    85 
    86 (* datatype option flags *)
    87 
    88 type config = {strict : bool, quiet : bool};
    89 val default_config : config = {strict = true, quiet = false};
    90 
    91 fun message ({quiet = true, ...} : config) s = writeln s
    92   | message _ _ = ();
    93 
    94 
    95 (* store theorems in theory *)
    96 
    97 fun store_thmss_atts name tnames attss thmss =
    98   fold_map (fn ((tname, atts), thms) =>
    99     Global_Theory.note_thmss ""
   100       [((Binding.qualify true tname (Binding.name name), atts), [(thms, [])])]
   101     #-> (fn [(_, res)] => pair res)) (tnames ~~ attss ~~ thmss);
   102 
   103 fun store_thmss name tnames = store_thmss_atts name tnames (replicate (length tnames) []);
   104 
   105 fun store_thms_atts name tnames attss thms =
   106   fold_map (fn ((tname, atts), thm) =>
   107     Global_Theory.note_thmss ""
   108       [((Binding.qualify true tname (Binding.name name), atts), [([thm], [])])]
   109     #-> (fn [(_, [res])] => pair res)) (tnames ~~ attss ~~ thms);
   110 
   111 fun store_thms name tnames = store_thms_atts name tnames (replicate (length tnames) []);
   112 
   113 
   114 (* split theorem thm_1 & ... & thm_n into n theorems *)
   115 
   116 fun split_conj_thm th =
   117   ((th RS conjunct1) :: split_conj_thm (th RS conjunct2)) handle THM _ => [th];
   118 
   119 val mk_conj = foldr1 (HOLogic.mk_binop @{const_name HOL.conj});
   120 val mk_disj = foldr1 (HOLogic.mk_binop @{const_name HOL.disj});
   121 
   122 fun app_bnds t i = list_comb (t, map Bound (i - 1 downto 0));
   123 
   124 
   125 (* instantiate induction rule *)
   126 
   127 fun ind_tac ctxt indrule indnames = CSUBGOAL (fn (cgoal, i) =>
   128   let
   129     val goal = Thm.term_of cgoal;
   130     val ts = HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of indrule));
   131     val ts' = HOLogic.dest_conj (HOLogic.dest_Trueprop (Logic.strip_imp_concl goal));
   132     val getP =
   133       if can HOLogic.dest_imp (hd ts)
   134       then apfst SOME o HOLogic.dest_imp
   135       else pair NONE;
   136     val flt =
   137       if null indnames then I
   138       else filter (member (op =) indnames o fst);
   139     fun abstr (t1, t2) =
   140       (case t1 of
   141         NONE =>
   142           (case flt (Term.add_frees t2 []) of
   143             [(s, T)] => SOME (absfree (s, T) t2)
   144           | _ => NONE)
   145       | SOME (_ $ t') => SOME (Abs ("x", fastype_of t', abstract_over (t', t2))));
   146     val insts =
   147       (ts ~~ ts') |> map_filter (fn (t, u) =>
   148         (case abstr (getP u) of
   149           NONE => NONE
   150         | SOME u' => SOME (apply2 (Thm.cterm_of ctxt) (t |> getP |> snd |> head_of, u'))));
   151     val indrule' = cterm_instantiate insts indrule;
   152   in resolve_tac ctxt [indrule'] i end);
   153 
   154 
   155 (* perform exhaustive case analysis on last parameter of subgoal i *)
   156 
   157 fun exh_tac ctxt exh_thm_of = CSUBGOAL (fn (cgoal, i) =>
   158   let
   159     val goal = Thm.term_of cgoal;
   160     val params = Logic.strip_params goal;
   161     val (_, Type (tname, _)) = hd (rev params);
   162     val exhaustion = Thm.lift_rule cgoal (exh_thm_of tname);
   163     val prem' = hd (Thm.prems_of exhaustion);
   164     val _ $ (_ $ lhs $ _) = hd (rev (Logic.strip_assums_hyp prem'));
   165     val exhaustion' =
   166       cterm_instantiate
   167         [apply2 (Thm.cterm_of ctxt)
   168           (head_of lhs, fold_rev (fn (_, T) => fn t => Abs ("z", T, t)) params (Bound 0))]
   169         exhaustion;
   170   in compose_tac ctxt (false, exhaustion', Thm.nprems_of exhaustion) i end);
   171 
   172 
   173 (********************** Internal description of datatypes *********************)
   174 
   175 datatype dtyp =
   176     DtTFree of string * sort
   177   | DtType of string * dtyp list
   178   | DtRec of int;
   179 
   180 (* information about datatypes *)
   181 
   182 (* index, datatype name, type arguments, constructor name, types of constructor's arguments *)
   183 type descr = (int * (string * dtyp list * (string * dtyp list) list)) list;
   184 
   185 type info =
   186   {index : int,
   187    descr : descr,
   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    case_cong_weak : thm,
   200    split : thm,
   201    split_asm: thm};
   202 
   203 type spec = (binding * (string * sort) list * mixfix) * (binding * typ list * mixfix) list;
   204 
   205 fun mk_Free s T i = Free (s ^ string_of_int i, T);
   206 
   207 fun subst_DtTFree _ substs (T as DtTFree a) = the_default T (AList.lookup (op =) substs a)
   208   | subst_DtTFree i substs (DtType (name, ts)) = 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 in
   234         space_implode "_"
   235           (filter_out (equal "") (map name_of_typ Ts) @
   236             [if Symbol_Pos.is_identifier s' then s' else "x"])
   237       end
   238   | name_of_typ _ = "";
   239 
   240 fun dtyp_of_typ _ (TFree a) = DtTFree a
   241   | dtyp_of_typ _ (TVar _) = error "Illegal schematic type variable(s)"
   242   | dtyp_of_typ new_dts (Type (tname, Ts)) =
   243       (case AList.lookup (op =) new_dts tname of
   244         NONE => DtType (tname, map (dtyp_of_typ new_dts) Ts)
   245       | SOME vs =>
   246           if map (try dest_TFree) Ts = map SOME vs then
   247             DtRec (find_index (curry op = tname o fst) new_dts)
   248           else error ("Illegal occurrence of recursive type " ^ quote tname));
   249 
   250 fun typ_of_dtyp descr (DtTFree a) = TFree a
   251   | typ_of_dtyp descr (DtRec i) =
   252       let val (s, ds, _) = the (AList.lookup (op =) descr i)
   253       in Type (s, map (typ_of_dtyp descr) ds) end
   254   | typ_of_dtyp descr (DtType (s, ds)) = Type (s, map (typ_of_dtyp descr) ds);
   255 
   256 (* find all non-recursive types in datatype description *)
   257 
   258 fun get_nonrec_types descr =
   259   map (typ_of_dtyp descr) (fold (fn (_, (_, _, constrs)) =>
   260     fold (fn (_, cargs) => union (op =) (filter_out is_rec_type cargs)) constrs) descr []);
   261 
   262 (* get all recursive types in datatype description *)
   263 
   264 fun get_rec_types descr = map (fn (_ , (s, ds, _)) =>
   265   Type (s, map (typ_of_dtyp descr) ds)) descr;
   266 
   267 (* get all branching types *)
   268 
   269 fun get_branching_types descr =
   270   map (typ_of_dtyp descr)
   271     (fold
   272       (fn (_, (_, _, constrs)) =>
   273         fold (fn (_, cargs) => fold (strip_dtyp #> fst #> fold (insert op =)) cargs) constrs)
   274       descr []);
   275 
   276 fun get_arities descr =
   277   fold
   278     (fn (_, (_, _, constrs)) =>
   279       fold (fn (_, cargs) =>
   280         fold (insert op =) (map (length o fst o strip_dtyp) (filter is_rec_type cargs))) constrs)
   281     descr [];
   282 
   283 (* interpret construction of datatype *)
   284 
   285 fun interpret_construction descr vs {atyp, dtyp} =
   286   let
   287     val typ_of =
   288       typ_of_dtyp descr #>
   289       map_atyps (fn TFree (a, _) => TFree (a, the (AList.lookup (op =) vs a)) | T => T);
   290     fun interpT dT =
   291       (case strip_dtyp dT of
   292         (dTs, DtRec l) =>
   293           let
   294             val (tyco, dTs', _) = the (AList.lookup (op =) descr l);
   295             val Ts = map typ_of dTs;
   296             val Ts' = map typ_of dTs';
   297             val is_proper = forall (can dest_TFree) Ts';
   298           in dtyp Ts (l, is_proper) (tyco, Ts') end
   299       | _ => atyp (typ_of dT));
   300     fun interpC (c, dTs) = (c, map interpT dTs);
   301     fun interpD (_, (tyco, dTs, cs)) = ((tyco, map typ_of dTs), map interpC cs);
   302   in map interpD descr end;
   303 
   304 (* nonemptiness check for datatypes *)
   305 
   306 fun check_nonempty descr =
   307   let
   308     val descr' = flat descr;
   309     fun is_nonempty_dt is i =
   310       let
   311         val (_, _, constrs) = the (AList.lookup (op =) descr' i);
   312         fun arg_nonempty (_, DtRec i) =
   313               if member (op =) is i then false
   314               else is_nonempty_dt (i :: is) i
   315           | arg_nonempty _ = true;
   316       in exists (forall (arg_nonempty o strip_dtyp) o snd) constrs end
   317     val _ = hd descr |> forall (fn (i, (s, _, _)) =>
   318       is_nonempty_dt [i] i orelse raise Datatype_Empty s)
   319   in () end;
   320 
   321 (* unfold a list of mutually recursive datatype specifications *)
   322 (* all types of the form DtType (dt_name, [..., DtRec _, ...]) *)
   323 (* need to be unfolded                                         *)
   324 
   325 fun unfold_datatypes ctxt orig_descr (dt_info : info Symtab.table) descr i =
   326   let
   327     fun typ_error T msg =
   328       error ("Non-admissible type expression\n" ^
   329         Syntax.string_of_typ ctxt (typ_of_dtyp (orig_descr @ descr) T) ^ "\n" ^ msg);
   330 
   331     fun get_dt_descr T i tname dts =
   332       (case Symtab.lookup dt_info tname of
   333         NONE =>
   334           typ_error T (quote tname ^ " is not registered as an old-style datatype and hence cannot \
   335             \be used in nested recursion")
   336       | SOME {index, descr, ...} =>
   337           let
   338             val (_, vars, _) = the (AList.lookup (op =) descr index);
   339             val subst = map dest_DtTFree vars ~~ dts
   340               handle ListPair.UnequalLengths =>
   341                 typ_error T ("Type constructor " ^ quote tname ^
   342                   " used with wrong number of arguments");
   343           in
   344             (i + index,
   345               map (fn (j, (tn, args, cs)) =>
   346                 (i + j, (tn, map (subst_DtTFree i subst) args,
   347                   map (apsnd (map (subst_DtTFree i subst))) cs))) descr)
   348           end);
   349 
   350     (* unfold a single constructor argument *)
   351 
   352     fun unfold_arg T (i, Ts, descrs) =
   353       if is_rec_type T then
   354         let val (Us, U) = strip_dtyp T in
   355           if exists is_rec_type Us then
   356             typ_error T "Non-strictly positive recursive occurrence of type"
   357           else
   358             (case U of
   359               DtType (tname, dts) =>
   360                 let
   361                   val (index, descr) = get_dt_descr T i tname dts;
   362                   val (descr', i') =
   363                     unfold_datatypes ctxt orig_descr dt_info descr (i + length descr);
   364                 in (i', Ts @ [mk_fun_dtyp Us (DtRec index)], descrs @ descr') end
   365             | _ => (i, Ts @ [T], descrs))
   366         end
   367       else (i, Ts @ [T], descrs);
   368 
   369     (* unfold a constructor *)
   370 
   371     fun unfold_constr (cname, cargs) (i, constrs, descrs) =
   372       let val (i', cargs', descrs') = fold unfold_arg cargs (i, [], descrs)
   373       in (i', constrs @ [(cname, cargs')], descrs') end;
   374 
   375     (* unfold a single datatype *)
   376 
   377     fun unfold_datatype (j, (tname, tvars, constrs)) (i, dtypes, descrs) =
   378       let val (i', constrs', descrs') = fold unfold_constr constrs (i, [], descrs)
   379       in (i', dtypes @ [(j, (tname, tvars, constrs'))], descrs') end;
   380 
   381     val (i', descr', descrs) = fold unfold_datatype descr (i, [], []);
   382 
   383   in (descr' :: descrs, i') end;
   384 
   385 (* find shortest path to constructor with no recursive arguments *)
   386 
   387 fun find_nonempty descr is i =
   388   let
   389     fun arg_nonempty (_, DtRec i) =
   390           if member (op =) is i
   391           then NONE
   392           else Option.map (Integer.add 1 o snd) (find_nonempty descr (i :: is) i)
   393       | arg_nonempty _ = SOME 0;
   394     fun max_inf (SOME i) (SOME j) = SOME (Integer.max i j)
   395       | max_inf _ _ = NONE;
   396     fun max xs = fold max_inf xs (SOME 0);
   397     val (_, _, constrs) = the (AList.lookup (op =) descr i);
   398     val xs =
   399       sort (int_ord o apply2 snd)
   400         (map_filter (fn (s, dts) => Option.map (pair s)
   401           (max (map (arg_nonempty o strip_dtyp) dts))) constrs)
   402   in if null xs then NONE else SOME (hd xs) end;
   403 
   404 fun find_shortest_path descr i = find_nonempty descr [i] i;
   405 
   406 end;