src/HOL/Tools/res_atp.ML
author wenzelm
Thu May 11 19:19:31 2006 +0200 (2006-05-11 ago)
changeset 19617 7cb4b67d4b97
parent 19490 bf7f8347174a
child 19641 f1de44e61ec1
permissions -rw-r--r--
avoid raw equality on type thm;
     1 (*  Author: Jia Meng, Cambridge University Computer Laboratory, NICTA
     2     ID: $Id$
     3     Copyright 2004 University of Cambridge
     4 
     5 ATPs with TPTP format input.
     6 *)
     7 
     8 signature RES_ATP =
     9 sig
    10   val prover: string ref
    11   val custom_spass: string list ref
    12   val destdir: string ref
    13   val helper_path: string -> string -> string
    14   val problem_name: string ref
    15   val time_limit: int ref
    16    
    17   datatype mode = Auto | Fol | Hol
    18   val linkup_logic_mode : mode ref
    19   val write_subgoal_file: mode -> Proof.context -> thm list -> thm list -> int -> string
    20   val vampire_time: int ref
    21   val eprover_time: int ref
    22   val run_vampire: int -> unit
    23   val run_eprover: int -> unit
    24   val vampireLimit: unit -> int
    25   val eproverLimit: unit -> int
    26   val atp_method: (ProofContext.context -> thm list -> int -> Tactical.tactic) ->
    27 		  Method.src -> ProofContext.context -> Method.method
    28   val cond_rm_tmp: string -> unit
    29   val keep_atp_input: bool ref
    30   val fol_keep_types: bool ref
    31   val hol_full_types: unit -> unit
    32   val hol_partial_types: unit -> unit
    33   val hol_const_types_only: unit -> unit
    34   val hol_no_types: unit -> unit
    35   val hol_typ_level: unit -> ResHolClause.type_level
    36   val run_relevance_filter: bool ref
    37   val invoke_atp_ml : ProofContext.context * thm -> unit
    38   val add_claset : unit -> unit
    39   val add_simpset : unit -> unit
    40   val add_clasimp : unit -> unit
    41   val add_atpset : unit -> unit
    42   val rm_claset : unit -> unit
    43   val rm_simpset : unit -> unit
    44   val rm_atpset : unit -> unit
    45   val rm_clasimp : unit -> unit
    46 end;
    47 
    48 structure ResAtp : RES_ATP =
    49 struct
    50 
    51 (********************************************************************)
    52 (* some settings for both background automatic ATP calling procedure*)
    53 (* and also explicit ATP invocation methods                         *)
    54 (********************************************************************)
    55 
    56 (*** background linkup ***)
    57 val call_atp = ref false; 
    58 val hook_count = ref 0;
    59 val time_limit = ref 30;
    60 val prover = ref "E";   (* use E as the default prover *)
    61 val custom_spass =   (*specialized options for SPASS*)
    62       ref ["-Auto=0","-FullRed=0","-IORe","-IOFc","-RTaut","-RFSub","-RBSub"];
    63 val destdir = ref "";   (*Empty means write files to /tmp*)
    64 val problem_name = ref "prob";
    65 
    66 (*Return the path to a "helper" like SPASS or tptp2X, first checking that
    67   it exists.  FIXME: modify to use Path primitives and move to some central place.*)  
    68 fun helper_path evar base =
    69   case getenv evar of
    70       "" => error  ("Isabelle environment variable " ^ evar ^ " not defined")
    71     | home => 
    72         let val path = home ^ "/" ^ base
    73         in  if File.exists (File.unpack_platform_path path) then path 
    74 	    else error ("Could not find the file " ^ path)
    75 	end;  
    76 
    77 fun probfile_nosuffix _ = 
    78   if !destdir = "" then File.platform_path (File.tmp_path (Path.basic (!problem_name)))
    79   else if File.exists (File.unpack_platform_path (!destdir))
    80   then !destdir ^ "/" ^ !problem_name
    81   else error ("No such directory: " ^ !destdir);
    82 
    83 fun prob_pathname n = probfile_nosuffix n ^ "_" ^ Int.toString n;
    84 
    85 
    86 (*** ATP methods ***)
    87 val vampire_time = ref 60;
    88 val eprover_time = ref 60;
    89 fun run_vampire time =  
    90     if (time >0) then vampire_time:= time
    91     else vampire_time:=60;
    92 
    93 fun run_eprover time = 
    94     if (time > 0) then eprover_time:= time
    95     else eprover_time:=60;
    96 
    97 fun vampireLimit () = !vampire_time;
    98 fun eproverLimit () = !eprover_time;
    99 
   100 val keep_atp_input = ref false;
   101 val fol_keep_types = ResClause.keep_types;
   102 val hol_full_types = ResHolClause.full_types;
   103 val hol_partial_types = ResHolClause.partial_types;
   104 val hol_const_types_only = ResHolClause.const_types_only;
   105 val hol_no_types = ResHolClause.no_types;
   106 fun hol_typ_level () = ResHolClause.find_typ_level ();
   107 fun is_typed_hol () = 
   108     let val tp_level = hol_typ_level()
   109     in
   110 	not (tp_level = ResHolClause.T_NONE)
   111     end;
   112 val include_combS = ResHolClause.include_combS;
   113 val include_min_comb = ResHolClause.include_min_comb;
   114 
   115 fun atp_input_file () =
   116     let val file = !problem_name 
   117     in
   118 	if !destdir = "" then File.platform_path (File.tmp_path (Path.basic file))
   119 	else if File.exists (File.unpack_platform_path (!destdir))
   120 	then !destdir ^ "/" ^ file
   121 	else error ("No such directory: " ^ !destdir)
   122     end;
   123 
   124 val include_simpset = ref false;
   125 val include_claset = ref false; 
   126 val include_atpset = ref true;
   127 val add_simpset = (fn () => include_simpset:=true);
   128 val add_claset = (fn () => include_claset:=true);
   129 val add_clasimp = (fn () => (include_simpset:=true;include_claset:=true));
   130 val add_atpset = (fn () => include_atpset:=true);
   131 val rm_simpset = (fn () => include_simpset:=false);
   132 val rm_claset = (fn () => include_claset:=false);
   133 val rm_clasimp = (fn () => (include_simpset:=false;include_claset:=false));
   134 val rm_atpset = (fn () => include_atpset:=false);
   135 
   136 
   137 (**** relevance filter ****)
   138 val run_relevance_filter = ref true;
   139 
   140 (******************************************************************)
   141 (* detect whether a given problem (clauses) is FOL/HOL/HOLC/HOLCS *)
   142 (******************************************************************)
   143 
   144 datatype logic = FOL | HOL | HOLC | HOLCS;
   145 
   146 fun string_of_logic FOL = "FOL"
   147   | string_of_logic HOL = "HOL"
   148   | string_of_logic HOLC = "HOLC"
   149   | string_of_logic HOLCS = "HOLCS";
   150 
   151 
   152 fun is_fol_logic FOL = true
   153   | is_fol_logic  _ = false
   154 
   155 
   156 (*HOLCS will not occur here*)
   157 fun upgrade_lg HOLC _ = HOLC
   158   | upgrade_lg HOL HOLC = HOLC
   159   | upgrade_lg HOL _ = HOL
   160   | upgrade_lg FOL lg = lg; 
   161 
   162 (* check types *)
   163 fun has_bool_hfn (Type("bool",_)) = true
   164   | has_bool_hfn (Type("fun",_)) = true
   165   | has_bool_hfn (Type(_, Ts)) = exists has_bool_hfn Ts
   166   | has_bool_hfn _ = false;
   167 
   168 fun is_hol_fn tp =
   169     let val (targs,tr) = strip_type tp
   170     in
   171 	exists (has_bool_hfn) (tr::targs)
   172     end;
   173 
   174 fun is_hol_pred tp =
   175     let val (targs,tr) = strip_type tp
   176     in
   177 	exists (has_bool_hfn) targs
   178     end;
   179 
   180 exception FN_LG of term;
   181 
   182 fun fn_lg (t as Const(f,tp)) (lg,seen) = 
   183     if is_hol_fn tp then (upgrade_lg HOL lg, t ins seen) else (lg, t ins seen) 
   184   | fn_lg (t as Free(f,tp)) (lg,seen) = 
   185     if is_hol_fn tp then (upgrade_lg HOL lg, t ins seen) else (lg, t ins seen) 
   186   | fn_lg (t as Var(f,tp)) (lg,seen) =
   187     if is_hol_fn tp then (upgrade_lg HOL lg,t ins seen) else (lg,t ins seen)
   188   | fn_lg (t as Abs(_,_,_)) (lg,seen) = (upgrade_lg HOLC lg,t ins seen)
   189   | fn_lg f _ = raise FN_LG(f); 
   190 
   191 
   192 fun term_lg [] (lg,seen) = (lg,seen)
   193   | term_lg (tm::tms) (FOL,seen) =
   194     let val (f,args) = strip_comb tm
   195 	val (lg',seen') = if f mem seen then (FOL,seen) 
   196 			  else fn_lg f (FOL,seen)
   197 	val _ = if is_fol_logic lg' then () else warning ("Found a HOL term: " ^ (Term.str_of_term f))
   198 	 in
   199 	     term_lg (args@tms) (lg',seen')
   200     end
   201   | term_lg _ (lg,seen) = (lg,seen)
   202 
   203 exception PRED_LG of term;
   204 
   205 fun pred_lg (t as Const(P,tp)) (lg,seen)= 
   206     if is_hol_pred tp then (upgrade_lg HOL lg, t ins seen) else (lg,t ins seen) 
   207   | pred_lg (t as Free(P,tp)) (lg,seen) =
   208     if is_hol_pred tp then (upgrade_lg HOL lg, t ins seen) else (lg,t ins seen)
   209   | pred_lg (t as Var(_,_)) (lg,seen) = (upgrade_lg HOL lg, t ins seen)
   210   | pred_lg P _ = raise PRED_LG(P);
   211 
   212 
   213 fun lit_lg (Const("Not",_) $ P) (lg,seen) = lit_lg P (lg,seen)
   214   | lit_lg P (lg,seen) =
   215     let val (pred,args) = strip_comb P
   216 	val (lg',seen') = if pred mem seen then (lg,seen) 
   217 			  else pred_lg pred (lg,seen)
   218 	val _ = if is_fol_logic lg' then () else warning ("Found a HOL predicate: " ^ (Term.str_of_term pred))
   219     in
   220 	term_lg args (lg',seen')
   221     end;
   222 
   223 fun lits_lg [] (lg,seen) = (lg,seen)
   224   | lits_lg (lit::lits) (FOL,seen) =
   225     let val (lg,seen') = lit_lg lit (FOL,seen)
   226 	val _ =  if is_fol_logic lg then () else warning ("Found a HOL literal: " ^ (Term.str_of_term lit))
   227     in
   228 	lits_lg lits (lg,seen')
   229     end
   230   | lits_lg lits (lg,seen) = (lg,seen);
   231 
   232 
   233 fun dest_disj_aux (Const ("op |", _) $ t $ t') disjs = 
   234     dest_disj_aux t (dest_disj_aux t' disjs)
   235   | dest_disj_aux t disjs = t::disjs;
   236 
   237 fun dest_disj t = dest_disj_aux t [];
   238 
   239 fun logic_of_clause tm (lg,seen) =
   240     let val tm' = HOLogic.dest_Trueprop tm
   241 	val disjs = dest_disj tm'
   242     in
   243 	lits_lg disjs (lg,seen)
   244     end;
   245 
   246 fun logic_of_clauses [] (lg,seen) = (lg,seen)
   247   | logic_of_clauses (cls::clss) (FOL,seen) =
   248     let val (lg,seen') = logic_of_clause cls (FOL,seen)
   249 	val _ = if is_fol_logic lg then () else warning ("Found a HOL clause: " ^ (Term.str_of_term cls))
   250     in
   251 	logic_of_clauses clss (lg,seen')
   252     end
   253   | logic_of_clauses (cls::clss) (lg,seen) = (lg,seen);
   254 
   255 fun problem_logic_goals_aux [] (lg,seen) = lg
   256   | problem_logic_goals_aux (subgoal::subgoals) (lg,seen) = 
   257     problem_logic_goals_aux subgoals (logic_of_clauses subgoal (lg,seen));
   258     
   259 fun problem_logic_goals subgoals = problem_logic_goals_aux subgoals (FOL,[]);
   260 
   261 
   262 (***************************************************************)
   263 (* ATP invocation methods setup                                *)
   264 (***************************************************************)
   265 
   266 
   267 (**** prover-specific format: TPTP ****)
   268 
   269 
   270 fun cnf_hyps_thms ctxt = 
   271     let val ths = ProofContext.prems_of ctxt
   272     in fold (fold (insert Thm.eq_thm) o ResAxioms.skolem_thm) ths [] end;
   273 
   274 
   275 (**** write to files ****)
   276 
   277 datatype mode = Auto | Fol | Hol;
   278 
   279 val linkup_logic_mode = ref Auto;
   280 
   281 fun tptp_writer logic goals filename (axioms,classrels,arities) =
   282     if is_fol_logic logic 
   283     then ResClause.tptp_write_file goals filename (axioms, classrels, arities)
   284     else ResHolClause.tptp_write_file goals filename (axioms, classrels, arities);
   285 
   286 (*2006-04-07: not working: goals has type thm list (not term list as above) and
   287   axioms has type ResClause.clause list (not (thm * (string * int)) list as above)*)
   288 fun dfg_writer logic goals filename (axioms,classrels,arities) =
   289     if is_fol_logic logic 
   290     then ResClause.dfg_write_file goals filename (axioms, classrels, arities)
   291     else error "DFG output for higher-order translations is not implemented"
   292 
   293 
   294 fun write_subgoal_file mode ctxt conjectures user_thms n =
   295     let val conj_cls = make_clauses conjectures 
   296 	val hyp_cls = cnf_hyps_thms ctxt
   297 	val goal_cls = conj_cls@hyp_cls
   298 	val user_rules = map ResAxioms.pairname user_thms
   299 	val (names_arr,axclauses_as_thms) = ResClasimp.get_clasimp_atp_lemmas ctxt (map prop_of goal_cls) user_rules (!include_claset,!include_simpset,!include_atpset) (!run_relevance_filter)  
   300 	val thy = ProofContext.theory_of ctxt
   301 	val prob_logic = case mode of Auto => problem_logic_goals [map prop_of goal_cls]
   302 				    | Fol => FOL
   303 				    | Hol => HOL
   304 	val keep_types = if is_fol_logic prob_logic then !fol_keep_types else is_typed_hol ()
   305 	val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   306 	val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   307         val writer = (*if !prover = "spass" then dfg_writer else*) tptp_writer 
   308 	val file = atp_input_file()
   309     in
   310 	(writer prob_logic goal_cls file (axclauses_as_thms,classrel_clauses,arity_clauses);
   311 	 warning ("Writing to " ^ file);
   312 	 file)
   313     end;
   314 
   315 
   316 (**** remove tmp files ****)
   317 fun cond_rm_tmp file = 
   318     if !keep_atp_input then warning "ATP input kept..." 
   319     else if !destdir <> "" then warning ("ATP input kept in directory " ^ (!destdir))
   320     else (warning "deleting ATP inputs..."; OS.FileSys.remove file);
   321 
   322 
   323 (****** setup ATPs as Isabelle methods ******)
   324 fun atp_meth' tac ths ctxt = 
   325     Method.SIMPLE_METHOD' HEADGOAL
   326     (tac ctxt ths);
   327 
   328 fun atp_meth tac ths ctxt = 
   329     let val thy = ProofContext.theory_of ctxt
   330 	val _ = ResClause.init thy
   331 	val _ = ResHolClause.init thy
   332     in
   333 	atp_meth' tac ths ctxt
   334     end;
   335 
   336 fun atp_method tac = Method.thms_ctxt_args (atp_meth tac);
   337 
   338 (***************************************************************)
   339 (* automatic ATP invocation                                    *)
   340 (***************************************************************)
   341 
   342 (* call prover with settings and problem file for the current subgoal *)
   343 fun watcher_call_provers sign sg_terms (childin, childout, pid) =
   344   let
   345     fun make_atp_list [] n = []
   346       | make_atp_list (sg_term::xs) n =
   347           let
   348             val probfile = prob_pathname n
   349             val time = Int.toString (!time_limit)
   350           in
   351             Output.debug ("problem file in watcher_call_provers is " ^ probfile);
   352             (*options are separated by Watcher.setting_sep, currently #"%"*)
   353             if !prover = "spass"
   354             then
   355               let val spass = helper_path "SPASS_HOME" "SPASS"
   356                   val sopts =
   357    "-Auto%-SOS=1%-PGiven=0%-PProblem=0%-Splits=0%-FullRed=0%-DocProof%-TimeLimit=" ^ time
   358               in 
   359                   ("spass", spass, sopts, probfile) :: make_atp_list xs (n+1)
   360               end
   361             else if !prover = "vampire"
   362 	    then 
   363               let val vampire = helper_path "VAMPIRE_HOME" "vampire"
   364                   val casc = if !time_limit > 70 then "--mode casc%" else ""
   365                   val vopts = casc ^ "-m 100000%-t " ^ time
   366               in
   367                   ("vampire", vampire, vopts, probfile) :: make_atp_list xs (n+1)
   368               end
   369       	     else if !prover = "E"
   370       	     then
   371 	       let val Eprover = helper_path "E_HOME" "eproof"
   372 	       in
   373 		  ("E", Eprover, 
   374 		     "--tptp-in%-l5%-xAuto%-tAuto%--cpu-limit=" ^ time, probfile) ::
   375 		   make_atp_list xs (n+1)
   376 	       end
   377 	     else error ("Invalid prover name: " ^ !prover)
   378           end
   379 
   380     val atp_list = make_atp_list sg_terms 1
   381   in
   382     Watcher.callResProvers(childout,atp_list);
   383     Output.debug "Sent commands to watcher!"
   384   end
   385 
   386 (*We write out problem files for each subgoal. Argument pf generates filenames,
   387   and allows the suppression of the suffix "_1" in problem-generation mode.
   388   FIXME: does not cope with &&, and it isn't easy because one could have multiple
   389   subgoals, each involving &&.*)
   390 fun write_problem_files pf (ctxt,th)  =
   391   let val goals = Thm.prems_of th
   392       val _ = Output.debug ("number of subgoals = " ^ Int.toString (length goals))
   393       val (names_arr, axclauses) = ResClasimp.get_clasimp_atp_lemmas ctxt goals [] (true,true,true) (!run_relevance_filter) (* no user supplied rules here, because no user invocation *)
   394       val _ = Output.debug ("claset, simprules and atprules total clauses = " ^ 
   395                      Int.toString (Array.length names_arr))
   396       val thy = ProofContext.theory_of ctxt
   397       fun get_neg_subgoals n =
   398 	  if n=0 then []
   399 	  else
   400 	      let val st = Seq.hd (EVERY'
   401 				       [rtac ccontr, ObjectLogic.atomize_tac, skolemize_tac] n th)
   402 		  val negs = Option.valOf (metahyps_thms n st)
   403 		  val negs_clauses = make_clauses negs
   404 	      in
   405 		  negs_clauses::(get_neg_subgoals (n - 1))
   406 	      end
   407       val neg_subgoals = get_neg_subgoals (length goals) 
   408       val goals_logic = case !linkup_logic_mode of Auto => problem_logic_goals (map (map prop_of) neg_subgoals)
   409 						 | Fol => FOL
   410 						 | Hol => HOL
   411       val keep_types = if is_fol_logic goals_logic then !ResClause.keep_types else is_typed_hol ()
   412       val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   413       val _ = Output.debug ("classrel clauses = " ^ Int.toString (length classrel_clauses))
   414       val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   415       val _ = Output.debug ("arity clauses = " ^ Int.toString (length arity_clauses))
   416       val writer = (*if !prover = "spass" then dfg_writer else*) tptp_writer 
   417       fun write_all [] _ = []
   418 	| write_all (subgoal::subgoals) k =
   419 	  (writer goals_logic subgoal (pf k) (axclauses,classrel_clauses,arity_clauses); pf k):: (write_all subgoals (k - 1))
   420   in
   421       (write_all neg_subgoals (length goals), names_arr)
   422   end;
   423 
   424 val last_watcher_pid = ref (NONE : (TextIO.instream * TextIO.outstream * 
   425                                     Posix.Process.pid * string list) option);
   426 
   427 fun kill_last_watcher () =
   428     (case !last_watcher_pid of 
   429          NONE => ()
   430        | SOME (_, _, pid, files) => 
   431 	  (Output.debug ("Killing old watcher, pid = " ^ string_of_pid pid);
   432 	   Watcher.killWatcher pid;  
   433 	   ignore (map (try OS.FileSys.remove) files)))
   434      handle OS.SysErr _ => Output.debug "Attempt to kill watcher failed";
   435 
   436 (*writes out the current clasimpset to a tptp file;
   437   turns off xsymbol at start of function, restoring it at end    *)
   438 val isar_atp = setmp print_mode [] 
   439  (fn (ctxt, th) =>
   440   if Thm.no_prems th then ()
   441   else
   442     let
   443       val _ = kill_last_watcher()
   444       val (files,names_arr) = write_problem_files prob_pathname (ctxt,th)
   445       val (childin, childout, pid) = Watcher.createWatcher (th, names_arr)
   446     in
   447       last_watcher_pid := SOME (childin, childout, pid, files);
   448       Output.debug ("problem files: " ^ space_implode ", " files); 
   449       Output.debug ("pid: " ^ string_of_pid pid);
   450       watcher_call_provers (sign_of_thm th) (Thm.prems_of th) (childin, childout, pid)
   451     end);
   452 
   453 val isar_atp_writeonly = setmp print_mode [] 
   454       (fn (ctxt,th) =>
   455        if Thm.no_prems th then ()
   456        else 
   457          let val pf = if Thm.nprems_of th = 1 then probfile_nosuffix 
   458          	      else prob_pathname
   459          in ignore (write_problem_files pf (ctxt,th)) end);
   460 
   461 
   462 (** the Isar toplevel hook **)
   463 
   464 fun invoke_atp_ml (ctxt, goal) =
   465   let val thy = ProofContext.theory_of ctxt;
   466   in
   467     Output.debug ("subgoals in isar_atp:\n" ^ 
   468 		  Pretty.string_of (ProofContext.pretty_term ctxt
   469 		    (Logic.mk_conjunction_list (Thm.prems_of goal))));
   470     Output.debug ("current theory: " ^ Context.theory_name thy);
   471     hook_count := !hook_count +1;
   472     Output.debug ("in hook for time: " ^ Int.toString (!hook_count));
   473     ResClause.init thy;
   474     ResHolClause.init thy;
   475     if !destdir = "" andalso !time_limit > 0 then isar_atp (ctxt, goal)
   476     else isar_atp_writeonly (ctxt, goal)
   477   end;
   478 
   479 val invoke_atp = Toplevel.no_timing o Toplevel.unknown_proof o Toplevel.keep
   480  (fn state =>
   481   let val (ctxt, (_, goal)) = Proof.get_goal (Toplevel.proof_of state)
   482   in  invoke_atp_ml (ctxt, goal)  end);
   483 
   484 val call_atpP =
   485   OuterSyntax.command 
   486     "ProofGeneral.call_atp" 
   487     "call automatic theorem provers" 
   488     OuterKeyword.diag
   489     (Scan.succeed invoke_atp);
   490 
   491 val _ = OuterSyntax.add_parsers [call_atpP];
   492 
   493 end;