src/HOL/Tools/Sledgehammer/sledgehammer_fol_clause.ML
author blanchet
Tue Jun 22 16:23:29 2010 +0200 (2010-06-22 ago)
changeset 37500 7587b6e63454
parent 37498 b426cbdb5a23
child 37509 f39464d971c4
permissions -rw-r--r--
thread original theorem along with CNF theorem, as a step toward killing the Skolem cache
     1 (*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fol_clause.ML
     2     Author:     Jia Meng, Cambridge University Computer Laboratory
     3     Author:     Jasmin Blanchette, TU Muenchen
     4 
     5 Storing/printing FOL clauses and arity clauses.  Typed equality is
     6 treated differently.
     7 
     8 FIXME: combine with sledgehammer_hol_clause!
     9 *)
    10 
    11 signature SLEDGEHAMMER_FOL_CLAUSE =
    12 sig
    13   val schematic_var_prefix: string
    14   val fixed_var_prefix: string
    15   val tvar_prefix: string
    16   val tfree_prefix: string
    17   val clause_prefix: string
    18   val const_prefix: string
    19   val tconst_prefix: string
    20   val class_prefix: string
    21   val union_all: ''a list list -> ''a list
    22   val const_trans_table: string Symtab.table
    23   val type_const_trans_table: string Symtab.table
    24   val ascii_of: string -> string
    25   val undo_ascii_of: string -> string
    26   val paren_pack : string list -> string
    27   val make_schematic_var : string * int -> string
    28   val make_fixed_var : string -> string
    29   val make_schematic_type_var : string * int -> string
    30   val make_fixed_type_var : string -> string
    31   val make_fixed_const : string -> string
    32   val make_fixed_type_const : string -> string
    33   val make_type_class : string -> string
    34   type name = string * string
    35   type name_pool = string Symtab.table * string Symtab.table
    36   val empty_name_pool : bool -> name_pool option
    37   val pool_map : ('a -> 'b -> 'c * 'b) -> 'a list -> 'b -> 'c list * 'b
    38   val nice_name : name -> name_pool option -> string * name_pool option
    39   datatype kind = Axiom | Conjecture
    40   datatype fol_type =
    41     TyVar of name |
    42     TyFree of name |
    43     TyConstr of name * fol_type list
    44   val string_of_fol_type :
    45     fol_type -> name_pool option -> string * name_pool option
    46   datatype type_literal =
    47     TyLitVar of string * name |
    48     TyLitFree of string * name
    49   exception CLAUSE of string * term
    50   val type_literals_for_types : typ list -> type_literal list
    51   datatype arLit =
    52       TConsLit of class * string * string list
    53     | TVarLit of class * string
    54   datatype arity_clause = ArityClause of
    55    {axiom_name: string, conclLit: arLit, premLits: arLit list}
    56   datatype classrel_clause = ClassrelClause of
    57    {axiom_name: string, subclass: class, superclass: class}
    58   val make_classrel_clauses: theory -> class list -> class list -> classrel_clause list
    59   val make_arity_clauses: theory -> string list -> class list -> class list * arity_clause list
    60   val tptp_sign: bool -> string -> string
    61   val tptp_of_type_literal :
    62     bool -> type_literal -> name_pool option -> string * name_pool option
    63   val gen_tptp_cls : int * string * kind * string list * string list -> string
    64   val tptp_tfree_clause : string -> string
    65   val tptp_arity_clause : arity_clause -> string
    66   val tptp_classrel_clause : classrel_clause -> string
    67 end
    68 
    69 structure Sledgehammer_FOL_Clause : SLEDGEHAMMER_FOL_CLAUSE =
    70 struct
    71 
    72 open Sledgehammer_Util
    73 
    74 val schematic_var_prefix = "V_";
    75 val fixed_var_prefix = "v_";
    76 
    77 val tvar_prefix = "T_";
    78 val tfree_prefix = "t_";
    79 
    80 val clause_prefix = "cls_";
    81 val arclause_prefix = "clsarity_"
    82 val clrelclause_prefix = "clsrel_";
    83 
    84 val const_prefix = "c_";
    85 val tconst_prefix = "tc_";
    86 val class_prefix = "class_";
    87 
    88 fun union_all xss = fold (union (op =)) xss []
    89 
    90 (* Readable names for the more common symbolic functions. Do not mess with the
    91    last nine entries of the table unless you know what you are doing. *)
    92 val const_trans_table =
    93   Symtab.make [(@{const_name "op ="}, "equal"),
    94                (@{const_name "op &"}, "and"),
    95                (@{const_name "op |"}, "or"),
    96                (@{const_name "op -->"}, "implies"),
    97                (@{const_name "op :"}, "in"),
    98                (@{const_name fequal}, "fequal"),
    99                (@{const_name COMBI}, "COMBI"),
   100                (@{const_name COMBK}, "COMBK"),
   101                (@{const_name COMBB}, "COMBB"),
   102                (@{const_name COMBC}, "COMBC"),
   103                (@{const_name COMBS}, "COMBS"),
   104                (@{const_name True}, "True"),
   105                (@{const_name False}, "False"),
   106                (@{const_name If}, "If")]
   107 
   108 val type_const_trans_table =
   109   Symtab.make [(@{type_name "*"}, "prod"),
   110                (@{type_name "+"}, "sum")]
   111 
   112 (*Escaping of special characters.
   113   Alphanumeric characters are left unchanged.
   114   The character _ goes to __
   115   Characters in the range ASCII space to / go to _A to _P, respectively.
   116   Other printing characters go to _nnn where nnn is the decimal ASCII code.*)
   117 val A_minus_space = Char.ord #"A" - Char.ord #" ";
   118 
   119 fun stringN_of_int 0 _ = ""
   120   | stringN_of_int k n = stringN_of_int (k-1) (n div 10) ^ Int.toString (n mod 10);
   121 
   122 fun ascii_of_c c =
   123   if Char.isAlphaNum c then String.str c
   124   else if c = #"_" then "__"
   125   else if #" " <= c andalso c <= #"/"
   126        then "_" ^ String.str (Char.chr (Char.ord c + A_minus_space))
   127   else if Char.isPrint c
   128        then ("_" ^ stringN_of_int 3 (Char.ord c))  (*fixed width, in case more digits follow*)
   129   else ""
   130 
   131 val ascii_of = String.translate ascii_of_c;
   132 
   133 (** Remove ASCII armouring from names in proof files **)
   134 
   135 (*We don't raise error exceptions because this code can run inside the watcher.
   136   Also, the errors are "impossible" (hah!)*)
   137 fun undo_ascii_aux rcs [] = String.implode(rev rcs)
   138   | undo_ascii_aux rcs [#"_"] = undo_ascii_aux (#"_"::rcs) []  (*ERROR*)
   139       (*Three types of _ escapes: __, _A to _P, _nnn*)
   140   | undo_ascii_aux rcs (#"_" :: #"_" :: cs) = undo_ascii_aux (#"_"::rcs) cs
   141   | undo_ascii_aux rcs (#"_" :: c :: cs) =
   142       if #"A" <= c andalso c<= #"P"  (*translation of #" " to #"/"*)
   143       then undo_ascii_aux (Char.chr(Char.ord c - A_minus_space) :: rcs) cs
   144       else
   145         let val digits = List.take (c::cs, 3) handle Subscript => []
   146         in
   147             case Int.fromString (String.implode digits) of
   148                 NONE => undo_ascii_aux (c:: #"_"::rcs) cs  (*ERROR*)
   149               | SOME n => undo_ascii_aux (Char.chr n :: rcs) (List.drop (cs, 2))
   150         end
   151   | undo_ascii_aux rcs (c::cs) = undo_ascii_aux (c::rcs) cs;
   152 
   153 val undo_ascii_of = undo_ascii_aux [] o String.explode;
   154 
   155 (* convert a list of strings into one single string; surrounded by brackets *)
   156 fun paren_pack [] = ""   (*empty argument list*)
   157   | paren_pack strings = "(" ^ commas strings ^ ")";
   158 
   159 fun tptp_clause strings = "(" ^ space_implode " | " strings ^ ")"
   160 
   161 (*Remove the initial ' character from a type variable, if it is present*)
   162 fun trim_type_var s =
   163   if s <> "" andalso String.sub(s,0) = #"'" then String.extract(s,1,NONE)
   164   else error ("trim_type: Malformed type variable encountered: " ^ s);
   165 
   166 fun ascii_of_indexname (v,0) = ascii_of v
   167   | ascii_of_indexname (v,i) = ascii_of v ^ "_" ^ Int.toString i;
   168 
   169 fun make_schematic_var v = schematic_var_prefix ^ (ascii_of_indexname v);
   170 fun make_fixed_var x = fixed_var_prefix ^ (ascii_of x);
   171 
   172 fun make_schematic_type_var (x,i) =
   173       tvar_prefix ^ (ascii_of_indexname (trim_type_var x,i));
   174 fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (trim_type_var x));
   175 
   176 fun lookup_const c =
   177   case Symtab.lookup const_trans_table c of
   178     SOME c' => c'
   179   | NONE => ascii_of c
   180 
   181 fun lookup_type_const c =
   182   case Symtab.lookup type_const_trans_table c of
   183     SOME c' => c'
   184   | NONE => ascii_of c
   185 
   186 (* "op =" MUST BE "equal" because it's built into ATPs. *)
   187 fun make_fixed_const @{const_name "op ="} = "equal"
   188   | make_fixed_const c = const_prefix ^ lookup_const c
   189 
   190 fun make_fixed_type_const c = tconst_prefix ^ lookup_type_const c
   191 
   192 fun make_type_class clas = class_prefix ^ ascii_of clas;
   193 
   194 
   195 (**** name pool ****)
   196  
   197 type name = string * string
   198 type name_pool = string Symtab.table * string Symtab.table
   199 
   200 fun empty_name_pool readable_names =
   201   if readable_names then SOME (`I Symtab.empty) else NONE
   202 
   203 fun pool_fold f xs z = pair z #> fold_rev (fn x => uncurry (f x)) xs
   204 fun pool_map f xs =
   205   pool_fold (fn x => fn ys => fn pool => f x pool |>> (fn y => y :: ys)) xs []
   206 
   207 fun add_nice_name full_name nice_prefix j the_pool =
   208   let
   209     val nice_name = nice_prefix ^ (if j = 0 then "" else "_" ^ Int.toString j)
   210   in
   211     case Symtab.lookup (snd the_pool) nice_name of
   212       SOME full_name' =>
   213       if full_name = full_name' then (nice_name, the_pool)
   214       else add_nice_name full_name nice_prefix (j + 1) the_pool
   215     | NONE =>
   216       (nice_name, (Symtab.update_new (full_name, nice_name) (fst the_pool),
   217                    Symtab.update_new (nice_name, full_name) (snd the_pool)))
   218   end
   219 
   220 fun translate_first_char f s =
   221   String.str (f (String.sub (s, 0))) ^ String.extract (s, 1, NONE)
   222 
   223 fun readable_name full_name s =
   224   let
   225     val s = s |> Long_Name.base_name
   226               |> fold remove_all ["\<^sub>", "\<^bsub>", "\<^esub>", "\<^isub>"]
   227     val s' = s |> explode |> rev |> dropwhile (curry (op =) "'")
   228     val s' =
   229       (s' |> rev
   230           |> implode
   231           |> String.translate
   232                  (fn c => if Char.isAlphaNum c orelse c = #"_" then String.str c
   233                           else ""))
   234       ^ replicate_string (String.size s - length s') "_"
   235     val s' =
   236       if s' = "" orelse not (Char.isAlpha (String.sub (s', 0))) then "X" ^ s'
   237       else s'
   238     (* Avoid "equal", since it's built into ATPs; and "op" is very ambiguous
   239        ("op &", "op |", etc.). *)
   240     val s' = if s' = "equal" orelse s' = "op" then full_name else s'
   241   in
   242     case (Char.isLower (String.sub (full_name, 0)),
   243           Char.isLower (String.sub (s', 0))) of
   244       (true, false) => translate_first_char Char.toLower s'
   245     | (false, true) => translate_first_char Char.toUpper s'
   246     | _ => s'
   247   end
   248 
   249 fun nice_name (full_name, _) NONE = (full_name, NONE)
   250   | nice_name (full_name, desired_name) (SOME the_pool) =
   251     case Symtab.lookup (fst the_pool) full_name of
   252       SOME nice_name => (nice_name, SOME the_pool)
   253     | NONE => add_nice_name full_name (readable_name full_name desired_name) 0
   254                             the_pool
   255               |> apsnd SOME
   256 
   257 (**** Definitions and functions for FOL clauses for TPTP format output ****)
   258 
   259 datatype kind = Axiom | Conjecture;
   260 
   261 (**** Isabelle FOL clauses ****)
   262 
   263 datatype fol_type =
   264   TyVar of name |
   265   TyFree of name |
   266   TyConstr of name * fol_type list
   267 
   268 fun string_of_fol_type (TyVar sp) pool = nice_name sp pool
   269   | string_of_fol_type (TyFree sp) pool = nice_name sp pool
   270   | string_of_fol_type (TyConstr (sp, tys)) pool =
   271     let
   272       val (s, pool) = nice_name sp pool
   273       val (ss, pool) = pool_map string_of_fol_type tys pool
   274     in (s ^ paren_pack ss, pool) end
   275 
   276 (* The first component is the type class; the second is a TVar or TFree. *)
   277 datatype type_literal =
   278   TyLitVar of string * name |
   279   TyLitFree of string * name
   280 
   281 exception CLAUSE of string * term;
   282 
   283 (*Make literals for sorted type variables*)
   284 fun sorts_on_typs_aux (_, [])   = []
   285   | sorts_on_typs_aux ((x,i),  s::ss) =
   286       let val sorts = sorts_on_typs_aux ((x,i), ss)
   287       in
   288           if s = "HOL.type" then sorts
   289           else if i = ~1 then TyLitFree (make_type_class s, `make_fixed_type_var x) :: sorts
   290           else TyLitVar (make_type_class s, (make_schematic_type_var (x,i), x)) :: sorts
   291       end;
   292 
   293 fun sorts_on_typs (TFree (a,s)) = sorts_on_typs_aux ((a,~1),s)
   294   | sorts_on_typs (TVar (v,s))  = sorts_on_typs_aux (v,s);
   295 
   296 (*Given a list of sorted type variables, return a list of type literals.*)
   297 fun type_literals_for_types Ts =
   298   fold (union (op =)) (map sorts_on_typs Ts) []
   299 
   300 (** make axiom and conjecture clauses. **)
   301 
   302 (**** Isabelle arities ****)
   303 
   304 datatype arLit = TConsLit of class * string * string list
   305                | TVarLit of class * string;
   306 
   307 datatype arity_clause =
   308   ArityClause of {axiom_name: string, conclLit: arLit, premLits: arLit list}
   309 
   310 
   311 fun gen_TVars 0 = []
   312   | gen_TVars n = ("T_" ^ Int.toString n) :: gen_TVars (n-1);
   313 
   314 fun pack_sort(_,[])  = []
   315   | pack_sort(tvar, "HOL.type"::srt) = pack_sort(tvar, srt)   (*IGNORE sort "type"*)
   316   | pack_sort(tvar, cls::srt) =  (cls, tvar) :: pack_sort(tvar, srt);
   317 
   318 (*Arity of type constructor tcon :: (arg1,...,argN)res*)
   319 fun make_axiom_arity_clause (tcons, axiom_name, (cls,args)) =
   320    let val tvars = gen_TVars (length args)
   321        val tvars_srts = ListPair.zip (tvars,args)
   322    in
   323      ArityClause {axiom_name = axiom_name, 
   324                   conclLit = TConsLit (cls, make_fixed_type_const tcons, tvars),
   325                   premLits = map TVarLit (union_all(map pack_sort tvars_srts))}
   326    end;
   327 
   328 
   329 (**** Isabelle class relations ****)
   330 
   331 datatype classrel_clause =
   332   ClassrelClause of {axiom_name: string, subclass: class, superclass: class}
   333 
   334 (*Generate all pairs (sub,super) such that sub is a proper subclass of super in theory thy.*)
   335 fun class_pairs _ [] _ = []
   336   | class_pairs thy subs supers =
   337       let
   338         val class_less = Sorts.class_less (Sign.classes_of thy)
   339         fun add_super sub super = class_less (sub, super) ? cons (sub, super)
   340         fun add_supers sub = fold (add_super sub) supers
   341       in fold add_supers subs [] end
   342 
   343 fun make_classrel_clause (sub,super) =
   344   ClassrelClause {axiom_name = clrelclause_prefix ^ ascii_of sub ^ "_" ^ ascii_of super,
   345                   subclass = make_type_class sub,
   346                   superclass = make_type_class super};
   347 
   348 fun make_classrel_clauses thy subs supers =
   349   map make_classrel_clause (class_pairs thy subs supers);
   350 
   351 
   352 (** Isabelle arities **)
   353 
   354 fun arity_clause _ _ (_, []) = []
   355   | arity_clause seen n (tcons, ("HOL.type",_)::ars) =  (*ignore*)
   356       arity_clause seen n (tcons,ars)
   357   | arity_clause seen n (tcons, (ar as (class,_)) :: ars) =
   358       if member (op =) seen class then (*multiple arities for the same tycon, class pair*)
   359           make_axiom_arity_clause (tcons, lookup_type_const tcons ^ "_" ^ class ^ "_" ^ Int.toString n, ar) ::
   360           arity_clause seen (n+1) (tcons,ars)
   361       else
   362           make_axiom_arity_clause (tcons, lookup_type_const tcons ^ "_" ^ class, ar) ::
   363           arity_clause (class::seen) n (tcons,ars)
   364 
   365 fun multi_arity_clause [] = []
   366   | multi_arity_clause ((tcons, ars) :: tc_arlists) =
   367       arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
   368 
   369 (*Generate all pairs (tycon,class,sorts) such that tycon belongs to class in theory thy
   370   provided its arguments have the corresponding sorts.*)
   371 fun type_class_pairs thy tycons classes =
   372   let val alg = Sign.classes_of thy
   373       fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
   374       fun add_class tycon class =
   375         cons (class, domain_sorts tycon class)
   376         handle Sorts.CLASS_ERROR _ => I
   377       fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
   378   in  map try_classes tycons  end;
   379 
   380 (*Proving one (tycon, class) membership may require proving others, so iterate.*)
   381 fun iter_type_class_pairs _ _ [] = ([], [])
   382   | iter_type_class_pairs thy tycons classes =
   383       let val cpairs = type_class_pairs thy tycons classes
   384           val newclasses = union_all (union_all (union_all (map (map #2 o #2) cpairs)))
   385             |> subtract (op =) classes |> subtract (op =) HOLogic.typeS
   386           val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
   387       in (union (op =) classes' classes, union (op =) cpairs' cpairs) end;
   388 
   389 fun make_arity_clauses thy tycons classes =
   390   let val (classes', cpairs) = iter_type_class_pairs thy tycons classes
   391   in  (classes', multi_arity_clause cpairs)  end;
   392 
   393 
   394 (**** Produce TPTP files ****)
   395 
   396 fun string_of_clausename (cls_id, ax_name) =
   397     clause_prefix ^ ascii_of ax_name ^ "_" ^ Int.toString cls_id
   398 
   399 fun tptp_sign true s = s
   400   | tptp_sign false s = "~ " ^ s
   401 
   402 fun tptp_of_type_literal pos (TyLitVar (s, name)) =
   403     nice_name name #>> (fn s' => tptp_sign pos (s ^ "(" ^ s' ^ ")"))
   404   | tptp_of_type_literal pos (TyLitFree (s, name)) =
   405     nice_name name #>> (fn s' => tptp_sign pos (s ^ "(" ^ s' ^ ")"))
   406 
   407 fun tptp_cnf name kind formula =
   408   "cnf(" ^ name ^ ", " ^ kind ^ ",\n    " ^ formula ^ ").\n"
   409 
   410 fun gen_tptp_cls (cls_id, ax_name, Axiom, lits, tylits) =
   411       tptp_cnf (string_of_clausename (cls_id, ax_name)) "axiom"
   412                (tptp_clause (tylits @ lits))
   413   | gen_tptp_cls (cls_id, ax_name, Conjecture, lits, _) =
   414       tptp_cnf (string_of_clausename (cls_id, ax_name)) "negated_conjecture"
   415                (tptp_clause lits)
   416 
   417 fun tptp_tfree_clause tfree_lit =
   418     tptp_cnf "tfree_tcs" "negated_conjecture" (tptp_clause [tfree_lit])
   419 
   420 fun tptp_of_arLit (TConsLit (c,t,args)) =
   421       tptp_sign true (make_type_class c ^ "(" ^ t ^ paren_pack args ^ ")")
   422   | tptp_of_arLit (TVarLit (c,str)) =
   423       tptp_sign false (make_type_class c ^ "(" ^ str ^ ")")
   424 
   425 fun tptp_arity_clause (ArityClause {axiom_name, conclLit, premLits, ...}) =
   426   tptp_cnf (arclause_prefix ^ ascii_of axiom_name) "axiom"
   427            (tptp_clause (map tptp_of_arLit (conclLit :: premLits)))
   428 
   429 fun tptp_classrelLits sub sup =
   430   let val tvar = "(T)"
   431   in  tptp_clause [tptp_sign false (sub^tvar), tptp_sign true (sup^tvar)]  end;
   432 
   433 fun tptp_classrel_clause (ClassrelClause {axiom_name, subclass, superclass,
   434                                           ...}) =
   435   tptp_cnf axiom_name "axiom" (tptp_classrelLits subclass superclass)
   436 
   437 end;