src/HOL/Tools/sat_solver.ML
author wenzelm
Thu Aug 03 17:30:36 2006 +0200 (2006-08-03)
changeset 20328 5b240a4216b0
parent 20152 b6373fe199e1
child 20441 a9034285b96b
permissions -rw-r--r--
RuleInsts.bires_inst_tac;
     1 (*  Title:      HOL/Tools/sat_solver.ML
     2     ID:         $Id$
     3     Author:     Tjark Weber
     4     Copyright   2004-2005
     5 
     6 Interface to external SAT solvers, and (simple) built-in SAT solvers.
     7 *)
     8 
     9 signature SAT_SOLVER =
    10 sig
    11 	exception NOT_CONFIGURED
    12 
    13 	type assignment = int -> bool option
    14 	type proof      = int list Inttab.table * int
    15 	datatype result = SATISFIABLE of assignment
    16 	                | UNSATISFIABLE of proof option
    17 	                | UNKNOWN
    18 	type solver     = PropLogic.prop_formula -> result
    19 
    20 	(* auxiliary functions to create external SAT solvers *)
    21 	val write_dimacs_cnf_file : Path.T -> PropLogic.prop_formula -> unit
    22 	val write_dimacs_sat_file : Path.T -> PropLogic.prop_formula -> unit
    23 	val read_std_result_file  : Path.T -> string * string * string -> result
    24 	val make_external_solver  : string -> (PropLogic.prop_formula -> unit) -> (unit -> result) -> solver
    25 
    26 	val read_dimacs_cnf_file : Path.T -> PropLogic.prop_formula
    27 
    28 	(* generic solver interface *)
    29 	val solvers       : (string * solver) list ref
    30 	val add_solver    : string * solver -> unit
    31 	val invoke_solver : string -> solver  (* exception Option *)
    32 end;
    33 
    34 structure SatSolver : SAT_SOLVER =
    35 struct
    36 
    37 	open PropLogic;
    38 
    39 (* ------------------------------------------------------------------------- *)
    40 (* should be raised by an external SAT solver to indicate that the solver is *)
    41 (* not configured properly                                                   *)
    42 (* ------------------------------------------------------------------------- *)
    43 
    44 	exception NOT_CONFIGURED;
    45 
    46 (* ------------------------------------------------------------------------- *)
    47 (* type of partial (satisfying) assignments: 'a i = NONE' means that 'a' is  *)
    48 (*      a satisfying assignment regardless of the value of variable 'i'      *)
    49 (* ------------------------------------------------------------------------- *)
    50 
    51 	type assignment = int -> bool option;
    52 
    53 (* ------------------------------------------------------------------------- *)
    54 (* a proof of unsatisfiability, to be interpreted as follows: each integer   *)
    55 (*      is a clause ID, each list 'xs' stored under the key 'x' in the table *)
    56 (*      contains the IDs of clauses that must be resolved (in the given      *)
    57 (*      order) to obtain the new clause 'x'.  Each list 'xs' must be         *)
    58 (*      non-empty, and the literal to be resolved upon must always be unique *)
    59 (*      (e.g. "A | ~B" must not be resolved with "~A | B").  Circular        *)
    60 (*      dependencies of clauses are not allowed.  (At least) one of the      *)
    61 (*      clauses in the table must be the empty clause (i.e. contain no       *)
    62 (*      literals); its ID is given by the second component of the proof.     *)
    63 (*      The clauses of the original problem passed to the SAT solver have    *)
    64 (*      consecutive IDs starting with 0.  Clause IDs must be non-negative,   *)
    65 (*      but do not need to be consecutive.                                   *)
    66 (* ------------------------------------------------------------------------- *)
    67 
    68 	type proof = int list Inttab.table * int;
    69 
    70 (* ------------------------------------------------------------------------- *)
    71 (* return type of SAT solvers: if the result is 'SATISFIABLE', a satisfying  *)
    72 (*      assignment must be returned as well; if the result is                *)
    73 (*      'UNSATISFIABLE', a proof of unsatisfiability may be returned         *)
    74 (* ------------------------------------------------------------------------- *)
    75 
    76 	datatype result = SATISFIABLE of assignment
    77 	                | UNSATISFIABLE of proof option
    78 	                | UNKNOWN;
    79 
    80 (* ------------------------------------------------------------------------- *)
    81 (* type of SAT solvers: given a propositional formula, a satisfying          *)
    82 (*      assignment may be returned                                           *)
    83 (* ------------------------------------------------------------------------- *)
    84 
    85 	type solver = prop_formula -> result;
    86 
    87 (* ------------------------------------------------------------------------- *)
    88 (* write_dimacs_cnf_file: serializes a formula 'fm' of propositional logic   *)
    89 (*      to a file in DIMACS CNF format (see "Satisfiability Suggested        *)
    90 (*      Format", May 8 1993, Section 2.1)                                    *)
    91 (* Note: 'fm' must not contain a variable index less than 1.                 *)
    92 (* Note: 'fm' must be given in CNF.                                          *)
    93 (* ------------------------------------------------------------------------- *)
    94 
    95 	(* Path.T -> prop_formula -> unit *)
    96 
    97 	fun write_dimacs_cnf_file path fm =
    98 	let
    99 		(* prop_formula -> prop_formula *)
   100 		fun cnf_True_False_elim True =
   101 			Or (BoolVar 1, Not (BoolVar 1))
   102 		  | cnf_True_False_elim False =
   103 			And (BoolVar 1, Not (BoolVar 1))
   104 		  | cnf_True_False_elim fm =
   105 			fm  (* since 'fm' is in CNF, either 'fm'='True'/'False', or 'fm' does not contain 'True'/'False' at all *)
   106 		(* prop_formula -> int *)
   107 		fun cnf_number_of_clauses (And (fm1,fm2)) =
   108 			(cnf_number_of_clauses fm1) + (cnf_number_of_clauses fm2)
   109 		  | cnf_number_of_clauses _ =
   110 			1
   111 		(* prop_formula -> string list *)
   112 		fun cnf_string fm =
   113 		let
   114 			(* prop_formula -> string list -> string list *)
   115 			fun cnf_string_acc True acc =
   116 				error "formula is not in CNF"
   117 			  | cnf_string_acc False acc =
   118 				error "formula is not in CNF"
   119 			  | cnf_string_acc (BoolVar i) acc =
   120 				(assert (i>=1) "formula contains a variable index less than 1";
   121 				string_of_int i :: acc)
   122 			  | cnf_string_acc (Not (BoolVar i)) acc =
   123 				"-" :: cnf_string_acc (BoolVar i) acc
   124 			  | cnf_string_acc (Not _) acc =
   125 				error "formula is not in CNF"
   126 			  | cnf_string_acc (Or (fm1,fm2)) acc =
   127 				cnf_string_acc fm1 (" " :: cnf_string_acc fm2 acc)
   128 			  | cnf_string_acc (And (fm1,fm2)) acc =
   129 				cnf_string_acc fm1 (" 0\n" :: cnf_string_acc fm2 acc)
   130 		in
   131 			cnf_string_acc fm []
   132 		end
   133 		val fm'               = cnf_True_False_elim fm
   134 		val number_of_vars    = maxidx fm'
   135 		val number_of_clauses = cnf_number_of_clauses fm'
   136 	in
   137 		File.write path
   138 			("c This file was generated by SatSolver.write_dimacs_cnf_file\n" ^
   139 			 "p cnf " ^ string_of_int number_of_vars ^ " " ^ string_of_int number_of_clauses ^ "\n");
   140 		File.append_list path
   141 			(cnf_string fm');
   142 		File.append path
   143 			" 0\n"
   144 	end;
   145 
   146 (* ------------------------------------------------------------------------- *)
   147 (* write_dimacs_sat_file: serializes a formula 'fm' of propositional logic   *)
   148 (*      to a file in DIMACS SAT format (see "Satisfiability Suggested        *)
   149 (*      Format", May 8 1993, Section 2.2)                                    *)
   150 (* Note: 'fm' must not contain a variable index less than 1.                 *)
   151 (* ------------------------------------------------------------------------- *)
   152 
   153 	(* Path.T -> prop_formula -> unit *)
   154 
   155 	fun write_dimacs_sat_file path fm =
   156 	let
   157 		(* prop_formula -> string list *)
   158 		fun sat_string fm =
   159 		let
   160 			(* prop_formula -> string list -> string list *)
   161 			fun sat_string_acc True acc =
   162 				"*()" :: acc
   163 			  | sat_string_acc False acc =
   164 				"+()" :: acc
   165 			  | sat_string_acc (BoolVar i) acc =
   166 				(assert (i>=1) "formula contains a variable index less than 1";
   167 				string_of_int i :: acc)
   168 			  | sat_string_acc (Not (BoolVar i)) acc =
   169 				"-" :: sat_string_acc (BoolVar i) acc
   170 			  | sat_string_acc (Not fm) acc =
   171 				"-(" :: sat_string_acc fm (")" :: acc)
   172 			  | sat_string_acc (Or (fm1,fm2)) acc =
   173 				"+(" :: sat_string_acc_or fm1 (" " :: sat_string_acc_or fm2 (")" :: acc))
   174 			  | sat_string_acc (And (fm1,fm2)) acc =
   175 				"*(" :: sat_string_acc_and fm1 (" " :: sat_string_acc_and fm2 (")" :: acc))
   176 			(* optimization to make use of n-ary disjunction/conjunction *)
   177 			(* prop_formula -> string list -> string list *)
   178 			and sat_string_acc_or (Or (fm1,fm2)) acc =
   179 				sat_string_acc_or fm1 (" " :: sat_string_acc_or fm2 acc)
   180 			  | sat_string_acc_or fm acc =
   181 				sat_string_acc fm acc
   182 			(* prop_formula -> string list -> string list *)
   183 			and sat_string_acc_and (And (fm1,fm2)) acc =
   184 				sat_string_acc_and fm1 (" " :: sat_string_acc_and fm2 acc)
   185 			  | sat_string_acc_and fm acc =
   186 				sat_string_acc fm acc
   187 		in
   188 			sat_string_acc fm []
   189 		end
   190 		val number_of_vars = Int.max (maxidx fm, 1)
   191 	in
   192 		File.write path
   193 			("c This file was generated by SatSolver.write_dimacs_sat_file\n" ^
   194 			 "p sat " ^ string_of_int number_of_vars ^ "\n" ^
   195 			 "(");
   196 		File.append_list path
   197 			(sat_string fm);
   198 		File.append path
   199 			")\n"
   200 	end;
   201 
   202 (* ------------------------------------------------------------------------- *)
   203 (* read_std_result_file: scans a SAT solver's output file for a satisfying   *)
   204 (*      variable assignment.  Returns the assignment, or 'UNSATISFIABLE' if  *)
   205 (*      the file contains 'unsatisfiable', or 'UNKNOWN' if the file contains *)
   206 (*      neither 'satisfiable' nor 'unsatisfiable'.  Empty lines are ignored. *)
   207 (*      The assignment must be given in one or more lines immediately after  *)
   208 (*      the line that contains 'satisfiable'.  These lines must begin with   *)
   209 (*      'assignment_prefix'.  Variables must be separated by " ".  Non-      *)
   210 (*      integer strings are ignored.  If variable i is contained in the      *)
   211 (*      assignment, then i is interpreted as 'true'.  If ~i is contained in  *)
   212 (*      the assignment, then i is interpreted as 'false'.  Otherwise the     *)
   213 (*      value of i is taken to be unspecified.                               *)
   214 (* ------------------------------------------------------------------------- *)
   215 
   216 	(* Path.T -> string * string * string -> result *)
   217 
   218 	fun read_std_result_file path (satisfiable, assignment_prefix, unsatisfiable) =
   219 	let
   220 		(* string -> int list *)
   221 		fun int_list_from_string s =
   222 			List.mapPartial Int.fromString (space_explode " " s)
   223 		(* int list -> assignment *)
   224 		fun assignment_from_list [] i =
   225 			NONE  (* the SAT solver didn't provide a value for this variable *)
   226 		  | assignment_from_list (x::xs) i =
   227 			if x=i then (SOME true)
   228 			else if x=(~i) then (SOME false)
   229 			else assignment_from_list xs i
   230 		(* int list -> string list -> assignment *)
   231 		fun parse_assignment xs [] =
   232 			assignment_from_list xs
   233 		  | parse_assignment xs (line::lines) =
   234 			if String.isPrefix assignment_prefix line then
   235 				parse_assignment (xs @ int_list_from_string line) lines
   236 			else
   237 				assignment_from_list xs
   238 		(* string -> string -> bool *)
   239 		fun is_substring needle haystack =
   240 		let
   241 			val length1 = String.size needle
   242 			val length2 = String.size haystack
   243 		in
   244 			if length2 < length1 then
   245 				false
   246 			else if needle = String.substring (haystack, 0, length1) then
   247 				true
   248 			else is_substring needle (String.substring (haystack, 1, length2-1))
   249 		end
   250 		(* string list -> result *)
   251 		fun parse_lines [] =
   252 			UNKNOWN
   253 		  | parse_lines (line::lines) =
   254 			if is_substring unsatisfiable line then
   255 				UNSATISFIABLE NONE
   256 			else if is_substring satisfiable line then
   257 				SATISFIABLE (parse_assignment [] lines)
   258 			else
   259 				parse_lines lines
   260 	in
   261 		(parse_lines o (List.filter (fn l => l <> "")) o split_lines o File.read) path
   262 	end;
   263 
   264 (* ------------------------------------------------------------------------- *)
   265 (* make_external_solver: call 'writefn', execute 'cmd', call 'readfn'        *)
   266 (* ------------------------------------------------------------------------- *)
   267 
   268 	(* string -> (PropLogic.prop_formula -> unit) -> (unit -> result) -> solver *)
   269 
   270 	fun make_external_solver cmd writefn readfn fm =
   271 		(writefn fm; system cmd; readfn ());
   272 
   273 (* ------------------------------------------------------------------------- *)
   274 (* read_dimacs_cnf_file: returns a propositional formula that corresponds to *)
   275 (*      a SAT problem given in DIMACS CNF format                             *)
   276 (* ------------------------------------------------------------------------- *)
   277 
   278 	(* Path.T -> PropLogic.prop_formula *)
   279 
   280 	fun read_dimacs_cnf_file path =
   281 	let
   282 		(* string list -> string list *)
   283 		fun filter_preamble [] =
   284 			error "problem line not found in DIMACS CNF file"
   285 		  | filter_preamble (line::lines) =
   286 			if String.isPrefix "c " line then
   287 				(* ignore comments *)
   288 				filter_preamble lines
   289 			else if String.isPrefix "p " line then
   290 				(* ignore the problem line (which must be the last line of the preamble) *)
   291 				(* Ignoring the problem line implies that if the file contains more clauses *)
   292 				(* or variables than specified in its preamble, we will accept it anyway.   *)
   293 				lines
   294 			else
   295 				error "preamble in DIMACS CNF file contains a line that does not begin with \"c \" or \"p \""
   296 		(* string -> int *)
   297 		fun int_from_string s =
   298 			case Int.fromString s of
   299 			  SOME i => i
   300 			| NONE   => error ("token " ^ quote s ^ "in DIMACS CNF file is not a number")
   301 		(* int list -> int list list *)
   302 		fun clauses xs =
   303 			let
   304 				val (xs1, xs2) = take_prefix (fn i => i <> 0) xs
   305 			in
   306 				case xs2 of
   307 				  []      => [xs1]
   308 				| (0::[]) => [xs1]
   309 				| (0::tl) => xs1 :: clauses tl
   310 				| _       => sys_error "this cannot happen"
   311 			end
   312 		(* int -> PropLogic.prop_formula *)
   313 		fun literal_from_int i =
   314 			(assert (i<>0) "variable index in DIMACS CNF file is 0";
   315 			if i>0 then
   316 				PropLogic.BoolVar i
   317 			else
   318 				PropLogic.Not (PropLogic.BoolVar (~i)))
   319 		(* PropLogic.prop_formula list -> PropLogic.prop_formula *)
   320 		fun disjunction [] =
   321 			error "empty clause in DIMACS CNF file"
   322 		  | disjunction (x::xs) =
   323 			(case xs of
   324 			  [] => x
   325 			| _  => PropLogic.Or (x, disjunction xs))
   326 		(* PropLogic.prop_formula list -> PropLogic.prop_formula *)
   327 		fun conjunction [] =
   328 			error "no clause in DIMACS CNF file"
   329 		  | conjunction (x::xs) =
   330 			(case xs of
   331 			  [] => x
   332 			| _  => PropLogic.And (x, conjunction xs))
   333 	in
   334 		(conjunction
   335 		o (map disjunction)
   336 		o (map (map literal_from_int))
   337 		o clauses
   338 		o (map int_from_string)
   339 		o List.concat
   340 		o (map (String.fields (fn c => c mem [#" ", #"\t", #"\n"])))
   341 		o filter_preamble
   342 		o (List.filter (fn l => l <> ""))
   343 		o split_lines
   344 		o File.read)
   345 			path
   346 	end;
   347 
   348 (* ------------------------------------------------------------------------- *)
   349 (* solvers: a (reference to a) table of all registered SAT solvers           *)
   350 (* ------------------------------------------------------------------------- *)
   351 
   352 	val solvers = ref ([] : (string * solver) list);
   353 
   354 (* ------------------------------------------------------------------------- *)
   355 (* add_solver: updates 'solvers' by adding a new solver                      *)
   356 (* ------------------------------------------------------------------------- *)
   357 
   358 	(* string * solver -> unit *)
   359 
   360 	fun add_solver (name, new_solver) =
   361 		(solvers := update_warn (op =) ("SAT solver " ^ quote name ^ " was defined before") (name, new_solver) (!solvers));
   362 
   363 (* ------------------------------------------------------------------------- *)
   364 (* invoke_solver: returns the solver associated with the given 'name'        *)
   365 (* Note: If no solver is associated with 'name', exception 'Option' will be  *)
   366 (*       raised.                                                             *)
   367 (* ------------------------------------------------------------------------- *)
   368 
   369 	(* string -> solver *)
   370 
   371 	fun invoke_solver name =
   372 		(the o AList.lookup (op =) (!solvers)) name;
   373 
   374 end;  (* SatSolver *)
   375 
   376 
   377 (* ------------------------------------------------------------------------- *)
   378 (* Predefined SAT solvers                                                    *)
   379 (* ------------------------------------------------------------------------- *)
   380 
   381 (* ------------------------------------------------------------------------- *)
   382 (* Internal SAT solver, available as 'SatSolver.invoke_solver "enumerate"'   *)
   383 (* -- simply enumerates assignments until a satisfying assignment is found   *)
   384 (* ------------------------------------------------------------------------- *)
   385 
   386 let
   387 	fun enum_solver fm =
   388 	let
   389 		(* int list *)
   390 		val indices = PropLogic.indices fm
   391 		(* int list -> int list -> int list option *)
   392 		(* binary increment: list 'xs' of current bits, list 'ys' of all bits (lower bits first) *)
   393 		fun next_list _ ([]:int list) =
   394 			NONE
   395 		  | next_list [] (y::ys) =
   396 			SOME [y]
   397 		  | next_list (x::xs) (y::ys) =
   398 			if x=y then
   399 				(* reset the bit, continue *)
   400 				next_list xs ys
   401 			else
   402 				(* set the lowest bit that wasn't set before, keep the higher bits *)
   403 				SOME (y::x::xs)
   404 		(* int list -> int -> bool *)
   405 		fun assignment_from_list xs i =
   406 			i mem xs
   407 		(* int list -> SatSolver.result *)
   408 		fun solver_loop xs =
   409 			if PropLogic.eval (assignment_from_list xs) fm then
   410 				SatSolver.SATISFIABLE (SOME o (assignment_from_list xs))
   411 			else
   412 				(case next_list xs indices of
   413 				  SOME xs' => solver_loop xs'
   414 				| NONE     => SatSolver.UNSATISFIABLE NONE)
   415 	in
   416 		(* start with the "first" assignment (all variables are interpreted as 'false') *)
   417 		solver_loop []
   418 	end
   419 in
   420 	SatSolver.add_solver ("enumerate", enum_solver)
   421 end;
   422 
   423 (* ------------------------------------------------------------------------- *)
   424 (* Internal SAT solver, available as 'SatSolver.invoke_solver "dpll"' -- a   *)
   425 (* simple implementation of the DPLL algorithm (cf. L. Zhang, S. Malik: "The *)
   426 (* Quest for Efficient Boolean Satisfiability Solvers", July 2002, Fig. 1).  *)
   427 (* ------------------------------------------------------------------------- *)
   428 
   429 let
   430 	local
   431 		open PropLogic
   432 	in
   433 		fun dpll_solver fm =
   434 		let
   435 			(* We could use 'PropLogic.defcnf fm' instead of 'PropLogic.nnf fm' *)
   436 			(* but that sometimes leads to worse performance due to the         *)
   437 			(* introduction of additional variables.                            *)
   438 			val fm' = PropLogic.nnf fm
   439 			(* int list *)
   440 			val indices = PropLogic.indices fm'
   441 			(* int list -> int -> prop_formula *)
   442 			fun partial_var_eval []      i = BoolVar i
   443 			  | partial_var_eval (x::xs) i = if x=i then True else if x=(~i) then False else partial_var_eval xs i
   444 			(* int list -> prop_formula -> prop_formula *)
   445 			fun partial_eval xs True             = True
   446 			  | partial_eval xs False            = False
   447 			  | partial_eval xs (BoolVar i)      = partial_var_eval xs i
   448 			  | partial_eval xs (Not fm)         = SNot (partial_eval xs fm)
   449 			  | partial_eval xs (Or (fm1, fm2))  = SOr (partial_eval xs fm1, partial_eval xs fm2)
   450 			  | partial_eval xs (And (fm1, fm2)) = SAnd (partial_eval xs fm1, partial_eval xs fm2)
   451 			(* prop_formula -> int list *)
   452 			fun forced_vars True              = []
   453 			  | forced_vars False             = []
   454 			  | forced_vars (BoolVar i)       = [i]
   455 			  | forced_vars (Not (BoolVar i)) = [~i]
   456 			  | forced_vars (Or (fm1, fm2))   = (forced_vars fm1) inter_int (forced_vars fm2)
   457 			  | forced_vars (And (fm1, fm2))  = (forced_vars fm1) union_int (forced_vars fm2)
   458 			  (* Above, i *and* ~i may be forced.  In this case the first occurrence takes   *)
   459 			  (* precedence, and the next partial evaluation of the formula returns 'False'. *)
   460 			  | forced_vars _                 = error "formula is not in negation normal form"
   461 			(* int list -> prop_formula -> (int list * prop_formula) *)
   462 			fun eval_and_force xs fm =
   463 			let
   464 				val fm' = partial_eval xs fm
   465 				val xs' = forced_vars fm'
   466 			in
   467 				if null xs' then
   468 					(xs, fm')
   469 				else
   470 					eval_and_force (xs@xs') fm'  (* xs and xs' should be distinct, so '@' here should have *)
   471 					                             (* the same effect as 'union_int'                         *)
   472 			end
   473 			(* int list -> int option *)
   474 			fun fresh_var xs =
   475 				Library.find_first (fn i => not (i mem_int xs) andalso not ((~i) mem_int xs)) indices
   476 			(* int list -> prop_formula -> int list option *)
   477 			(* partial assignment 'xs' *)
   478 			fun dpll xs fm =
   479 			let
   480 				val (xs', fm') = eval_and_force xs fm
   481 			in
   482 				case fm' of
   483 				  True  => SOME xs'
   484 				| False => NONE
   485 				| _     =>
   486 					let
   487 						val x = valOf (fresh_var xs')  (* a fresh variable must exist since 'fm' did not evaluate to 'True'/'False' *)
   488 					in
   489 						case dpll (x::xs') fm' of  (* passing fm' rather than fm should save some simplification work *)
   490 						  SOME xs'' => SOME xs''
   491 						| NONE      => dpll ((~x)::xs') fm'  (* now try interpreting 'x' as 'False' *)
   492 					end
   493 			end
   494 			(* int list -> assignment *)
   495 			fun assignment_from_list [] i =
   496 				NONE  (* the DPLL procedure didn't provide a value for this variable *)
   497 			  | assignment_from_list (x::xs) i =
   498 				if x=i then (SOME true)
   499 				else if x=(~i) then (SOME false)
   500 				else assignment_from_list xs i
   501 		in
   502 			(* initially, no variable is interpreted yet *)
   503 			case dpll [] fm' of
   504 			  SOME assignment => SatSolver.SATISFIABLE (assignment_from_list assignment)
   505 			| NONE            => SatSolver.UNSATISFIABLE NONE
   506 		end
   507 	end  (* local *)
   508 in
   509 	SatSolver.add_solver ("dpll", dpll_solver)
   510 end;
   511 
   512 (* ------------------------------------------------------------------------- *)
   513 (* Internal SAT solver, available as 'SatSolver.invoke_solver "auto"': uses  *)
   514 (* the last installed solver (other than "auto" itself) that does not raise  *)
   515 (* 'NOT_CONFIGURED'.  (However, the solver may return 'UNKNOWN'.)            *)
   516 (* ------------------------------------------------------------------------- *)
   517 
   518 let
   519 	fun auto_solver fm =
   520 	let
   521 		fun loop [] =
   522 			SatSolver.UNKNOWN
   523 		  | loop ((name, solver)::solvers) =
   524 			if name="auto" then
   525 				(* do not call solver "auto" from within "auto" *)
   526 				loop solvers
   527 			else (
   528 				(if name="dpll" orelse name="enumerate" then
   529 					warning ("Using SAT solver " ^ quote name ^ "; for better performance, consider using an external solver.")
   530 				else
   531 					tracing ("Using SAT solver " ^ quote name ^ "."));
   532 				(* apply 'solver' to 'fm' *)
   533 				solver fm
   534 					handle SatSolver.NOT_CONFIGURED => loop solvers
   535 			)
   536 	in
   537 		loop (!SatSolver.solvers)
   538 	end
   539 in
   540 	SatSolver.add_solver ("auto", auto_solver)
   541 end;
   542 
   543 (* ------------------------------------------------------------------------- *)
   544 (* MiniSat 1.14                                                              *)
   545 (* (http://www.cs.chalmers.se/Cs/Research/FormalMethods/MiniSat/)            *)
   546 (* ------------------------------------------------------------------------- *)
   547 
   548 (* ------------------------------------------------------------------------- *)
   549 (* "minisat_with_proofs" requires a modified version of MiniSat 1.14 by John *)
   550 (* Matthews, which can output ASCII proof traces.  Replaying binary proof    *)
   551 (* traces generated by MiniSat-p_v1.14 has _not_ been implemented.           *)
   552 (* ------------------------------------------------------------------------- *)
   553 
   554 (* add "minisat_with_proofs" _before_ "minisat" to the available solvers, so *)
   555 (* that the latter is preferred by the "auto" solver                         *)
   556 
   557 (* There is a complication that is dealt with in the code below: MiniSat     *)
   558 (* introduces IDs for original clauses in the proof trace.  It does not (in  *)
   559 (* general) follow the convention that the original clauses are numbered     *)
   560 (* from 0 to n-1 (where n is the number of clauses in the formula).          *)
   561 
   562 let
   563 	exception INVALID_PROOF of string
   564 	fun minisat_with_proofs fm =
   565 	let
   566 		val _          = if (getenv "MINISAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   567 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   568 		val outpath    = File.tmp_path (Path.unpack "result")
   569 		val proofpath  = File.tmp_path (Path.unpack "result.prf")
   570 		val cmd        = (getenv "MINISAT_HOME") ^ "/minisat " ^ (Path.pack inpath) ^ " -r " ^ (Path.pack outpath) ^ " -t " ^ (Path.pack proofpath) ^ "> /dev/null"
   571 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath fm
   572 		fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
   573 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   574 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   575 		val cnf        = PropLogic.defcnf fm
   576 		val result     = SatSolver.make_external_solver cmd writefn readfn cnf
   577 		val _          = try File.rm inpath
   578 		val _          = try File.rm outpath
   579 	in  case result of
   580 	  SatSolver.UNSATISFIABLE NONE =>
   581 		(let
   582 			(* string list *)
   583 			val proof_lines = ((split_lines o File.read) proofpath)
   584 				handle IO.Io _ => raise INVALID_PROOF "Could not read file \"result.prf\""
   585 			(* a simple representation of the CNF formula as list of clauses (paired with their ID), *)
   586 			(* where each clause is a sorted list of literals, where each literal is an int          *)
   587 			(* removes duplicates from an ordered list *)
   588 			(* int list -> int list *)
   589 			fun remove_dups []             = []
   590 			  | remove_dups [x]            = [x]
   591 			  | remove_dups (x :: y :: xs) = if x = y then remove_dups (y :: xs) else x :: remove_dups (y :: xs)
   592 			(* prop_formula -> int list *)
   593 			fun clause_to_lit_list (PropLogic.Or (fm1, fm2))             = clause_to_lit_list fm1 @ clause_to_lit_list fm2
   594 			  | clause_to_lit_list (PropLogic.BoolVar i)                 = [i]
   595 			  | clause_to_lit_list (PropLogic.Not (PropLogic.BoolVar i)) = [~i]
   596 			  | clause_to_lit_list _                 = raise INVALID_PROOF "Error: invalid clause in CNF formula."
   597 			(* prop_formula -> int list list *)
   598 			fun cnf_to_clause_list (PropLogic.And (fm1, fm2)) = cnf_to_clause_list fm1 @ cnf_to_clause_list fm2
   599 			  | cnf_to_clause_list fm                         = [(remove_dups o sort int_ord o clause_to_lit_list) fm]
   600 			(* (int list * int) list * int *)
   601 			val (clauses, length_clauses) = fold_map (fn clause => fn n => ((clause, n), n+1)) (cnf_to_clause_list cnf) 0
   602 			(* string -> int *)
   603 			fun int_from_string s = (
   604 				case Int.fromString s of
   605 				  SOME i => i
   606 				| NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
   607 			)
   608 			(* parse the proof file *)
   609 			(* contains a mapping from clause IDs as used by MiniSat to clause IDs in *)
   610 			(* our proof format, where original clauses are numbered starting from 0  *)
   611 			val clause_id_map = ref (Inttab.empty : int Inttab.table)
   612 			fun sat_to_proof id = (
   613 				case Inttab.lookup (!clause_id_map) id of
   614 				  SOME id' => id'
   615 				| NONE     => raise INVALID_PROOF ("Clause ID " ^ Int.toString id ^ " used, but not defined.")
   616 			)
   617 			val next_id = ref (length_clauses - 1)
   618 			(* string list -> proof -> proof *)
   619 			fun process_tokens [] proof =
   620 				proof
   621 			  | process_tokens (tok::toks) (clause_table, empty_id) =
   622 				if tok="R" then (
   623 					case toks of
   624 					  id::sep::lits =>
   625 						let
   626 							val _        = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"R\" disallowed after \"X\"."
   627 							val cid      = int_from_string id
   628 							val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
   629 							val ls       = sort int_ord (map int_from_string lits)
   630 							val proof_id = (* both 'ls' and the list of literals used as key in 'clauses' are sorted, *)
   631 							               (* so testing for equality should suffice -- barring duplicate literals    *)
   632 							               case AList.lookup (op =) clauses ls of
   633 							                 SOME orig_id => orig_id
   634 						                   | NONE         => raise INVALID_PROOF ("Original clause (new ID is " ^ id ^ ") not found.")
   635 							(* extend the mapping of clause IDs with this newly defined ID *)
   636 							val _        = clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
   637 							                 handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"R\").")
   638 						in
   639 							(* the proof itself doesn't change *)
   640 							(clause_table, empty_id)
   641 						end
   642 					| _ =>
   643 						raise INVALID_PROOF "File format error: \"R\" followed by an insufficient number of tokens."
   644 				) else if tok="C" then (
   645 					case toks of
   646 					  id::sep::ids =>
   647 						let
   648 							val _        = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"C\" disallowed after \"X\"."
   649 							val cid      = int_from_string id
   650 							val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
   651 							(* ignore the pivot literals in MiniSat's trace *)
   652 							fun unevens []             = raise INVALID_PROOF "File format error: \"C\" followed by an even number of IDs."
   653 							  | unevens (x :: [])      = x :: []
   654 							  | unevens (x :: _ :: xs) = x :: unevens xs
   655 							val rs       = (map sat_to_proof o unevens o map int_from_string) ids
   656 							(* extend the mapping of clause IDs with this newly defined ID *)
   657 							val proof_id = inc next_id
   658 							val _        = clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
   659 							                 handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"C\").")
   660 						in
   661 							(* update clause table *)
   662 							(Inttab.update_new (proof_id, rs) clause_table, empty_id)
   663 								handle Inttab.DUP _ => raise INVALID_PROOF ("Error: internal ID for clause " ^ id ^ " already used.")
   664 						end
   665 					| _ =>
   666 						raise INVALID_PROOF "File format error: \"C\" followed by an insufficient number of tokens."
   667 				) else if tok="D" then (
   668 					case toks of
   669 					  [id] =>
   670 						let
   671 							val _ = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"D\" disallowed after \"X\"."
   672 							val _ = sat_to_proof (int_from_string id)
   673 						in
   674 							(* simply ignore "D" *)
   675 							(clause_table, empty_id)
   676 						end
   677 					| _ =>
   678 						raise INVALID_PROOF "File format error: \"D\" followed by an illegal number of tokens."
   679 				) else if tok="X" then (
   680 					case toks of
   681 					  [id1, id2] =>
   682 						let
   683 							val _            = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one end-of-proof statement."
   684 							val _            = sat_to_proof (int_from_string id1)
   685 							val new_empty_id = sat_to_proof (int_from_string id2)
   686 						in
   687 							(* update conflict id *)
   688 							(clause_table, new_empty_id)
   689 						end
   690 					| _ =>
   691 						raise INVALID_PROOF "File format error: \"X\" followed by an illegal number of tokens."
   692 				) else
   693 					raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
   694 			(* string list -> proof -> proof *)
   695 			fun process_lines [] proof =
   696 				proof
   697 			  | process_lines (l::ls) proof =
   698 				process_lines ls (process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l) proof)
   699 			(* proof *)
   700 			val (clause_table, empty_id) = process_lines proof_lines (Inttab.empty, ~1)
   701 			val _                        = if empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
   702 		in
   703 			SatSolver.UNSATISFIABLE (SOME (clause_table, empty_id))
   704 		end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
   705 	| result =>
   706 		result
   707 	end
   708 in
   709 	SatSolver.add_solver ("minisat_with_proofs", minisat_with_proofs)
   710 end;
   711 
   712 let
   713 	fun minisat fm =
   714 	let
   715 		val _          = if (getenv "MINISAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   716 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   717 		val outpath    = File.tmp_path (Path.unpack "result")
   718 		val cmd        = (getenv "MINISAT_HOME") ^ "/minisat " ^ (Path.pack inpath) ^ " -r " ^ (Path.pack outpath) ^ " > /dev/null"
   719 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   720 		fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
   721 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   722 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   723 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   724 		val _          = try File.rm inpath
   725 		val _          = try File.rm outpath
   726 	in
   727 		result
   728 	end
   729 in
   730 	SatSolver.add_solver ("minisat", minisat)
   731 end;
   732 
   733 (* ------------------------------------------------------------------------- *)
   734 (* zChaff (http://www.princeton.edu/~chaff/zchaff.html)                      *)
   735 (* ------------------------------------------------------------------------- *)
   736 
   737 (* ------------------------------------------------------------------------- *)
   738 (* 'zchaff_with_proofs' applies the "zchaff" prover to a formula, and if     *)
   739 (* zChaff finds that the formula is unsatisfiable, a proof of this is read   *)
   740 (* from a file "resolve_trace" that was generated by zChaff.  See the code   *)
   741 (* below for the expected format of the "resolve_trace" file.  Aside from    *)
   742 (* some basic syntactic checks, no verification of the proof is performed.   *)
   743 (* ------------------------------------------------------------------------- *)
   744 
   745 (* add "zchaff_with_proofs" _before_ "zchaff" to the available solvers, so   *)
   746 (* that the latter is preferred by the "auto" solver                         *)
   747 
   748 let
   749 	exception INVALID_PROOF of string
   750 	fun zchaff_with_proofs fm =
   751 	case SatSolver.invoke_solver "zchaff" fm of
   752 	  SatSolver.UNSATISFIABLE NONE =>
   753 		(let
   754 			(* string list *)
   755 			val proof_lines = ((split_lines o File.read) (Path.unpack "resolve_trace"))
   756 				handle IO.Io _ => raise INVALID_PROOF "Could not read file \"resolve_trace\""
   757 			(* PropLogic.prop_formula -> int *)
   758 			fun cnf_number_of_clauses (PropLogic.And (fm1, fm2)) = cnf_number_of_clauses fm1 + cnf_number_of_clauses fm2
   759 			  | cnf_number_of_clauses _                          = 1
   760 			(* string -> int *)
   761 			fun int_from_string s = (
   762 				case Int.fromString s of
   763 				  SOME i => i
   764 				| NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
   765 			)
   766 			(* parse the "resolve_trace" file *)
   767 			(* int ref *)
   768 			val clause_offset = ref ~1
   769 			(* string list -> proof -> proof *)
   770 			fun process_tokens [] proof =
   771 				proof
   772 			  | process_tokens (tok::toks) (clause_table, empty_id) =
   773 				if tok="CL:" then (
   774 					case toks of
   775 					  id::sep::ids =>
   776 						let
   777 							val _   = if !clause_offset = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"VAR:\".")
   778 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"CONF:\".")
   779 							val cid = int_from_string id
   780 							val _   = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
   781 							val rs  = map int_from_string ids
   782 						in
   783 							(* update clause table *)
   784 							(Inttab.update_new (cid, rs) clause_table, empty_id)
   785 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once.")
   786 						end
   787 					| _ =>
   788 						raise INVALID_PROOF "File format error: \"CL:\" followed by an insufficient number of tokens."
   789 				) else if tok="VAR:" then (
   790 					case toks of
   791 					  id::levsep::levid::valsep::valid::antesep::anteid::litsep::lits =>
   792 						let
   793 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"VAR:\" disallowed after \"CONF:\".")
   794 							(* set 'clause_offset' to the largest used clause ID *)
   795 							val _   = if !clause_offset = ~1 then clause_offset :=
   796 								(case Inttab.max_key clause_table of
   797 								  SOME id => id
   798 								| NONE    => cnf_number_of_clauses (PropLogic.defcnf fm) - 1  (* the first clause ID is 0, not 1 *))
   799 								else
   800 									()
   801 							val vid = int_from_string id
   802 							val _   = if levsep = "L:" then () else raise INVALID_PROOF ("File format error: \"L:\" expected (" ^ quote levsep ^ " encountered).")
   803 							val _   = int_from_string levid
   804 							val _   = if valsep = "V:" then () else raise INVALID_PROOF ("File format error: \"V:\" expected (" ^ quote valsep ^ " encountered).")
   805 							val _   = int_from_string valid
   806 							val _   = if antesep = "A:" then () else raise INVALID_PROOF ("File format error: \"A:\" expected (" ^ quote antesep ^ " encountered).")
   807 							val aid = int_from_string anteid
   808 							val _   = if litsep = "Lits:" then () else raise INVALID_PROOF ("File format error: \"Lits:\" expected (" ^ quote litsep ^ " encountered).")
   809 							val ls  = map int_from_string lits
   810 							(* convert the data provided by zChaff to our resolution-style proof format *)
   811 							(* each "VAR:" line defines a unit clause, the resolvents are implicitly    *)
   812 							(* given by the literals in the antecedent clause                           *)
   813 							(* we use the sum of '!clause_offset' and the variable ID as clause ID for the unit clause *)
   814 							val cid = !clause_offset + vid
   815 							(* the low bit of each literal gives its sign (positive/negative), therefore  *)
   816 							(* we have to divide each literal by 2 to obtain the proper variable ID; then *)
   817 							(* we add '!clause_offset' to obtain the ID of the corresponding unit clause  *)
   818 							val vids = filter (not_equal vid) (map (fn l => l div 2) ls)
   819 							val rs   = aid :: map (fn v => !clause_offset + v) vids
   820 						in
   821 							(* update clause table *)
   822 							(Inttab.update_new (cid, rs) clause_table, empty_id)
   823 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int cid ^ " (derived from antecedent for variable " ^ id ^ ") already defined.")
   824 						end
   825 					| _ =>
   826 						raise INVALID_PROOF "File format error: \"VAR:\" followed by an insufficient number of tokens."
   827 				) else if tok="CONF:" then (
   828 					case toks of
   829 					  id::sep::ids =>
   830 						let
   831 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one conflicting clause specified."
   832 							val cid = int_from_string id
   833 							val _   = if sep = "==" then () else raise INVALID_PROOF ("File format error: \"==\" expected (" ^ quote sep ^ " encountered).")
   834 							val ls  = map int_from_string ids
   835 							(* the conflict clause must be resolved with the unit clauses *)
   836 							(* for its literals to obtain the empty clause                *)
   837 							val vids         = map (fn l => l div 2) ls
   838 							val rs           = cid :: map (fn v => !clause_offset + v) vids
   839 							val new_empty_id = getOpt (Inttab.max_key clause_table, !clause_offset) + 1
   840 						in
   841 							(* update clause table and conflict id *)
   842 							(Inttab.update_new (new_empty_id, rs) clause_table, new_empty_id)
   843 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int new_empty_id ^ " (empty clause derived from clause " ^ id ^ ") already defined.")
   844 						end
   845 					| _ =>
   846 						raise INVALID_PROOF "File format error: \"CONF:\" followed by an insufficient number of tokens."
   847 				) else
   848 					raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
   849 			(* string list -> proof -> proof *)
   850 			fun process_lines [] proof =
   851 				proof
   852 			  | process_lines (l::ls) proof =
   853 				process_lines ls (process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l) proof)
   854 			(* proof *)
   855 			val (clause_table, empty_id) = process_lines proof_lines (Inttab.empty, ~1)
   856 			val _                        = if empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
   857 		in
   858 			SatSolver.UNSATISFIABLE (SOME (clause_table, empty_id))
   859 		end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
   860 	| result =>
   861 		result
   862 in
   863 	SatSolver.add_solver ("zchaff_with_proofs", zchaff_with_proofs)
   864 end;
   865 
   866 let
   867 	fun zchaff fm =
   868 	let
   869 		val _          = if (getenv "ZCHAFF_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   870 		val _          = if (getenv "ZCHAFF_VERSION") <> "2004.5.13" andalso
   871 		                    (getenv "ZCHAFF_VERSION") <> "2004.11.15" then raise SatSolver.NOT_CONFIGURED else ()
   872 			(* both versions of zChaff appear to have the same interface, so we do *)
   873 			(* not actually need to distinguish between them in the following code *)
   874 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   875 		val outpath    = File.tmp_path (Path.unpack "result")
   876 		val cmd        = (getenv "ZCHAFF_HOME") ^ "/zchaff " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   877 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   878 		fun readfn ()  = SatSolver.read_std_result_file outpath ("Instance Satisfiable", "", "Instance Unsatisfiable")
   879 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   880 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   881 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   882 		val _          = try File.rm inpath
   883 		val _          = try File.rm outpath
   884 	in
   885 		result
   886 	end
   887 in
   888 	SatSolver.add_solver ("zchaff", zchaff)
   889 end;
   890 
   891 (* ------------------------------------------------------------------------- *)
   892 (* BerkMin 561 (http://eigold.tripod.com/BerkMin.html)                       *)
   893 (* ------------------------------------------------------------------------- *)
   894 
   895 let
   896 	fun berkmin fm =
   897 	let
   898 		val _          = if (getenv "BERKMIN_HOME") = "" orelse (getenv "BERKMIN_EXE") = "" then raise SatSolver.NOT_CONFIGURED else ()
   899 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   900 		val outpath    = File.tmp_path (Path.unpack "result")
   901 		val cmd        = (getenv "BERKMIN_HOME") ^ "/" ^ (getenv "BERKMIN_EXE") ^ " " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   902 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   903 		fun readfn ()  = SatSolver.read_std_result_file outpath ("Satisfiable          !!", "solution =", "UNSATISFIABLE          !!")
   904 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   905 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   906 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   907 		val _          = try File.rm inpath
   908 		val _          = try File.rm outpath
   909 	in
   910 		result
   911 	end
   912 in
   913 	SatSolver.add_solver ("berkmin", berkmin)
   914 end;
   915 
   916 (* ------------------------------------------------------------------------- *)
   917 (* Jerusat 1.3 (http://www.cs.tau.ac.il/~ale1/)                              *)
   918 (* ------------------------------------------------------------------------- *)
   919 
   920 let
   921 	fun jerusat fm =
   922 	let
   923 		val _          = if (getenv "JERUSAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   924 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   925 		val outpath    = File.tmp_path (Path.unpack "result")
   926 		val cmd        = (getenv "JERUSAT_HOME") ^ "/Jerusat1.3 " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   927 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   928 		fun readfn ()  = SatSolver.read_std_result_file outpath ("s SATISFIABLE", "v ", "s UNSATISFIABLE")
   929 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   930 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   931 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   932 		val _          = try File.rm inpath
   933 		val _          = try File.rm outpath
   934 	in
   935 		result
   936 	end
   937 in
   938 	SatSolver.add_solver ("jerusat", jerusat)
   939 end;
   940 
   941 (* ------------------------------------------------------------------------- *)
   942 (* Add code for other SAT solvers below.                                     *)
   943 (* ------------------------------------------------------------------------- *)
   944 
   945 (*
   946 let
   947 	fun mysolver fm = ...
   948 in
   949 	SatSolver.add_solver ("myname", (fn fm => if mysolver_is_configured then mysolver fm else raise SatSolver.NOT_CONFIGURED));  -- register the solver
   950 end;
   951 
   952 -- the solver is now available as SatSolver.invoke_solver "myname"
   953 *)