src/HOL/Tools/ATP/atp_util.ML
author blanchet
Sun, 17 Jul 2011 14:12:45 +0200
changeset 44734 a43d61270142
parent 44691 62d64709af3b
child 44735 58a7b3fdc193
permissions -rw-r--r--
ensure that the lambda translation procedure is called only once with all the facts, which is necessary for soundness of lambda-lifting (freshness of new names)
     1 (*  Title:      HOL/Tools/ATP/atp_util.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3 
     4 General-purpose functions used by the ATP module.
     5 *)
     6 
     7 signature ATP_UTIL =
     8 sig
     9   val timestamp : unit -> string
    10   val hash_string : string -> int
    11   val hash_term : term -> int
    12   val strip_spaces : bool -> (char -> bool) -> string -> string
    13   val nat_subscript : int -> string
    14   val unyxml : string -> string
    15   val maybe_quote : string -> string
    16   val string_from_ext_time : bool * Time.time -> string
    17   val string_from_time : Time.time -> string
    18   val varify_type : Proof.context -> typ -> typ
    19   val instantiate_type : theory -> typ -> typ -> typ -> typ
    20   val varify_and_instantiate_type : Proof.context -> typ -> typ -> typ -> typ
    21   val typ_of_dtyp :
    22     Datatype_Aux.descr -> (Datatype_Aux.dtyp * typ) list -> Datatype_Aux.dtyp
    23     -> typ
    24   val is_type_surely_finite : Proof.context -> bool -> typ -> bool
    25   val is_type_surely_infinite : Proof.context -> bool -> typ -> bool
    26   val s_not : term -> term
    27   val s_conj : term * term -> term
    28   val s_disj : term * term -> term
    29   val s_imp : term * term -> term
    30   val s_iff : term * term -> term
    31   val monomorphic_term : Type.tyenv -> term -> term
    32   val eta_expand : typ list -> term -> int -> term
    33   val transform_elim_prop : term -> term
    34   val specialize_type : theory -> (string * typ) -> term -> term
    35   val strip_subgoal :
    36     Proof.context -> thm -> int -> (string * typ) list * term list * term
    37 end;
    38 
    39 structure ATP_Util : ATP_UTIL =
    40 struct
    41 
    42 val timestamp = Date.fmt "%Y-%m-%d %H:%M:%S" o Date.fromTimeLocal o Time.now
    43 
    44 (* This hash function is recommended in "Compilers: Principles, Techniques, and
    45    Tools" by Aho, Sethi, and Ullman. The "hashpjw" function, which they
    46    particularly recommend, triggers a bug in versions of Poly/ML up to 4.2.0. *)
    47 fun hashw (u, w) = Word.+ (u, Word.* (0w65599, w))
    48 fun hashw_char (c, w) = hashw (Word.fromInt (Char.ord c), w)
    49 fun hashw_string (s : string, w) = CharVector.foldl hashw_char w s
    50 fun hashw_term (t1 $ t2) = hashw (hashw_term t1, hashw_term t2)
    51   | hashw_term (Const (s, _)) = hashw_string (s, 0w0)
    52   | hashw_term (Free (s, _)) = hashw_string (s, 0w0)
    53   | hashw_term _ = 0w0
    54 
    55 fun hash_string s = Word.toInt (hashw_string (s, 0w0))
    56 val hash_term = Word.toInt o hashw_term
    57 
    58 fun strip_c_style_comment _ [] = []
    59   | strip_c_style_comment is_evil (#"*" :: #"/" :: cs) =
    60     strip_spaces_in_list true is_evil cs
    61   | strip_c_style_comment is_evil (_ :: cs) = strip_c_style_comment is_evil cs
    62 and strip_spaces_in_list _ _ [] = []
    63   | strip_spaces_in_list true is_evil (#"%" :: cs) =
    64     strip_spaces_in_list true is_evil
    65                          (cs |> chop_while (not_equal #"\n") |> snd)
    66   | strip_spaces_in_list true is_evil (#"/" :: #"*" :: cs) =
    67     strip_c_style_comment is_evil cs
    68   | strip_spaces_in_list _ _ [c1] = if Char.isSpace c1 then [] else [str c1]
    69   | strip_spaces_in_list skip_comments is_evil [c1, c2] =
    70     strip_spaces_in_list skip_comments is_evil [c1] @
    71     strip_spaces_in_list skip_comments is_evil [c2]
    72   | strip_spaces_in_list skip_comments is_evil (c1 :: c2 :: c3 :: cs) =
    73     if Char.isSpace c1 then
    74       strip_spaces_in_list skip_comments is_evil (c2 :: c3 :: cs)
    75     else if Char.isSpace c2 then
    76       if Char.isSpace c3 then
    77         strip_spaces_in_list skip_comments is_evil (c1 :: c3 :: cs)
    78       else
    79         str c1 :: (if forall is_evil [c1, c3] then [" "] else []) @
    80         strip_spaces_in_list skip_comments is_evil (c3 :: cs)
    81     else
    82       str c1 :: strip_spaces_in_list skip_comments is_evil (c2 :: c3 :: cs)
    83 fun strip_spaces skip_comments is_evil =
    84   implode o strip_spaces_in_list skip_comments is_evil o String.explode
    85 
    86 val subscript = implode o map (prefix "\<^isub>") o raw_explode  (* FIXME Symbol.explode (?) *)
    87 fun nat_subscript n =
    88   n |> string_of_int |> print_mode_active Symbol.xsymbolsN ? subscript
    89 
    90 val unyxml = XML.content_of o YXML.parse_body
    91 
    92 val is_long_identifier = forall Lexicon.is_identifier o space_explode "."
    93 fun maybe_quote y =
    94   let val s = unyxml y in
    95     y |> ((not (is_long_identifier (perhaps (try (unprefix "'")) s)) andalso
    96            not (is_long_identifier (perhaps (try (unprefix "?")) s))) orelse
    97            Keyword.is_keyword s) ? quote
    98   end
    99 
   100 fun string_from_ext_time (plus, time) =
   101   let val ms = Time.toMilliseconds time in
   102     (if plus then "> " else "") ^
   103     (if plus andalso ms mod 1000 = 0 then
   104        signed_string_of_int (ms div 1000) ^ " s"
   105      else if ms < 1000 then
   106        signed_string_of_int ms ^ " ms"
   107      else
   108        string_of_real (0.01 * Real.fromInt (ms div 10)) ^ " s")
   109   end
   110 
   111 val string_from_time = string_from_ext_time o pair false
   112 
   113 fun varify_type ctxt T =
   114   Variable.polymorphic_types ctxt [Const (@{const_name undefined}, T)]
   115   |> snd |> the_single |> dest_Const |> snd
   116 
   117 (* TODO: use "Term_Subst.instantiateT" instead? *)
   118 fun instantiate_type thy T1 T1' T2 =
   119   Same.commit (Envir.subst_type_same
   120                    (Sign.typ_match thy (T1, T1') Vartab.empty)) T2
   121   handle Type.TYPE_MATCH => raise TYPE ("instantiate_type", [T1, T1'], [])
   122 
   123 fun varify_and_instantiate_type ctxt T1 T1' T2 =
   124   let val thy = Proof_Context.theory_of ctxt in
   125     instantiate_type thy (varify_type ctxt T1) T1' (varify_type ctxt T2)
   126   end
   127 
   128 fun typ_of_dtyp _ typ_assoc (Datatype_Aux.DtTFree a) =
   129     the (AList.lookup (op =) typ_assoc (Datatype_Aux.DtTFree a))
   130   | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtType (s, Us)) =
   131     Type (s, map (typ_of_dtyp descr typ_assoc) Us)
   132   | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtRec i) =
   133     let val (s, ds, _) = the (AList.lookup (op =) descr i) in
   134       Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   135     end
   136 
   137 fun datatype_constrs thy (T as Type (s, Ts)) =
   138     (case Datatype.get_info thy s of
   139        SOME {index, descr, ...} =>
   140        let val (_, dtyps, constrs) = AList.lookup (op =) descr index |> the in
   141          map (apsnd (fn Us => map (typ_of_dtyp descr (dtyps ~~ Ts)) Us ---> T))
   142              constrs
   143        end
   144      | NONE => [])
   145   | datatype_constrs _ _ = []
   146 
   147 (* Similar to "Nitpick_HOL.bounded_exact_card_of_type".
   148    0 means infinite type, 1 means singleton type (e.g., "unit"), and 2 means
   149    cardinality 2 or more. The specified default cardinality is returned if the
   150    cardinality of the type can't be determined. *)
   151 fun tiny_card_of_type ctxt sound default_card T =
   152   let
   153     val thy = Proof_Context.theory_of ctxt
   154     val max = 2 (* 1 would be too small for the "fun" case *)
   155     fun aux slack avoid T =
   156       if member (op =) avoid T then
   157         0
   158       else case T of
   159         Type (@{type_name fun}, [T1, T2]) =>
   160         (case (aux slack avoid T1, aux slack avoid T2) of
   161            (k, 1) => if slack andalso k = 0 then 0 else 1
   162          | (0, _) => 0
   163          | (_, 0) => 0
   164          | (k1, k2) =>
   165            if k1 >= max orelse k2 >= max then max
   166            else Int.min (max, Integer.pow k2 k1))
   167       | @{typ prop} => 2
   168       | @{typ bool} => 2 (* optimization *)
   169       | @{typ nat} => 0 (* optimization *)
   170       | Type ("Int.int", []) => 0 (* optimization *)
   171       | Type (s, _) =>
   172         (case datatype_constrs thy T of
   173            constrs as _ :: _ =>
   174            let
   175              val constr_cards =
   176                map (Integer.prod o map (aux slack (T :: avoid)) o binder_types
   177                     o snd) constrs
   178            in
   179              if exists (curry (op =) 0) constr_cards then 0
   180              else Int.min (max, Integer.sum constr_cards)
   181            end
   182          | [] =>
   183            case Typedef.get_info ctxt s of
   184              ({abs_type, rep_type, ...}, _) :: _ =>
   185              (* We cheat here by assuming that typedef types are infinite if
   186                 their underlying type is infinite. This is unsound in general
   187                 but it's hard to think of a realistic example where this would
   188                 not be the case. We are also slack with representation types:
   189                 If a representation type has the form "sigma => tau", we
   190                 consider it enough to check "sigma" for infiniteness. (Look
   191                 for "slack" in this function.) *)
   192              (case varify_and_instantiate_type ctxt
   193                        (Logic.varifyT_global abs_type) T
   194                        (Logic.varifyT_global rep_type)
   195                    |> aux true avoid of
   196                 0 => if sound then default_card else 0
   197               | 1 => 1
   198               | _ => default_card)
   199            | [] => default_card)
   200         (* Very slightly unsound: Type variables are assumed not to be
   201            constrained to cardinality 1. (In practice, the user would most
   202            likely have used "unit" directly anyway.) *)
   203       | TFree _ =>
   204         if default_card = 1 andalso not sound then 2 else default_card
   205       | TVar _ => default_card
   206   in Int.min (max, aux false [] T) end
   207 
   208 fun is_type_surely_finite ctxt sound T = tiny_card_of_type ctxt sound 0 T <> 0
   209 fun is_type_surely_infinite ctxt sound T = tiny_card_of_type ctxt sound 1 T = 0
   210 
   211 (* Simple simplifications to ensure that sort annotations don't leave a trail of
   212    spurious "True"s. *)
   213 fun s_not (Const (@{const_name All}, T) $ Abs (s, T', t')) =
   214     Const (@{const_name Ex}, T) $ Abs (s, T', s_not t')
   215   | s_not (Const (@{const_name Ex}, T) $ Abs (s, T', t')) =
   216     Const (@{const_name All}, T) $ Abs (s, T', s_not t')
   217   | s_not (@{const HOL.implies} $ t1 $ t2) = @{const HOL.conj} $ t1 $ s_not t2
   218   | s_not (@{const HOL.conj} $ t1 $ t2) =
   219     @{const HOL.disj} $ s_not t1 $ s_not t2
   220   | s_not (@{const HOL.disj} $ t1 $ t2) =
   221     @{const HOL.conj} $ s_not t1 $ s_not t2
   222   | s_not (@{const False}) = @{const True}
   223   | s_not (@{const True}) = @{const False}
   224   | s_not (@{const Not} $ t) = t
   225   | s_not t = @{const Not} $ t
   226 fun s_conj (@{const True}, t2) = t2
   227   | s_conj (t1, @{const True}) = t1
   228   | s_conj p = HOLogic.mk_conj p
   229 fun s_disj (@{const False}, t2) = t2
   230   | s_disj (t1, @{const False}) = t1
   231   | s_disj p = HOLogic.mk_disj p
   232 fun s_imp (@{const True}, t2) = t2
   233   | s_imp (t1, @{const False}) = s_not t1
   234   | s_imp p = HOLogic.mk_imp p
   235 fun s_iff (@{const True}, t2) = t2
   236   | s_iff (t1, @{const True}) = t1
   237   | s_iff (t1, t2) = HOLogic.eq_const HOLogic.boolT $ t1 $ t2
   238 
   239 fun monomorphic_term subst =
   240   map_types (map_type_tvar (fn v =>
   241       case Type.lookup subst v of
   242         SOME typ => typ
   243       | NONE => TVar v))
   244 
   245 fun eta_expand _ t 0 = t
   246   | eta_expand Ts (Abs (s, T, t')) n =
   247     Abs (s, T, eta_expand (T :: Ts) t' (n - 1))
   248   | eta_expand Ts t n =
   249     fold_rev (fn T => fn t' => Abs ("x" ^ nat_subscript n, T, t'))
   250              (List.take (binder_types (fastype_of1 (Ts, t)), n))
   251              (list_comb (incr_boundvars n t, map Bound (n - 1 downto 0)))
   252 
   253 (* Converts an elim-rule into an equivalent theorem that does not have the
   254    predicate variable. Leaves other theorems unchanged. We simply instantiate
   255    the conclusion variable to False. (Cf. "transform_elim_theorem" in
   256    "Meson_Clausify".) *)
   257 fun transform_elim_prop t =
   258   case Logic.strip_imp_concl t of
   259     @{const Trueprop} $ Var (z, @{typ bool}) =>
   260     subst_Vars [(z, @{const False})] t
   261   | Var (z, @{typ prop}) => subst_Vars [(z, @{prop False})] t
   262   | _ => t
   263 
   264 fun specialize_type thy (s, T) t =
   265   let
   266     fun subst_for (Const (s', T')) =
   267       if s = s' then
   268         SOME (Sign.typ_match thy (T', T) Vartab.empty)
   269         handle Type.TYPE_MATCH => NONE
   270       else
   271         NONE
   272     | subst_for (t1 $ t2) =
   273       (case subst_for t1 of SOME x => SOME x | NONE => subst_for t2)
   274     | subst_for (Abs (_, _, t')) = subst_for t'
   275     | subst_for _ = NONE
   276   in
   277     case subst_for t of
   278       SOME subst => monomorphic_term subst t
   279     | NONE => raise Type.TYPE_MATCH
   280   end
   281 
   282 fun strip_subgoal ctxt goal i =
   283   let
   284     val (t, (frees, params)) =
   285       Logic.goal_params (prop_of goal) i
   286       ||> (map dest_Free #> Variable.variant_frees ctxt [] #> `(map Free))
   287     val hyp_ts = t |> Logic.strip_assums_hyp |> map (curry subst_bounds frees)
   288     val concl_t = t |> Logic.strip_assums_concl |> curry subst_bounds frees
   289   in (rev params, hyp_ts, concl_t) end
   290 
   291 end;