src/HOL/Tools/sat_solver.ML
author webertj
Mon Jul 17 15:16:17 2006 +0200 (2006-07-17)
changeset 20137 6c04453ac1bd
parent 20135 5a6b33268bb6
child 20152 b6373fe199e1
permissions -rw-r--r--
butlast removed (use fst o split_last instead)
     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 are two complications that must be dealt with in the code below:    *)
   558 (* 1. MiniSat introduces IDs for original clauses in the proof trace.  It    *)
   559 (*    does not in general follow the convention that the original clauses    *)
   560 (*    are numbered from 0 to n-1 (where n is the number of clauses in the    *)
   561 (*    formula).                                                              *)
   562 (* 2. MiniSat considers some problems (presumably those that can be solved   *)
   563 (*    by unit propagation alone) to be "trivial" and does not provide a      *)
   564 (*    proof for them.                                                        *)
   565 
   566 let
   567 	exception INVALID_PROOF of string
   568 	exception TRIVIAL_PROOF of SatSolver.proof
   569 	fun minisat_with_proofs fm =
   570 	let
   571 		val _          = if (getenv "MINISAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   572 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   573 		val outpath    = File.tmp_path (Path.unpack "result")
   574 		val proofpath  = File.tmp_path (Path.unpack "result.prf")
   575 		val cmd        = (getenv "MINISAT_HOME") ^ "/minisat " ^ (Path.pack inpath) ^ " -r " ^ (Path.pack outpath) ^ " -t " ^ (Path.pack proofpath) ^ "> /dev/null"
   576 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath fm
   577 		fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
   578 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   579 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   580 		(* since MiniSat only generates proof traces for "non-trivial" problems, *)
   581 		(* an old proof trace must be deleted so that it is not mistaken as the  *)
   582 		(* proof trace for this (possibly trivial) problem                       *)
   583 		val _          = try File.rm proofpath
   584 		val cnf        = PropLogic.defcnf fm
   585 		val result     = SatSolver.make_external_solver cmd writefn readfn cnf
   586 		val _          = try File.rm inpath
   587 		val _          = try File.rm outpath
   588 	in  case result of
   589 	  SatSolver.UNSATISFIABLE NONE =>
   590 		(let
   591 			(* a simple representation of the CNF formula as list of clauses (paired with their ID), *)
   592 			(* where each clause is a sorted list of literals, where each literal is an int          *)
   593 			(* removes duplicates from an ordered list *)
   594 			(* int list -> int list *)
   595 			fun remove_dups []             = []
   596 			  | remove_dups [x]            = [x]
   597 			  | remove_dups (x :: y :: xs) = if x = y then remove_dups (y :: xs) else x :: remove_dups (y :: xs)
   598 			(* prop_formula -> int list *)
   599 			fun clause_to_lit_list (PropLogic.Or (fm1, fm2))             = clause_to_lit_list fm1 @ clause_to_lit_list fm2
   600 			  | clause_to_lit_list (PropLogic.BoolVar i)                 = [i]
   601 			  | clause_to_lit_list (PropLogic.Not (PropLogic.BoolVar i)) = [~i]
   602 			  | clause_to_lit_list _                 = raise INVALID_PROOF "Error: invalid clause in CNF formula."
   603 			(* prop_formula -> int list list *)
   604 			fun cnf_to_clause_list (PropLogic.And (fm1, fm2)) = cnf_to_clause_list fm1 @ cnf_to_clause_list fm2
   605 			  | cnf_to_clause_list fm                         = [(remove_dups o sort int_ord o clause_to_lit_list) fm]
   606 			(* (int list * int) list * int *)
   607 			val (clauses, length_clauses) = fold_map (fn clause => fn n => ((clause, n), n+1)) (cnf_to_clause_list cnf) 0
   608 			(* string list *)
   609 			val proof_lines = ((split_lines o File.read) proofpath)
   610 				handle IO.Io _ =>
   611 					(* the problem may be "trivial", i.e. provable by unit propagation only *)
   612 					let
   613 						val _ = tracing "Unable to read MiniSat proof file, searching for a proof by unit propagation only ..."
   614 						(* int list -> bool *)
   615 						fun is_empty_clause [] = true
   616 						  | is_empty_clause _  = false
   617 						(* int list -> bool *)
   618 						fun is_unit_clause [_] = true
   619 						  | is_unit_clause _   = false
   620 						(* int list -> int *)
   621 						fun unit_literal [l] = l
   622 						  | unit_literal _   = raise INVALID_PROOF "Error during unit propagation: clause is not a unit clause."
   623 						(* proof -> ... -> proof *)
   624 						fun proof_by_iterated_unit_propagation (clause_table, next_id) (units_new, units, clauses_done, clauses_todo) = (
   625 							case clauses_todo of
   626 							  [] =>
   627 								if units_new = [] then
   628 									(* no further unit propagation possible -- give up *)
   629 									raise INVALID_PROOF "Could not read file \"result.prf\", and no proof by unit propagation only found."
   630 								else
   631 									(* start over again, this time with the new unit clauses *)
   632 									proof_by_iterated_unit_propagation (clause_table, next_id) ([], units_new, [], clauses_done)
   633 							| (clause_lits, clause_id) :: clauses_todo' =>
   634 								let
   635 									(* resolve the given list of literals with all possible unit clauses, *)
   636 									(* return the remaining literals and the resolvents' IDs              *)
   637 									(* int list * int list -> int list * int list *)
   638 									fun resolve_loop ([],      rs) = ([], rs)
   639 									  | resolve_loop (l :: ls, rs) =
   640 										(case AList.lookup (op =) units (~l) of
   641 										  SOME unit_id => resolve_loop (ls, unit_id :: rs)
   642 										| NONE         => apfst (cons l) (resolve_loop (ls, rs)))
   643 									val (new_clause_lits, rs) = resolve_loop (clause_lits, [])
   644 								in
   645 									if rs = [] then
   646 										(* no resolution possible, clause remains unchanged -- continue with the next clause *)
   647 										proof_by_iterated_unit_propagation (clause_table, next_id)
   648 										  (units_new, units, (clause_lits, clause_id) :: clauses_done, clauses_todo')
   649 									else
   650 										let
   651 											(* we have a new clause -- add its derivation to the proof trace *)
   652 											val new_clause_table = Inttab.update_new (next_id, clause_id :: rs) clause_table
   653 											                         handle Inttab.DUP _ => raise INVALID_PROOF ("Error during unit propagation: internal clause ID " ^ Int.toString next_id ^ " already used.")
   654 										in
   655 											if is_empty_clause new_clause_lits then
   656 												(* proof found *)
   657 												(new_clause_table, next_id)
   658 											else if is_unit_clause new_clause_lits then
   659 												(* continue search with a new unit clause *)
   660 												proof_by_iterated_unit_propagation (new_clause_table, next_id + 1)
   661 												  ((unit_literal new_clause_lits, next_id + 1) :: units_new, units, (new_clause_lits, next_id + 1) :: clauses_done, clauses_todo')
   662 											else
   663 												(* continue search with a new clause *)
   664 												proof_by_iterated_unit_propagation (new_clause_table, next_id + 1)
   665 												  (units_new, units, (new_clause_lits, next_id + 1) :: clauses_done, clauses_todo')
   666 										end
   667 								end
   668 						)
   669 						val units = map (apfst unit_literal) (filter (is_unit_clause o fst) clauses)
   670 						val proof = proof_by_iterated_unit_propagation (Inttab.empty, length_clauses) ([], units, [], clauses)
   671 					in
   672 						raise TRIVIAL_PROOF proof
   673 					end  (* end of "trivial" proof search *)
   674 			(* string -> int *)
   675 			fun int_from_string s = (
   676 				case Int.fromString s of
   677 				  SOME i => i
   678 				| NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
   679 			)
   680 			(* parse the proof file *)
   681 			(* contains a mapping from clause IDs as used by MiniSat to clause IDs in *)
   682 			(* our proof format, where original clauses are numbered starting from 0  *)
   683 			val clause_id_map = ref (Inttab.empty : int Inttab.table)
   684 			fun sat_to_proof id = (
   685 				case Inttab.lookup (!clause_id_map) id of
   686 				  SOME id' => id'
   687 				| NONE     => raise INVALID_PROOF ("Clause ID " ^ Int.toString id ^ " used, but not defined.")
   688 			)
   689 			val next_id = ref (length_clauses - 1)
   690 			(* string list -> proof -> proof *)
   691 			fun process_tokens [] proof =
   692 				proof
   693 			  | process_tokens (tok::toks) (clause_table, empty_id) =
   694 				if tok="R" then (
   695 					case toks of
   696 					  id::sep::lits =>
   697 						let
   698 							val _        = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"R\" disallowed after \"X\"."
   699 							val cid      = int_from_string id
   700 							val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
   701 							val zero     = List.last lits handle List.Empty => raise INVALID_PROOF "File format error: \"R\" not terminated by \"0\"."
   702 							val ls       = sort int_ord (map int_from_string ((fst o split_last) lits))
   703 							val _        = if zero = "0" then () else raise INVALID_PROOF ("File format error: \"0\" expected (" ^ quote zero ^ " encountered).")
   704 							val proof_id = (* both 'ls' and the list of literals used as key in 'clauses' are sorted, *)
   705 							               (* so testing for equality should suffice -- barring duplicate literals    *)
   706 							               case AList.lookup (op =) clauses ls of
   707 							                 SOME orig_id => orig_id
   708 						                   | NONE         => raise INVALID_PROOF ("Original clause (new ID is " ^ id ^ ") not found.")
   709 							(* extend the mapping of clause IDs with this newly defined ID *)
   710 							val _        = clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
   711 							                 handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"R\").")
   712 						in
   713 							(* the proof itself doesn't change *)
   714 							(clause_table, empty_id)
   715 						end
   716 					| _ =>
   717 						raise INVALID_PROOF "File format error: \"R\" followed by an insufficient number of tokens."
   718 				) else if tok="C" then (
   719 					case toks of
   720 					  id::sep::ids =>
   721 						let
   722 							val _        = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"C\" disallowed after \"X\"."
   723 							val cid      = int_from_string id
   724 							val _        = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
   725 							val dot      = List.last ids handle List.Empty => raise INVALID_PROOF "File format error: \"C\" not terminated by \".\"."
   726 							(* ignore the pivot literals in MiniSat's trace *)
   727 							fun unevens []             = raise INVALID_PROOF "File format error: \"C\" followed by an even number of IDs."
   728 							  | unevens (x :: [])      = x :: []
   729 							  | unevens (x :: _ :: xs) = x :: unevens xs
   730 							val rs       = (map sat_to_proof o unevens o map int_from_string o fst o split_last) ids
   731 							val _        = if dot = "." then () else raise INVALID_PROOF ("File format error: \".\" expected (" ^ quote dot ^ " encountered).")
   732 							(* extend the mapping of clause IDs with this newly defined ID *)
   733 							val proof_id = inc next_id
   734 							val _        = clause_id_map := Inttab.update_new (cid, proof_id) (!clause_id_map)
   735 							                 handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once (in \"C\").")
   736 						in
   737 							(* update clause table *)
   738 							(Inttab.update_new (proof_id, rs) clause_table, empty_id)
   739 								handle Inttab.DUP _ => raise INVALID_PROOF ("Error: internal ID for clause " ^ id ^ " already used.")
   740 						end
   741 					| _ =>
   742 						raise INVALID_PROOF "File format error: \"C\" followed by an insufficient number of tokens."
   743 				) else if tok="D" then (
   744 					case toks of
   745 					  [id] =>
   746 						let
   747 							val _ = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: \"D\" disallowed after \"X\"."
   748 							val _ = sat_to_proof (int_from_string id)
   749 						in
   750 							(* simply ignore "D" *)
   751 							(clause_table, empty_id)
   752 						end
   753 					| _ =>
   754 						raise INVALID_PROOF "File format error: \"D\" followed by an illegal number of tokens."
   755 				) else if tok="X" then (
   756 					case toks of
   757 					  [id1, id2] =>
   758 						let
   759 							val _            = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one end-of-proof statement."
   760 							val _            = sat_to_proof (int_from_string id1)
   761 							val new_empty_id = sat_to_proof (int_from_string id2)
   762 						in
   763 							(* update conflict id *)
   764 							(clause_table, new_empty_id)
   765 						end
   766 					| _ =>
   767 						raise INVALID_PROOF "File format error: \"X\" followed by an illegal number of tokens."
   768 				) else
   769 					raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
   770 			(* string list -> proof -> proof *)
   771 			fun process_lines [] proof =
   772 				proof
   773 			  | process_lines (l::ls) proof =
   774 				process_lines ls (process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l) proof)
   775 			(* proof *)
   776 			val (clause_table, empty_id) = process_lines proof_lines (Inttab.empty, ~1)
   777 			val _                        = if empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
   778 		in
   779 			SatSolver.UNSATISFIABLE (SOME (clause_table, empty_id))
   780 		end handle TRIVIAL_PROOF proof => SatSolver.UNSATISFIABLE (SOME proof)
   781 		         | INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
   782 	| result =>
   783 		result
   784 	end
   785 in
   786 	SatSolver.add_solver ("minisat_with_proofs", minisat_with_proofs)
   787 end;
   788 
   789 let
   790 	fun minisat fm =
   791 	let
   792 		val _          = if (getenv "MINISAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   793 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   794 		val outpath    = File.tmp_path (Path.unpack "result")
   795 		val cmd        = (getenv "MINISAT_HOME") ^ "/minisat " ^ (Path.pack inpath) ^ " -r " ^ (Path.pack outpath) ^ " > /dev/null"
   796 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   797 		fun readfn ()  = SatSolver.read_std_result_file outpath ("SAT", "", "UNSAT")
   798 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   799 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   800 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   801 		val _          = try File.rm inpath
   802 		val _          = try File.rm outpath
   803 	in
   804 		result
   805 	end
   806 in
   807 	SatSolver.add_solver ("minisat", minisat)
   808 end;
   809 
   810 (* ------------------------------------------------------------------------- *)
   811 (* zChaff (http://www.princeton.edu/~chaff/zchaff.html)                      *)
   812 (* ------------------------------------------------------------------------- *)
   813 
   814 (* ------------------------------------------------------------------------- *)
   815 (* 'zchaff_with_proofs' applies the "zchaff" prover to a formula, and if     *)
   816 (* zChaff finds that the formula is unsatisfiable, a proof of this is read   *)
   817 (* from a file "resolve_trace" that was generated by zChaff.  See the code   *)
   818 (* below for the expected format of the "resolve_trace" file.  Aside from    *)
   819 (* some basic syntactic checks, no verification of the proof is performed.   *)
   820 (* ------------------------------------------------------------------------- *)
   821 
   822 (* add "zchaff_with_proofs" _before_ "zchaff" to the available solvers, so   *)
   823 (* that the latter is preferred by the "auto" solver                         *)
   824 
   825 let
   826 	exception INVALID_PROOF of string
   827 	fun zchaff_with_proofs fm =
   828 	case SatSolver.invoke_solver "zchaff" fm of
   829 	  SatSolver.UNSATISFIABLE NONE =>
   830 		(let
   831 			(* string list *)
   832 			val proof_lines = ((split_lines o File.read) (Path.unpack "resolve_trace"))
   833 				handle IO.Io _ => raise INVALID_PROOF "Could not read file \"resolve_trace\""
   834 			(* PropLogic.prop_formula -> int *)
   835 			fun cnf_number_of_clauses (PropLogic.And (fm1, fm2)) = cnf_number_of_clauses fm1 + cnf_number_of_clauses fm2
   836 			  | cnf_number_of_clauses _                          = 1
   837 			(* string -> int *)
   838 			fun int_from_string s = (
   839 				case Int.fromString s of
   840 				  SOME i => i
   841 				| NONE   => raise INVALID_PROOF ("File format error: number expected (" ^ quote s ^ " encountered).")
   842 			)
   843 			(* parse the "resolve_trace" file *)
   844 			(* int ref *)
   845 			val clause_offset = ref ~1
   846 			(* string list -> proof -> proof *)
   847 			fun process_tokens [] proof =
   848 				proof
   849 			  | process_tokens (tok::toks) (clause_table, empty_id) =
   850 				if tok="CL:" then (
   851 					case toks of
   852 					  id::sep::ids =>
   853 						let
   854 							val _   = if !clause_offset = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"VAR:\".")
   855 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"CL:\" disallowed after \"CONF:\".")
   856 							val cid = int_from_string id
   857 							val _   = if sep = "<=" then () else raise INVALID_PROOF ("File format error: \"<=\" expected (" ^ quote sep ^ " encountered).")
   858 							val rs  = map int_from_string ids
   859 						in
   860 							(* update clause table *)
   861 							(Inttab.update_new (cid, rs) clause_table, empty_id)
   862 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ id ^ " defined more than once.")
   863 						end
   864 					| _ =>
   865 						raise INVALID_PROOF "File format error: \"CL:\" followed by an insufficient number of tokens."
   866 				) else if tok="VAR:" then (
   867 					case toks of
   868 					  id::levsep::levid::valsep::valid::antesep::anteid::litsep::lits =>
   869 						let
   870 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF ("File format error: \"VAR:\" disallowed after \"CONF:\".")
   871 							(* set 'clause_offset' to the largest used clause ID *)
   872 							val _   = if !clause_offset = ~1 then clause_offset :=
   873 								(case Inttab.max_key clause_table of
   874 								  SOME id => id
   875 								| NONE    => cnf_number_of_clauses (PropLogic.defcnf fm) - 1  (* the first clause ID is 0, not 1 *))
   876 								else
   877 									()
   878 							val vid = int_from_string id
   879 							val _   = if levsep = "L:" then () else raise INVALID_PROOF ("File format error: \"L:\" expected (" ^ quote levsep ^ " encountered).")
   880 							val _   = int_from_string levid
   881 							val _   = if valsep = "V:" then () else raise INVALID_PROOF ("File format error: \"V:\" expected (" ^ quote valsep ^ " encountered).")
   882 							val _   = int_from_string valid
   883 							val _   = if antesep = "A:" then () else raise INVALID_PROOF ("File format error: \"A:\" expected (" ^ quote antesep ^ " encountered).")
   884 							val aid = int_from_string anteid
   885 							val _   = if litsep = "Lits:" then () else raise INVALID_PROOF ("File format error: \"Lits:\" expected (" ^ quote litsep ^ " encountered).")
   886 							val ls  = map int_from_string lits
   887 							(* convert the data provided by zChaff to our resolution-style proof format *)
   888 							(* each "VAR:" line defines a unit clause, the resolvents are implicitly    *)
   889 							(* given by the literals in the antecedent clause                           *)
   890 							(* we use the sum of '!clause_offset' and the variable ID as clause ID for the unit clause *)
   891 							val cid = !clause_offset + vid
   892 							(* the low bit of each literal gives its sign (positive/negative), therefore  *)
   893 							(* we have to divide each literal by 2 to obtain the proper variable ID; then *)
   894 							(* we add '!clause_offset' to obtain the ID of the corresponding unit clause  *)
   895 							val vids = filter (not_equal vid) (map (fn l => l div 2) ls)
   896 							val rs   = aid :: map (fn v => !clause_offset + v) vids
   897 						in
   898 							(* update clause table *)
   899 							(Inttab.update_new (cid, rs) clause_table, empty_id)
   900 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int cid ^ " (derived from antecedent for variable " ^ id ^ ") already defined.")
   901 						end
   902 					| _ =>
   903 						raise INVALID_PROOF "File format error: \"VAR:\" followed by an insufficient number of tokens."
   904 				) else if tok="CONF:" then (
   905 					case toks of
   906 					  id::sep::ids =>
   907 						let
   908 							val _   = if empty_id = ~1 then () else raise INVALID_PROOF "File format error: more than one conflicting clause specified."
   909 							val cid = int_from_string id
   910 							val _   = if sep = "==" then () else raise INVALID_PROOF ("File format error: \"==\" expected (" ^ quote sep ^ " encountered).")
   911 							val ls  = map int_from_string ids
   912 							(* the conflict clause must be resolved with the unit clauses *)
   913 							(* for its literals to obtain the empty clause                *)
   914 							val vids         = map (fn l => l div 2) ls
   915 							val rs           = cid :: map (fn v => !clause_offset + v) vids
   916 							val new_empty_id = getOpt (Inttab.max_key clause_table, !clause_offset) + 1
   917 						in
   918 							(* update clause table and conflict id *)
   919 							(Inttab.update_new (new_empty_id, rs) clause_table, new_empty_id)
   920 								handle Inttab.DUP _ => raise INVALID_PROOF ("File format error: clause " ^ string_of_int new_empty_id ^ " (empty clause derived from clause " ^ id ^ ") already defined.")
   921 						end
   922 					| _ =>
   923 						raise INVALID_PROOF "File format error: \"CONF:\" followed by an insufficient number of tokens."
   924 				) else
   925 					raise INVALID_PROOF ("File format error: unknown token " ^ quote tok ^ " encountered.")
   926 			(* string list -> proof -> proof *)
   927 			fun process_lines [] proof =
   928 				proof
   929 			  | process_lines (l::ls) proof =
   930 				process_lines ls (process_tokens (String.tokens (fn c => c = #" " orelse c = #"\t") l) proof)
   931 			(* proof *)
   932 			val (clause_table, empty_id) = process_lines proof_lines (Inttab.empty, ~1)
   933 			val _                        = if empty_id <> ~1 then () else raise INVALID_PROOF "File format error: no conflicting clause specified."
   934 		in
   935 			SatSolver.UNSATISFIABLE (SOME (clause_table, empty_id))
   936 		end handle INVALID_PROOF reason => (warning reason; SatSolver.UNSATISFIABLE NONE))
   937 	| result =>
   938 		result
   939 in
   940 	SatSolver.add_solver ("zchaff_with_proofs", zchaff_with_proofs)
   941 end;
   942 
   943 let
   944 	fun zchaff fm =
   945 	let
   946 		val _          = if (getenv "ZCHAFF_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
   947 		val _          = if (getenv "ZCHAFF_VERSION") <> "2004.5.13" andalso
   948 		                    (getenv "ZCHAFF_VERSION") <> "2004.11.15" then raise SatSolver.NOT_CONFIGURED else ()
   949 			(* both versions of zChaff appear to have the same interface, so we do *)
   950 			(* not actually need to distinguish between them in the following code *)
   951 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   952 		val outpath    = File.tmp_path (Path.unpack "result")
   953 		val cmd        = (getenv "ZCHAFF_HOME") ^ "/zchaff " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   954 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   955 		fun readfn ()  = SatSolver.read_std_result_file outpath ("Instance Satisfiable", "", "Instance Unsatisfiable")
   956 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   957 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   958 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   959 		val _          = try File.rm inpath
   960 		val _          = try File.rm outpath
   961 	in
   962 		result
   963 	end
   964 in
   965 	SatSolver.add_solver ("zchaff", zchaff)
   966 end;
   967 
   968 (* ------------------------------------------------------------------------- *)
   969 (* BerkMin 561 (http://eigold.tripod.com/BerkMin.html)                       *)
   970 (* ------------------------------------------------------------------------- *)
   971 
   972 let
   973 	fun berkmin fm =
   974 	let
   975 		val _          = if (getenv "BERKMIN_HOME") = "" orelse (getenv "BERKMIN_EXE") = "" then raise SatSolver.NOT_CONFIGURED else ()
   976 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
   977 		val outpath    = File.tmp_path (Path.unpack "result")
   978 		val cmd        = (getenv "BERKMIN_HOME") ^ "/" ^ (getenv "BERKMIN_EXE") ^ " " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
   979 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
   980 		fun readfn ()  = SatSolver.read_std_result_file outpath ("Satisfiable          !!", "solution =", "UNSATISFIABLE          !!")
   981 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
   982 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
   983 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
   984 		val _          = try File.rm inpath
   985 		val _          = try File.rm outpath
   986 	in
   987 		result
   988 	end
   989 in
   990 	SatSolver.add_solver ("berkmin", berkmin)
   991 end;
   992 
   993 (* ------------------------------------------------------------------------- *)
   994 (* Jerusat 1.3 (http://www.cs.tau.ac.il/~ale1/)                              *)
   995 (* ------------------------------------------------------------------------- *)
   996 
   997 let
   998 	fun jerusat fm =
   999 	let
  1000 		val _          = if (getenv "JERUSAT_HOME") = "" then raise SatSolver.NOT_CONFIGURED else ()
  1001 		val inpath     = File.tmp_path (Path.unpack "isabelle.cnf")
  1002 		val outpath    = File.tmp_path (Path.unpack "result")
  1003 		val cmd        = (getenv "JERUSAT_HOME") ^ "/Jerusat1.3 " ^ (Path.pack inpath) ^ " > " ^ (Path.pack outpath)
  1004 		fun writefn fm = SatSolver.write_dimacs_cnf_file inpath (PropLogic.defcnf fm)
  1005 		fun readfn ()  = SatSolver.read_std_result_file outpath ("s SATISFIABLE", "v ", "s UNSATISFIABLE")
  1006 		val _          = if File.exists inpath then warning ("overwriting existing file " ^ quote (Path.pack inpath)) else ()
  1007 		val _          = if File.exists outpath then warning ("overwriting existing file " ^ quote (Path.pack outpath)) else ()
  1008 		val result     = SatSolver.make_external_solver cmd writefn readfn fm
  1009 		val _          = try File.rm inpath
  1010 		val _          = try File.rm outpath
  1011 	in
  1012 		result
  1013 	end
  1014 in
  1015 	SatSolver.add_solver ("jerusat", jerusat)
  1016 end;
  1017 
  1018 (* ------------------------------------------------------------------------- *)
  1019 (* Add code for other SAT solvers below.                                     *)
  1020 (* ------------------------------------------------------------------------- *)
  1021 
  1022 (*
  1023 let
  1024 	fun mysolver fm = ...
  1025 in
  1026 	SatSolver.add_solver ("myname", (fn fm => if mysolver_is_configured then mysolver fm else raise SatSolver.NOT_CONFIGURED));  -- register the solver
  1027 end;
  1028 
  1029 -- the solver is now available as SatSolver.invoke_solver "myname"
  1030 *)