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