1 % (c) 2019-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(cdclt_solver, [cdcl_sat_solve_predicate/2,
6 cdcl_sat_solve_predicate_in_state/3,
7 cdclt_solve_predicate/3,
8 cdclt_solve_predicate/4,
9 cdclt_solve_predicate_in_state/4,
10 cdclt_solve_predicate_in_state/5,
11 get_amount_of_sat_variables/2,
12 add_bindings_for_typed_ids/3]).
13
14 :- use_module(library(lists)).
15 :- use_module(library(timeout)).
16 :- use_module(library(sets), [subtract/3,add_element/3]).
17 :- use_module(library(clpfd), [fd_var/1, fd_min/2, fd_max/2]).
18
19 :- use_module(smt_solvers_interface(ast_optimizer_for_smt)).
20
21 :- use_module(cdclt_solver('symmetry_check/smt_symmetry_breaking')).
22 :- use_module(cdclt_solver('cdclt_stats')).
23 :- use_module(cdclt_solver('cdclt_preprocessing')).
24 :- use_module(cdclt_solver('cdclt_pred_to_sat')).
25 :- use_module(cdclt_solver('cdclt_sat_solver')).
26 :- use_module(cdclt_solver('difference_logic/difference_logic_solver')).
27 :- use_module(cdclt_solver('difference_logic/ast_to_difference_logic')).
28 :- use_module(cdclt_solver('cdclt_settings')).
29
30 :- use_module(probsrc(debug)).
31 :- use_module(probsrc(tools), [ajoin/2]).
32 :- use_module(probsrc(b_ast_cleanup), [clean_up_pred/3]).
33 :- use_module(probsrc(preferences), [get_preference/2,
34 temporary_set_preference/2,
35 reset_temporary_preference/1]).
36 :- use_module(probsrc(bmachine), [b_get_machine_variables/1,b_get_machine_constants/1]).
37 :- use_module(probsrc(b_global_sets), [list_contains_unfixed_deferred_set_id/1]).
38 :- use_module(probsrc(b_compiler), [b_compile/6]).
39 :- use_module(probsrc(b_enumerate), [b_tighter_enumerate_all_values/2]).
40 :- use_module(probsrc(tools_meta), [safe_time_out/3]).
41 :- use_module(probsrc(translate), [print_bexpr/1]).
42 :- use_module(probsrc(tools_platform), [host_platform/1]).
43 :- use_module(probsrc(tools), [start_ms_timer/1,stop_ms_timer_with_debug_msg/2]).
44 :- use_module(probsrc(kernel_waitflags), [init_wait_flags/2,ground_wait_flags/1]).
45 :- use_module(probsrc(kernel_objects), [infer_value_type/2,contains_any/1]).
46 :- use_module(probsrc(b_interpreter), [set_up_typed_localstate/6,
47 b_test_boolean_expression/4,
48 b_convert_bool_timeout/7]).
49 :- use_module(probsrc(error_manager), [error_occurred_in_error_scope/0,
50 add_error/3,
51 add_error_and_fail/3,
52 add_internal_error/2,
53 add_message/3,
54 add_message/4,
55 check_error_occured/2,
56 enter_new_error_scope/2,
57 exit_error_scope/3,
58 clear_enumeration_warnings/0,
59 clear_wd_errors/0,
60 critical_enumeration_warning_occured_in_error_scope/4]).
61 :- use_module(probsrc(bsyntaxtree), [find_typed_identifier_uses/2,
62 find_typed_identifier_uses/3,
63 find_identifier_uses/3,
64 check_ast/1,
65 get_texpr_info/2,
66 conjunct_predicates/2,
67 safe_create_texpr/4]).
68 %:- use_module(probsrc('well_def/well_def_analyser'), [analyse_wd_for_expr/3]).
69 %:- use_module(probsrc('debug'), [set_silent_mode/1]).
70 :- use_module(probsrc(module_information), [module_info/2]).
71 :- use_module(probsrc(typing_tools), [any_value_for_type/2]).
72 :- use_module(extension('banditfuzz/welldef')).
73
74 :- module_info(group, cdclt).
75 :- module_info(description,'This module provides a CDCL(T) based solver for B.').
76
77 :- dynamic initial_solution/0, unfixed_deferred_set_error_after_grounding/0, unfixed_deferred_set_has_been_propagated/0, solve_in_state/0, idl_candidate_constants/2, grounding_timeout_occurred/0, grounding_fallback_z3/0, additional_z3_reification/0.
78
79 %% Use a small timeout for grounding with ProB and fall back to Z3 if time limit exceeded.
80 grounding_fallback_z3.
81 % Additionally reify constraints with Z3 using the incremental solver.
82 %additional_z3_reification.
83
84 debug_format_cdclt(_, _) :-
85 print_logs(false),
86 !.
87 debug_format_cdclt(Msg, Vars) :-
88 append(Msg, " (CDCL(T) Solver)~n", NCodes),
89 format(NCodes, Vars), !.
90
91 debug_format_cdclt(_, _, _) :-
92 print_logs(false),
93 !.
94 debug_format_cdclt(Msg, Vars, Pred) :-
95 format(Msg, Vars),
96 translate:print_bexpr(Pred), nl, !.
97
98 init :-
99 % enumeration has to be linear for symmetry breaking but also set to false by default
100 temporary_set_preference(randomise_enumeration_order, false),
101 cdclt_pred_to_sat:reset_sat_var_id,
102 cdclt_preprocessing:reset_artificial_id_counter,
103 cdclt_sat_solver:reset_cdclt_sat_solver,
104 reset_stats,
105 ( additional_z3_reification
106 -> smt_solvers_interface:reset_smt_supported_interpreter
107 ; true
108 ),
109 welldef:filter_typing_pos(true),
110 welldef:preprocess_pos_for_cdclt(true),
111 retractall(initial_solution),
112 retractall(grounding_timeout_occurred),
113 retractall(unfixed_deferred_set_error_after_grounding),
114 retractall(unfixed_deferred_set_has_been_propagated),
115 retractall(solve_in_state),
116 retractall(idl_candidate_constants(_,_)),
117 %temporary_set_preference(use_chr_solver, true),
118 temporary_set_preference(unsat_core_algorithm, divide_and_conquer), % default is linear_greedy
119 temporary_set_preference(allow_improving_wd_mode, true),
120 %temporary_set_preference(solver_strength, 20000),
121 temporary_set_preference(use_smt_mode, false),
122 temporary_set_preference(use_clpfd_solver, true),
123 temporary_set_preference(optimize_ast, true),
124 temporary_set_preference(use_common_subexpression_elimination, false),
125 temporary_set_preference(add_wd_pos_for_z3, false),
126 temporary_set_preference(normalize_ast_sort_commutative, false),
127 temporary_set_preference(normalize_ast, false).
128
129 reset_preferences :-
130 reset_temporary_preference(randomise_enumeration_order),
131 %reset_temporary_preference(solver_strength),
132 reset_temporary_preference(unsat_core_algorithm),
133 reset_temporary_preference(allow_improving_wd_mode),
134 reset_temporary_preference(use_smt_mode),
135 reset_temporary_preference(use_clpfd_solver),
136 reset_temporary_preference(optimize_ast),
137 reset_temporary_preference(use_common_subexpression_elimination),
138 reset_temporary_preference(add_wd_pos_for_z3),
139 reset_temporary_preference(normalize_ast_sort_commutative),
140 reset_temporary_preference(normalize_ast).
141
142 set_current_state(Pred, TypedIds, State, NPred) :-
143 reset_optimizer_state,
144 assert_state_id_values(TypedIds, State),
145 replace_ids_with_ground_values(Pred, 0, [], NPred),
146 reset_optimizer_state, !.
147
148 %% cdcl_sat_solve_predicate_in_state(+BoolFormula, +State, -Result).
149 cdcl_sat_solve_predicate_in_state(BoolFormula, State, Result) :-
150 include(ground_state_binding, State, GState),
151 get_typed_ids_in_scope_of_pred(BoolFormula, TypedIds),
152 set_current_state(BoolFormula, TypedIds, GState, NPred),
153 get_equalities_from_bindings(GState, TypedIds, EqConj),
154 safe_create_texpr(conjunct(EqConj,NPred), pred, [], Conj),
155 cdcl_sat_solve_predicate(Conj, Result).
156
157 %% cdcl_sat_solve_predicate(+BoolFormula, -Result).
158 % Pure SAT solving without theories.
159 cdcl_sat_solve_predicate(BoolFormula, Result) :-
160 init,
161 get_preference(time_out, Timeout),
162 safe_time_out(cdcl_sat_solve_predicate_no_timeout(BoolFormula, TResult),
163 Timeout,
164 TimeoutResult),
165 ( TimeoutResult == time_out
166 -> Result = time_out
167 ; Result = TResult
168 ).
169
170 analyze_binary_clauses(Clauses, VarsFromBinaryClauses) :-
171 analyze_binary_clauses(Clauses, 0, 0, [], VarsFromBinaryClauses).
172
173 analyze_binary_clauses([], Len, Binary, Acc, Acc) :-
174 debug_format_cdclt("Found ~w clauses ~w of which are binary clauses~n", [Len,Binary]).
175 analyze_binary_clauses([[_-_-_-N1,_-_-_-N2]|T], Len, Binary, Acc, VarsFromBinaryClauses) :-
176 !,
177 add_element(N1, Acc, NAcc1),
178 add_element(N2, NAcc1, NAcc),
179 Len1 is Len + 1,
180 Binary1 is Binary + 1,
181 analyze_binary_clauses(T, Len1, Binary1, NAcc, VarsFromBinaryClauses).
182 analyze_binary_clauses([_|T], Len, Binary, Acc, VarsFromBinaryClauses) :-
183 Len1 is Len + 1,
184 analyze_binary_clauses(T, Len1, Binary, Acc, VarsFromBinaryClauses).
185
186 cdcl_sat_solve_predicate_no_timeout(BoolFormula, Result) :-
187 find_typed_identifier_uses(BoolFormula, [], SatVars),
188 % rewriting similar to Tseitin
189 optimize_clause_size_by_rewriting(BoolFormula, SatVars, TOptBoolFormula, NewSatVars, NewVarConjList),
190 conjunct_predicates(NewVarConjList, NewVarConj),
191 % add new top-level Boolean variables introduced by Tseitin rewriting
192 conjunct_predicates([NewVarConj,TOptBoolFormula], FullBoolFormula),
193 get_bindings_from_ids(NewSatVars, StackBindings, SatBindings, SatVarNames, _IdPrologVarTuples, PrologSatVarTriple),
194 b_to_cnf_safe(FullBoolFormula, StackBindings, CnfBoolFormula),
195 analyze_binary_clauses(CnfBoolFormula, VarsFromBinaryClauses),
196 cdclt_sat_solver:create_solver_state(SatStateMutable),
197 SolverEnv = [sat_vars:NewSatVars,sat_varnames:SatVarNames,sat_bindings:SatBindings,t2b_env:_,pl_vars:PrologSatVarTriple,binary_clause_vars:VarsFromBinaryClauses],
198 ( ( cdclt_sat_solver:unit_propagate_cnf(SolverEnv, SatStateMutable, CnfBoolFormula, TCnfBoolFormula2),
199 remove_subsumed_clauses(TCnfBoolFormula2, TCnfBoolFormula3),
200 sort(TCnfBoolFormula3, CnfBoolFormula2),
201 cdclt_sat_solver:sat(default_sat, SolverEnv, SatStateMutable, CnfBoolFormula2)
202 )
203 -> Result = solution(SatBindings)
204 ; Result = contradiction_found
205 ),
206 print_stats.
207
208 %% cdclt_solve_predicate(+Pred, -SolvedPred, -Result).
209 % Main interface predicate for CDCL(T) based solver which times out
210 % with respect to ProB's time_out preference.
211 cdclt_solve_predicate(Pred, SolvedPred, Result) :-
212 cdclt_solve_predicate(default, Pred, SolvedPred, Result).
213
214 %% cdclt_solve_predicate(+SolverName, +Pred, -SolvedPred, -Result).
215 cdclt_solve_predicate(SolverName, Pred, SolvedPred, Result) :-
216 init,
217 cdclt_solve_predicate_timeout(SolverName, Pred, SolvedPred, Result).
218
219 %% cdclt_solve_predicate_in_state(+Pred, +Pred, -Result).
220 cdclt_solve_predicate_in_state(Pred, State, SolvedPred, Result) :-
221 cdclt_solve_predicate_in_state(default, Pred, State, SolvedPred, Result).
222
223 %% cdclt_solve_predicate_in_state(+SolverName, +Pred, +Pred, -Result).
224 cdclt_solve_predicate_in_state(SolverName, Pred, State, SolvedPred, Result) :-
225 init,
226 include(ground_state_binding, State, GState),
227 get_typed_ids_in_scope_of_pred(Pred, TypedIds),
228 set_current_state(Pred, TypedIds, GState, NPred),
229 get_equalities_from_bindings(GState, TypedIds, EqConj),
230 safe_create_texpr(conjunct(EqConj,NPred), pred, [], Conj),
231 asserta(solve_in_state),
232 cdclt_solve_predicate_timeout(SolverName, Conj, SolvedPred, Result).
233
234 cdclt_solve_predicate_timeout(SolverName, Pred, SolvedPred, Result) :-
235 get_preference(time_out, Timeout),
236 safe_time_out(cdclt_solve_predicate_initialized(SolverName, Pred, TSolvedPred, SolverResult),
237 Timeout,
238 TimeoutResult),
239 ( TimeoutResult == time_out
240 -> Result = time_out,
241 SolvedPred = Pred
242 ; ground(SolverResult),
243 Result = SolverResult,
244 SolvedPred = TSolvedPred
245 ).
246
247 %% add_bindings_for_typed_ids(+TypedIds, +SolverResult, -Result).
248 % Callers which know the identifiers to be solved for (e.g., the constants of a machine) use this
249 % for identifiers whose constraints were already removed before calling the solver (e.g., PROPERTIES e:BOOL):
250 % they have no binding in the solution and are bound to an arbitrary value of their type.
251 % Note: TypedIds must not contain identifiers whose values come from a state (see cdclt_solve_predicate_in_state).
252 add_bindings_for_typed_ids(TIds, solution(Bindings), Result) :-
253 !,
254 findall(bind(Id,Val),
255 ( member(b(identifier(Id),Type,_), TIds),
256 \+ memberchk(bind(Id,_), Bindings),
257 any_value_for_type(Type, Val)
258 ), MissingBindings),
259 append(Bindings, MissingBindings, AllBindings),
260 Result = solution(AllBindings).
261 add_bindings_for_typed_ids(_, Result, Result).
262
263 cdclt_solve_predicate_initialized(SolverName, Pred, SolvedPred, Result) :-
264 ( check_ast(Pred)
265 -> ( (error_occurred_in_error_scope, check_error_occured(check_ast_typing, _))
266 -> % input AST is not correctly typed
267 SolvedPred = Pred,
268 Result = error
269 ; cdclt_solve_predicate_initialized_checked(SolverName, Pred, SolvedPred, Result)
270 )
271 ; add_message(cdclt_solve_predicate_no_timeout, 'Input predicate is not well-defined~nProB\'s SMT solver transforms the input to a well-defined predicate before constraint solving~nFor: ',SolverName),
272 cdclt_solve_predicate_initialized_checked(SolverName, Pred, SolvedPred, Result)
273 ).
274
275 cdclt_solve_predicate_initialized_checked(SolverName, Pred, SolvedPred, Result) :-
276 call_cleanup(catch(cdclt_solve_predicate_no_timeout(SolverName, Pred, SolvedPred, Result),
277 Exception, % TO DO: catch specific exception instead of all
278 handle_clpfd_overflow(SolverName, Exception, Pred, SolvedPred, Result)
279 ),
280 reset_preferences
281 ).
282
283 %% handle_clpfd_overflow(+SolverName, +Exception, +Pred, -SolvedPred, -Result).
284 % Disable CLP(FD) interface and restart CDCL(T) if an overflow occurred.
285 handle_clpfd_overflow(SolverName, Exception, Pred, SolvedPred, Result) :-
286 Exception = error(representation_error(Err),_),
287 memberchk(Err, ['CLPFD integer overflow','max_clpfd_integer','min_clpfd_integer']),
288 !,
289 debug_format_cdclt("Handle CLP(FD) overflow error and restart CDCL(T) without CLP(FD).", []),
290 temporary_set_preference(use_clpfd_solver, false),
291 cdclt_solve_predicate_initialized(SolverName, Pred, SolvedPred, Result).
292 handle_clpfd_overflow(SolverName, Exception, Pred, SolvedPred, unknown) :-
293 ajoin(['Exception occured during solving with ',SolverName,':'],Msg),
294 add_error(cdclt,Msg,Exception),
295 SolvedPred = Pred.
296
297 %% cdclt_solve_predicate(+SolverName, +Pred, -SolvedPred, -SolverResult).
298 % Interface predicate for CDCL(T) based solver without a timeout.
299 cdclt_solve_predicate_no_timeout(SolverName, Pred, SolvedPred, SolverResult) :-
300 debug_format_cdclt("Parsed predicate: ", [], Pred),
301 debug_format_cdclt("Start preprocessing", []),
302 cdclt_solve_predicate_no_timeout_cleanup(SolverName, Pred, NPred),
303 debug_format_cdclt("After preprocessing: ", [], NPred),
304 cdclt_solve_predicate_no_timeout_clean(SolverName, NPred, SolvedPred, SolverResult).
305
306 cdclt_solve_predicate_no_timeout_clean(_, b(truth,pred,Info), SolvedPred, SolverResult) :-
307 !,
308 SolvedPred = b(truth,pred,Info),
309 SolverResult = solution([]).
310 cdclt_solve_predicate_no_timeout_clean(_, b(falsity,pred,Info), SolvedPred, SolverResult) :-
311 !,
312 SolvedPred = b(falsity,pred,Info),
313 SolverResult = contradiction_found.
314 cdclt_solve_predicate_no_timeout_clean(SolverName, CleanPred, SolvedPred, SolverResult) :-
315 cdclt_solve_predicate_no_timeout_setup(SolverName, CleanPred, Env, SmtVars, SatVars, WDPosBoolFormula, AnalysisBoolFormula, SmtBoolFormula),
316 cdclt_sat_solver:cnf_to_smt(SmtBoolFormula, SolvedPred),
317 start_ms_timer(Timer),
318 enter_new_error_scope(ScopeID, cdclt_solve_predicate),
319 call_cleanup(conflict_driven_clause_learning_online(SolverName, Env, SmtVars, SatVars, WDPosBoolFormula, AnalysisBoolFormula, SmtBoolFormula, SolverResult),
320 exit_error_scope(ScopeID, _, cdclt_solve_predicate)),
321 functor(SolverResult,SR,_),
322 stop_ms_timer_with_debug_msg(Timer, cdclt_solving_success(SR)),
323 print_stats.
324
325 %% cdclt_solve_predicate_no_timeout_cleanup(+SolverName, +Pred, -NPred).
326 % Some rewriting and cleanup for CDCL(T).
327 cdclt_solve_predicate_no_timeout_cleanup(SolverName, Pred, NPred) :-
328 start_ms_timer(Timer0),
329 simplify_negation(Pred, SPred),
330 debug_format_cdclt("After simplifying negations: ", [], SPred),
331 reset_optimizer_state,
332 assert_ground_id_values(0, SPred),
333 replace_ids_with_ground_values(SPred, 0, [], AstOpt),
334 precompute_values_non_recursive([instantiate_quantifier_limit(0),instantiate_sets_limit(1000)], AstOpt, AstPrecomputed),
335 debug_format_cdclt("After precomputing values: ", [], AstOpt),
336 stop_ms_timer_with_debug_msg(Timer0, precompute_values_for_cdclt),
337 find_identifier_uses(AstPrecomputed, [], UsedIds),
338 temporary_set_preference(data_validation_mode, true),
339 catch(b_compile(AstPrecomputed, UsedIds, [], [], AstCompiled, no_wf_available),
340 enumeration_warning(_,_,_,_,_), % cancel if enumeration warning has occurred
341 AstCompiled = AstPrecomputed),
342 clear_wd_errors, % b_compile might throw a wd error
343 reset_temporary_preference(data_validation_mode),
344 debug_format_cdclt("After compiling values (used ids ~w): ", [UsedIds], AstCompiled),
345 start_ms_timer(Timer2),
346 ( clean_up_pred(AstCompiled, _, NPred)
347 -> true
348 ; add_internal_error('Clean up failed ',SolverName),
349 NPred = AstCompiled
350 ),
351 stop_ms_timer_with_debug_msg(Timer2, clean_up_pred_for_cdclt).
352
353 %% cdclt_solve_predicate_no_timeout_setup(+SolverName, +CleanPred, -Env, -SmtVars, -SatVars, -WDPosBoolFormula, -AnalysisBoolFormula, -SmtBoolFormula).
354 cdclt_solve_predicate_no_timeout_setup(SolverName, CleanPred, Env, SmtVars, SatVars, WDPosBoolFormula, AnalysisBoolFormula, SmtBoolFormula) :-
355 start_ms_timer(Timer),
356 cdclt_settings:static_syntax_analysis(PerformStaticAnalysis),
357 is_rewrite_to_idl(RewriteToIdl),
358 add_symmetry_breaking_predicates_cond(CleanPred, CleanPredSym),
359 preprocess_predicate(PerformStaticAnalysis, RewriteToIdl, CleanPredSym, LiftedPred, InferredImplsConj, CandidateImpls),
360 log_inferred_implications(InferredImplsConj),
361 debug_format_cdclt("Lifted predicate: ", [], LiftedPred),
362 predicate_to_sat(normal_make_wd, LiftedPred, Env1, WDPOs1, SmtBoolFormula, SatVars1), !,
363 ( PerformStaticAnalysis == true
364 -> predicate_to_sat(only_reuse, WDPOs1, SatVars1, Env1, InferredImplsConj, Env3, WDPOsList, ImplBoolFormula, SatVars3),
365 debug_format_cdclt("Static analysis inferred: ", [], ImplBoolFormula)
366 ; ImplBoolFormula = b(truth,pred,[]),
367 SatVars3 = SatVars1, Env3 = Env1, WDPOsList = WDPOs1
368 ),
369 % well-definedness implication on the top-level to encode well-definedness in the SAT solver
370 conjunct_predicates(WDPOsList, WDPOs),
371 preprocess_predicate(false, RewriteToIdl, WDPOs, LiftedWDPOs, _, WDCandidateImpls),
372 % theory deduction for wd
373 get_wd_theory_implications(CandidateImpls, WDCandidateImpls, WDTheoryImpls),
374 log_inferred_wd_theory_implications(InferredImplsConj),
375 predicate_to_sat(normal_make_wd, [], SatVars3, Env3, WDTheoryImpls, Env4, _, WDTheoryImplsBoolFormula, SatVars4),
376 debug_format_cdclt("WD Theory Deduction Implications: ", [], WDTheoryImpls),
377 predicate_to_sat(normal_make_wd, [], SatVars4, Env4, LiftedWDPOs, Env5, WDPOsList2, WDPosBoolFormula1, SatVars5),
378 % there can be WD POs that also have WD POs
379 conjunct_predicates(WDPOsList2, WDPOs2),
380 preprocess_predicate(false, RewriteToIdl, WDPOs2, LiftedWDPOs2, _, _),
381 predicate_to_sat(normal_make_wd, [], SatVars5, Env5, LiftedWDPOs2, Env, _, WDPosBoolFormula2, SatVars),
382 conjunct_predicates([WDPosBoolFormula1,WDPosBoolFormula2], WDPosBoolFormula),
383 ( SatVars3 \== SatVars
384 -> %set_silent_mode(on),
385 %analyse_wd_for_expr(CleanPred, _ResStr, _IsWd), % prints missing WD conditions
386 %set_silent_mode(off),
387 add_message(cdclt_solve_predicate_no_timeout_setup, 'Input not well-defined: automatically added WD POs for solver ',SolverName)
388 ; true
389 ),
390 debug_format_cdclt("WD Implication: ", [], LiftedWDPOs),
391 debug_format_cdclt("WD Implication as Boolean formula: ", [], WDPosBoolFormula),
392 !,
393 conjunct_predicates([WDTheoryImplsBoolFormula,ImplBoolFormula], AnalysisBoolFormula),
394 find_typed_identifier_uses(LiftedPred, SmtVars), % no global sets or constants are considered here
395 debug_format_cdclt("Check LiftedPred", []),
396 ( check_ast(LiftedPred)
397 -> true
398 ; add_internal_error('AST is missing well-definedness information for solver ', SolverName)
399 ),
400 %translate:nested_print_bexpr(LiftedPred),nl,
401 stop_ms_timer_with_debug_msg(Timer, preprocessing_for_cdclt),
402 debug_format_cdclt("End preprocessing", []),
403 !.
404 cdclt_solve_predicate_no_timeout_setup(_, Pred, _, _, _, _, _, _) :-
405 add_error_and_fail(cdclt_solve_predicate, 'Cannot create SAT formula from B predicate:', [Pred]).
406
407 %% add_symmetry_breaking_predicates_cond(+Pred, -SymPred).
408 add_symmetry_breaking_predicates_cond(Pred, SymPred) :-
409 cdclt_settings:static_smt_symmetry_breaking(true),
410 !,
411 debug_format_cdclt("Start symmetry breaking..", []),
412 ( add_symmetry_breaking_predicates(Pred, SymPred),
413 get_amount_of_found_sbps(FoundSBPs),
414 log_symmetry_breaking_stats(FoundSBPs),
415 debug_format_cdclt("done.", [])
416 -> true
417 ; add_message(smt_symmetry_breaking, 'Symmetry breaking failed for: ',Pred),
418 SymPred = Pred
419 ).
420 add_symmetry_breaking_predicates_cond(Pred, Pred).
421
422 is_rewrite_to_idl(Res) :-
423 get_preference(cdclt_use_idl_theory_solver,true),
424 !,
425 Res = true.
426 is_rewrite_to_idl(false).
427
428 %% conflict_driven_clause_learning_online(+SolverName, +Env, +SmtVars, +SatVars, +WDPosBoolFormula, +AnalysisBoolFormula, +BoolFormula, -SolverResult).
429 % Conflict-driven clause learning from incomplete assignments of the boolean formula by setting up reification constraints (b_interpreter:b_convert_bool_timeout/7)
430 % connecting the SAT and theory solver. IDL constraint solver uses custom coroutines for the reification (cdclt_solver:idl_solver_interface/3).
431 conflict_driven_clause_learning_online(_, _, _, _, _, _, b(truth,pred,_), SolverResult) :-
432 !,
433 SolverResult = solution([]).
434 conflict_driven_clause_learning_online(_, _, _, _, _, _, b(falsity,pred,_), SolverResult) :-
435 !,
436 debug_format_cdclt("contradiction_found: falsity derived",[]),
437 SolverResult = contradiction_found.
438 conflict_driven_clause_learning_online(SolverName, Env, SmtVars, SatVars, WDPosBoolFormula, AnalysisBoolFormula, BoolFormula, SolverResult) :-
439 % rewriting similar to Tseitin
440 optimize_clause_size_by_rewriting(BoolFormula, SatVars, TOptBoolFormula, NewSatVars, NewVarConjList),
441 conjunct_predicates(NewVarConjList, NewVarConj),
442 conjunct_predicates([AnalysisBoolFormula,TOptBoolFormula], TFullBoolFormula),
443 % add new top-level Boolean variables introduced by Tseitin rewriting
444 ( NewVarConj = b(truth,pred,_)
445 -> FullBoolFormula = TFullBoolFormula
446 ; safe_create_texpr(conjunct(NewVarConj,TFullBoolFormula), pred, [], FullBoolFormula)
447 ),
448 get_bindings_from_ids(NewSatVars, StackBindings, SatBindings, SatVarNames, IdPrologVarTuples, PlVars),
449 b_to_cnf_safe(FullBoolFormula, StackBindings, CnfBoolFormula),
450 setup_theory_wf_store(SmtVars, SmtBindings, WfStoreSmt),
451 ( get_preference(cdclt_use_idl_theory_solver,true)
452 -> difference_logic_solver:init_idl_solver(IdlGraphMut)
453 ; true
454 ),
455 ( WDPosBoolFormula \= b(truth,pred,_)
456 -> % add WD PO implications
457 b_to_cnf_safe(WDPosBoolFormula, StackBindings, CnfWDPosBoolFormula),
458 append(CnfWDPosBoolFormula, CnfBoolFormula, TNCnfBoolFormula)
459 ; TNCnfBoolFormula = CnfBoolFormula
460 ),
461 cdclt_sat_solver:create_solver_state(SatStateMutable),
462 SolverEnv = [sat_vars:NewSatVars,sat_varnames:SatVarNames,sat_bindings:SatBindings,t2b_env:Env,pl_vars:PlVars],
463 log_unique_predicates(SatVarNames),
464 cdclt_sat_solver:unit_propagate_cnf(SolverEnv, SatStateMutable, TNCnfBoolFormula, TNCnfBoolFormula2),
465 remove_subsumed_clauses(TNCnfBoolFormula2, TNCnfBoolFormula3),
466 sort(TNCnfBoolFormula3, NCnfBoolFormula),
467 ( debug_mode(off)
468 -> true
469 ; cdclt_sat_solver:portray_cnf(NCnfBoolFormula)
470 ),
471 analyze_binary_clauses(CnfBoolFormula, VarsFromBinaryClauses),
472 NSolverEnv = [sat_vars:NewSatVars,sat_varnames:SatVarNames,sat_bindings:SatBindings,t2b_env:Env,pl_vars:PlVars,binary_clause_vars:VarsFromBinaryClauses],
473 setup_reification(SatStateMutable, IdlGraphMut, IdPrologVarTuples, SmtBindings, WfStoreSmt),
474 cdclt_sat_solver:sat(SolverName, NSolverEnv, SatStateMutable, NCnfBoolFormula, [allow_partial_model]),
475 retractall(unfixed_deferred_set_error_after_grounding),
476 cdclt_sat_solver:clear_pending_theory_propagations,
477 ( severe_error_occurred
478 -> % error occurred during SAT solving
479 !,
480 SolverResult = error
481 ; debug_format_cdclt("Ground waitflags", []),
482 remove_pending_theory_propagations_on_bt,
483 ( conflict_driven_clause_learning_online_grounding(IdlGraphMut, SmtVars, PlVars, SmtBindings, WfStoreSmt, SolverResult)
484 -> true
485 ; ( unfixed_deferred_set_has_been_propagated
486 -> % a contradiction has been found but at least one unfixed deferred set has been propagated
487 % we thus do not know if it's a genuine contradiction
488 asserta(unfixed_deferred_set_error_after_grounding),
489 fail
490 ; % this is a genuine contradiction after grounding
491 fail
492 )
493 )
494 ).
495 conflict_driven_clause_learning_online(_, _, _, _, _, _, _, Res) :-
496 \+ wd_error_occurred_in_error_scope(_),
497 critical_enumeration_warning_occured_in_error_scope(A, B, C, D),
498 !,
499 clear_enumeration_warnings,
500 debug_format_cdclt("no_solution_found: Enumeration warning occurred",[]),
501 Res = no_solution_found(enumeration_warning(A,B,C,D,critical)).
502 conflict_driven_clause_learning_online(_, _, _, _, _, _, _, Res) :-
503 severe_error_occurred,
504 !,
505 Res = error.
506 conflict_driven_clause_learning_online(_, _, _, _, _, _, _, error) :-
507 \+ initial_solution,
508 wd_error_occurred_in_error_scope(Reason),
509 add_error(well_definedness_error, Reason, 'conflict_driven_clause_learning_online').
510 conflict_driven_clause_learning_online(_, _, _, _, _, _, _, Res) :-
511 ( grounding_timeout_occurred
512 -> debug_format_cdclt("no_solution_found: grounding timeout occurred",[])
513 ; cdclt_sat_solver:assignment_timeout_occurred
514 -> debug_format_cdclt("no_solution_found: assignment timeout occurred",[])
515 ),
516 !,
517 Res = no_solution_found(solver_answered_unknown).
518 conflict_driven_clause_learning_online(_, _, _, _, _, _, _, no_solution_found(unfixed_deferred_sets)) :-
519 \+ solve_in_state,
520 ( cdclt_sat_solver:unfixed_deferred_set_error_occurred
521 ; unfixed_deferred_set_error_after_grounding
522 ; unfixed_deferred_set_has_been_propagated
523 ), debug_format_cdclt("no_solution_found: unfixed_deferred_sets",[]).
524 conflict_driven_clause_learning_online(_, _, _, _, _, _, _, contradiction_found) :-
525 \+ initial_solution,
526 ( solve_in_state
527 -> true
528 ; \+ unfixed_deferred_set_error_after_grounding,
529 \+ cdclt_sat_solver:unfixed_deferred_set_error_occurred,
530 \+ unfixed_deferred_set_has_been_propagated
531 ),
532 \+ wd_error_occurred_in_error_scope(_),
533 debug_format_cdclt("contradiction_found in conflict_driven_clause_learning_online",[]).
534
535 % Backtracking after grounding: We have either found a solution or a conflict.
536 % If a conflict has been found, it can be a theory conflict in the SAT solver
537 % (pending props have already been used for CDCL) or we just backtrack to the last decision.
538 % In all cases, remove all pending theory propagations now.
539 remove_pending_theory_propagations_on_bt :-
540 ( true
541 ; cdclt_sat_solver:clear_pending_theory_propagations,
542 debug_format_cdclt("backtrack after grounding waitflags", []),
543 fail
544 ).
545
546 :- use_module(smt_solvers_interface(smt_solvers_interface)).
547
548 %% conflict_driven_clause_learning_online_grounding(+IdlGraphMut, +SmtVars, +PlVars, +SmtBindings, +WfStoreSmt, -SolverResult).
549 % Use IDL theory solver if option is set and enter ProB's grounding phase.
550 conflict_driven_clause_learning_online_grounding(IdlGraphMut, SmtVars, _, SmtBindings, WfStoreSmt, SolverResult) :-
551 get_preference(cdclt_use_idl_theory_solver, true),
552 !,
553 add_typed_ids_in_scope(SmtVars, StateTypedIds),
554 propagate_fd_bounds_to_idl_solver(IdlGraphMut, SmtBindings),
555 get_idl_solution_bindings(IdlGraphMut, IdlBindings),
556 ( % try one idl solution first since ProB could timeout, but do not enumerate idl solutions here
557 set_bindings(IdlBindings, SmtBindings),
558 ground_wait_flags(WfStoreSmt)
559 ; exclude_idl_solution(IdlBindings, SmtBindings, StateTypedIds, WfStoreSmt),
560 ( ground_wait_flags(WfStoreSmt)
561 ; % fallback to idl solver and possibly enumerate all solutions
562 critical_enumeration_warning_occured_in_error_scope(_, _, _, _),
563 clear_enumeration_warnings,
564 propagate_idl_solution_to_bindings_bt(IdlGraphMut, SmtBindings),
565 ground_wait_flags(WfStoreSmt)
566 )
567 ),
568 finalize_smt_solution(SmtBindings, SolverResult).
569 conflict_driven_clause_learning_online_grounding(_, _, PlVars, SmtBindings, WfStoreSmt, SolverResult) :-
570 grounding_fallback_z3,
571 \+ host_platform(windows),
572 !,
573 ( grounding_timeout_occurred
574 -> % use a smaller time limit if a timeout already occurred
575 GroundTimeout = 5000
576 ; GroundTimeout = 30000
577 ),
578 safe_time_out(ground_wait_flags(WfStoreSmt),
579 GroundTimeout,
580 TimeOutRes),
581 ( TimeOutRes == time_out
582 -> debug_format_cdclt("Timeout when grounding with ProB. Fallback to Z3.", []),
583 sat_bindings_to_smt_formula(PlVars, SmtFormula),
584 safe_time_out(smt_solve_predicate(z3, [check_sat_skeleton(0)], SmtFormula, _, Result),
585 10000,
586 TimeOutResZ3),
587 ( ( TimeOutResZ3 == time_out
588 ; Result = no_solution_found(_)
589 )
590 -> asserta(grounding_timeout_occurred),
591 fail
592 ; Result = solution(NSmtBindings),
593 debug_format_cdclt("Validating Z3 solution with ProB.", []),
594 copy_smt_solution(SmtBindings,NSmtBindings),
595 ground_wait_flags(WfStoreSmt) % also avoid Call Residue warnings
596 )
597 ; NSmtBindings = SmtBindings
598 ),
599 \+ severe_error_occurred,
600 finalize_smt_solution(NSmtBindings, SolverResult).
601 conflict_driven_clause_learning_online_grounding(_, _, _, SmtBindings, WfStoreSmt, SolverResult) :-
602 ground_wait_flags(WfStoreSmt),
603 \+ severe_error_occurred,
604 finalize_smt_solution(SmtBindings, SolverResult).
605
606 :- use_module(probsrc(kernel_objects),[equal_object/3]).
607 copy_smt_solution([],_).
608 copy_smt_solution([bind(ID,Val)|T],NSmtBindings) :- member(binding(ID,Z3Val,_),NSmtBindings),!,
609 equal_object(Val,Z3Val,copy_smt_solution),
610 copy_smt_solution(T,NSmtBindings).
611 copy_smt_solution([H|T],NSmtBindings) :- add_internal_error('No SMT solution for:',H),
612 copy_smt_solution(T,NSmtBindings).
613
614 finalize_smt_solution(SmtBindings, SolverResult) :-
615 SolverResult = solution(SmtBindings),
616 log_solution,
617 announce_bt_from_smt_solution.
618
619 wd_error_occurred_in_error_scope(Reason) :-
620 error_occurred_in_error_scope,
621 check_error_occured(well_definedness_error, Reason).
622
623 %% setup_reification(+SatStateMutable, +IdlGraphMut, +IdPrologVarTuples, +SmtBindings, +WfStoreSmt).
624 % Set up reification constraints to connect SAT and SMT solver.
625 % Propagates in both directions (b_convert_bool_timeout/7 implements theory propagation).
626 setup_reification(_, _, [], _, _).
627 setup_reification(SatStateMutable, IdlGraphMut, [(SatId,SatPrologVar,StackInfo)|T], SmtBindings, WfStoreSmt) :-
628 get_texpr_info(SatId, Info),
629 memberchk(smt_formula(SmtFormula), Info),
630 !,
631 SatId = b(identifier(SatVarName),_,_),
632 setup_reification_for_solver(SatStateMutable, StackInfo, IdlGraphMut, SmtFormula, SmtBindings, WfStoreSmt, SatVarName, SatPrologVar),
633 %sat_smt_reification(SatId, SatPrologVar, SmtBindings, WfStoreSmt)
634 setup_reification(SatStateMutable, IdlGraphMut, T, SmtBindings, WfStoreSmt).
635 setup_reification(SatStateMutable, IdlGraphMut, [_|T], SmtBindings, WfStoreSmt) :-
636 % plain SAT variable which is not reified with a theory solver, e.g., introduced by CNF optimization rewriting
637 setup_reification(SatStateMutable, IdlGraphMut, T, SmtBindings, WfStoreSmt).
638
639 /*:- block sat_smt_reification(?, -, ?, ?).
640 % without theory propagation
641 sat_smt_reification(SatId, SatPrologVar, SmtBindings, WfStoreSmt) :-
642 get_texpr_info(SatId, Info),
643 memberchk(smt_formula(TSmtFormula), Info),
644 ( SatPrologVar == pred_true
645 -> SmtFormula = TSmtFormula
646 ; SmtFormula = b(negation(TSmtFormula),pred,[])
647 ),
648 b_test_boolean_expression(SmtFormula, SmtBindings, [], WfStoreSmt).*/
649
650 setup_reification_for_solver(SatStateMutable, StackInfo, IdlGraphMut, SmtFormula, SmtBindings, WfStoreSmt, SatVarName, SatPrologVar) :-
651 find_typed_identifier_uses(SmtFormula, [], UsedIds),
652 ( list_contains_unfixed_deferred_set_id(UsedIds)
653 -> ContainsUnfixed = true,
654 ( ground(SatPrologVar)
655 -> DetUnfixedProp = true
656 ; DetUnfixedProp = false
657 )
658 ; ContainsUnfixed = false,
659 DetUnfixedProp = false
660 ),
661 log_theory_propagation_and_unfixed_deferred_sets(SatStateMutable, SatVarName, StackInfo, ContainsUnfixed, DetUnfixedProp, SatPrologVar),
662 sat_var_assignment_timeout(ATO),
663 ( get_preference(cdclt_use_idl_theory_solver,true)
664 -> ( ast_to_difference_logic:rewrite_to_idl(SmtFormula, [DLConstraint])
665 -> debug_format_cdclt("Constraint for IDL: ", [], SmtFormula),
666 idl_solver_interface(IdlGraphMut, SatPrologVar, [DLConstraint])
667 ; log_idl_candidates_from_constraint(SmtFormula)
668 -> propagate_non_idl_to_idl(IdlGraphMut, SatPrologVar, SmtFormula)
669 ; true
670 ),
671 sat_debug_msg(SatVarName,SmtFormula,SatPrologVar),
672 b_convert_bool_timeout(SmtFormula, SmtBindings, [], WfStoreSmt, SatPrologVar, ATO, TORes),
673 cdclt_sat_solver:log_det_theory_timeout(TORes)
674 ; sat_debug_msg(SatVarName,SmtFormula,SatPrologVar),
675 b_convert_bool_timeout(SmtFormula, SmtBindings, [], WfStoreSmt, SatPrologVar, ATO, TORes),
676 cdclt_sat_solver:log_det_theory_timeout(TORes),
677 ( additional_z3_reification
678 -> kernel_waitflags:get_wait_flag1(smt_call, WfStoreSmt, BeforeEnumWF),
679 gensym:gensym(smt_assertion_name, Symbol),
680 z3_coroutine(SatPrologVar, BeforeEnumWF, Symbol, SmtBindings, SmtFormula)
681 ; true
682 )
683 ).
684
685 :- block z3_coroutine(-, ?, ?, ?, ?).
686 z3_coroutine(SatPrologVar, BeforeEnumWF, Symbol, SmtBindings, SmtFormula) :-
687 SatPrologVar == pred_true,
688 smt_add_predicate(BeforeEnumWF, SmtFormula, SmtBindings, SmtBindings, Symbol).
689 z3_coroutine(SatPrologVar, BeforeEnumWF, Symbol, SmtBindings, SmtFormula) :-
690 SatPrologVar == pred_false,
691 safe_create_texpr(negation(SmtFormula), pred, [], NSmtFormula),
692 smt_add_predicate(BeforeEnumWF, NSmtFormula, SmtBindings, SmtBindings, Symbol).
693
694 sat_debug_msg(SatVarName, SmtFormula, SatPrologVar) :-
695 ( debug_mode(off)
696 -> true
697 ; format('% SAT variable ~w (~w) for ProB pred: ',[SatVarName,SatPrologVar]),
698 print_bexpr(SmtFormula), nl
699 ).
700
701 :- block log_theory_propagation_and_unfixed_deferred_sets(?, ?, ?, ?, ?, -).
702 log_theory_propagation_and_unfixed_deferred_sets(SatStateMutable, SatVarName, StackInfo, ContainsUnfixed, _DetUnfixedProp, SatPrologVar) :-
703 ground(SatPrologVar),
704 ( ContainsUnfixed
705 -> % log unfixed deferred set propagation; this is not undone when backtracking:
706 % a conflict found in this branch can depend on the propagated constraint (and the clause learned
707 % from it remains), so a final contradiction is no longer reliable, e.g., for
708 % (card(D) > 5 or x = 1) & x = 2 with an unfixed deferred set D (result is unknown, not false)
709 ( unfixed_deferred_set_has_been_propagated
710 -> true
711 ; asserta(unfixed_deferred_set_has_been_propagated)
712 )
713 ; true
714 ),
715 StackInfo = (PropType,_,_,_),
716 ( ( PropType == unit; PropType == branch) % has been propagated by the SAT solver
717 -> true
718 ; cdclt_sat_solver:log_theory_propagation_sat_stack(SatStateMutable, SatVarName, SatPrologVar, StackInfo)
719 ).
720
721 log_idl_candidates_from_constraint(Constraint) :-
722 get_ids_and_int_constants(Constraint, Ids, IntConstants),
723 Ids \== [],
724 IntConstants \== [],
725 !,
726 assert_idl_candidates(Ids, IntConstants).
727 log_idl_candidates_from_constraint(_).
728
729 assert_idl_candidates([], _).
730 assert_idl_candidates([Id|T], IntConstants) :-
731 retract(idl_candidate_constants(Id, Candidates)),
732 !,
733 subtract(IntConstants, Candidates, New),
734 append(Candidates, New, NewCandidates),
735 asserta(idl_candidate_constants(Id, NewCandidates)),
736 assert_idl_candidates(T, IntConstants).
737 assert_idl_candidates([Id|T], IntConstants) :-
738 asserta(idl_candidate_constants(Id, IntConstants)),
739 assert_idl_candidates(T, IntConstants).
740
741 get_ids_and_int_constants(b(Node,pred,_), Ids, IntConstants) :-
742 comparison_op(Node, Lhs, Rhs),
743 get_ids_and_int_constants_expr(Lhs, [], [], IdsAcc, IntConstantsAcc),
744 get_ids_and_int_constants_expr(Rhs, IdsAcc, IntConstantsAcc, Ids, IntConstants).
745
746 get_ids_and_int_constants_expr(Id, IdsAcc, IntConstantsAcc, [Name|IdsAcc], IntConstantsAcc) :-
747 Id = b(identifier(Name),integer,_).
748 get_ids_and_int_constants_expr(Int, IdsAcc, IntConstantsAcc, IdsAcc, [Value,Value1|IntConstantsAcc]) :-
749 ( Int = b(integer(Value),integer,_)
750 ; Int = b(unary_minus(b(integer(Value),integer,_)),integer,_)
751 ),
752 % select positive and negative value
753 Value1 is Value * -1.
754 get_ids_and_int_constants_expr(b(Node,integer,_), IdsAcc, IntConstantsAcc, Ids, IntConstants) :-
755 arithmetic_expr(Node, Lhs, Rhs),
756 get_ids_and_int_constants_expr(Lhs, IdsAcc, IntConstantsAcc, NIdsAcc, NIntConstantsAcc),
757 get_ids_and_int_constants_expr(Rhs, NIdsAcc, NIntConstantsAcc, Ids, IntConstants).
758
759 comparison_op(less(Lhs,Rhs), Lhs, Rhs).
760 comparison_op(less_equal(Lhs,Rhs), Lhs, Rhs).
761 comparison_op(equal(Lhs,Rhs), Lhs, Rhs).
762 comparison_op(not_equal(Lhs,Rhs), Lhs, Rhs).
763
764 arithmetic_expr(minus(Lhs,Rhs), Lhs, Rhs).
765 arithmetic_expr(add(Lhs,Rhs), Lhs, Rhs).
766 arithmetic_expr(div(Lhs,Rhs), Lhs, Rhs).
767 arithmetic_expr(floored_div(Lhs,Rhs), Lhs, Rhs).
768 arithmetic_expr(power_of(Lhs,Rhs), Lhs, Rhs).
769 arithmetic_expr(multiplication(Lhs,Rhs), Lhs, Rhs).
770 arithmetic_expr(modulo(Lhs,Rhs), Lhs, Rhs).
771
772 :- block propagate_non_idl_to_idl(?, -, ?).
773 propagate_non_idl_to_idl(IdlGraphMut, SatPrologVar, SmtFormula) :-
774 ( SatPrologVar == pred_true
775 % e.g., x:NAT -> x>=0
776 -> ( infer_constraints_for_idl_solver(SmtFormula, ConjList)
777 -> register_constraints(ConjList,IdlGraphMut)
778 ; true
779 )
780 ; true % TO DO: also propagate pred_false? probably not beneficial
781 ).
782
783 %% idl_solver_interface(+IdlGraphMut, +SatPrologVar, +Constraint).
784 :- block idl_solver_interface(?, -, ?).
785 idl_solver_interface(IdlGraphMut, SatPrologVar, [DLConstraint]) :-
786 SatPrologVar == pred_true,
787 difference_logic_solver:remove_unsat_core,
788 cdclt_sat_solver:remove_idl_unsat_core,
789 ( difference_logic_solver:register_constraint(IdlGraphMut, DLConstraint)
790 ; \+ cdclt_sat_solver:is_backjumping,
791 propagate_idl_unsat_core_to_sat_solver(IdlGraphMut),
792 fail
793 ).
794 idl_solver_interface(IdlGraphMut, SatPrologVar, [DLConstraint]) :-
795 SatPrologVar == pred_false,
796 difference_logic_solver:remove_unsat_core,
797 cdclt_sat_solver:remove_idl_unsat_core,
798 ( difference_logic_solver:register_constraint(IdlGraphMut, b(negation(DLConstraint),pred,[]))
799 ; \+ cdclt_sat_solver:is_backjumping,
800 propagate_idl_unsat_core_to_sat_solver(IdlGraphMut),
801 fail
802 ).
803
804 propagate_idl_unsat_core_to_sat_solver(IdlGraphMut) :-
805 difference_logic_solver:get_solver_result(IdlGraphMut, Res),
806 Res == contradiction_found,
807 difference_logic_solver:get_unsat_core(IdlCore),
808 difference_logic_solver:remove_unsat_core,
809 cdclt_sat_solver:store_idl_unsat_core(IdlCore), !.
810
811 %% get_idl_solution_bindings(+IdlGraphMut, -Bindings).
812 get_idl_solution_bindings(IdlGraphMut, Bindings) :-
813 get_solver_result(IdlGraphMut, SolverResult),
814 SolverResult = solution(Bindings).
815
816 %% propagate_idl_solution_to_bindings_bt(+IdlGraphMut, +SmtBindings).
817 propagate_idl_solution_to_bindings_bt(IdlGraphMut, SmtBindings) :-
818 get_preference(cdclt_use_idl_theory_solver,true),
819 !,
820 % TO DO: try the current solution first
821 ( get_candidate_bounds_from_non_idl_constraints(CandidateTuples),
822 difference_logic_solver:try_candidate_bounds(IdlGraphMut, CandidateTuples, Result)
823 ; difference_logic_solver:get_all_solutions_on_bt(IdlGraphMut, Result)
824 ),
825 Result = solution(Bindings),
826 set_bindings(Bindings, SmtBindings).
827 propagate_idl_solution_to_bindings_bt(_, _).
828
829 %% propagate_fd_bounds_to_idl_solver(+IdlGraphMut, +SmtBindings).
830 propagate_fd_bounds_to_idl_solver(IdlGraphMut, SmtBindings) :-
831 get_preference(cdclt_use_idl_theory_solver,true),
832 !,
833 difference_logic_solver:get_registered_vars(IdlGraphMut, Vars),
834 get_constraints_from_fd_bounds(SmtBindings, Vars, [], ConjList),
835 difference_logic_solver:register_constraints(ConjList,IdlGraphMut).
836 propagate_fd_bounds_to_idl_solver(_, _).
837
838 get_constraints_from_fd_bounds(_, [], Acc, Acc).
839 get_constraints_from_fd_bounds(SmtBindings, [Var|T], Acc, ConjList) :-
840 memberchk(bind(Var, int(Int)), SmtBindings),
841 integer(Int),
842 !,
843 Zero = b(identifier('_zero'),integer,[]),
844 % Var = Int but represented as Var - _zero <= Int & _zero - Var <= -Int
845 Conj1 = b(less_equal(b(minus(b(identifier(Var),integer,[]),Zero),integer,[]),b(integer(Int),integer,[])),pred,[]),
846 Conj2 = b(less_equal(b(minus(Zero,b(identifier(Var),integer,[])),integer,[]),b(unary_minus(b(integer(Int),integer,[])),integer,[])),pred,[]),
847 get_constraints_from_fd_bounds(SmtBindings, T, [Conj1,Conj2|Acc], ConjList).
848 get_constraints_from_fd_bounds(SmtBindings, [Var|T], Acc, ConjList) :-
849 memberchk(bind(Var, int(FDVar)), SmtBindings),
850 fd_var(FDVar),
851 fd_min(FDVar, Min),
852 fd_max(FDVar, Max),
853 !,
854 ( var_geq_min(Var, Min, MinBound)
855 -> ( var_leq_max(Var, Max, MaxBound)
856 -> NAcc = [MinBound,MaxBound|Acc]
857 ; NAcc = [MinBound|Acc]
858 )
859 ; ( var_leq_max(Var, Max, MaxBound)
860 -> NAcc = [MaxBound|Acc]
861 ; NAcc = Acc
862 )
863 ),
864 get_constraints_from_fd_bounds(SmtBindings, T, NAcc, ConjList).
865 get_constraints_from_fd_bounds(SmtBindings, [_|T], Acc, ConjList) :-
866 get_constraints_from_fd_bounds(SmtBindings, T, Acc, ConjList).
867
868 var_geq_min(Var, Min, MinBound) :-
869 % -v <= -min
870 integer(Min),
871 Min1 is Min * -1,
872 Minus = b(minus(b(identifier('_zero'),integer,[]),b(identifier(Var),integer,[])),integer,[]),
873 MinBound = b(less_equal(Minus,b(integer(Min1),integer,[])),pred,[]).
874
875 var_leq_max(Var, Max, MaxBound) :-
876 % v <= Max
877 integer(Max),
878 MaxBound = b(less_equal(b(identifier(Var),integer,[]),b(integer(Max),integer,[])),pred,[]).
879
880 get_candidate_bounds_from_non_idl_constraints(CandidateTuples) :-
881 findall((VarName,Candidates), idl_candidate_constants(VarName, Candidates), CandidateTuples).
882
883 set_bindings([], _).
884 set_bindings([binding(VarName,Val,_)|T], SmtBindings) :-
885 member(bind(VarName,Val), SmtBindings),
886 set_bindings(T, SmtBindings).
887
888 %% exclude_idl_solution(+IdlBindings, +SmtBindings, +StateTypedIds, +WfStoreSmt).
889 exclude_idl_solution(IdlBindings, SmtBindings, StateTypedIds, WfStoreSmt) :-
890 initial_solution,
891 exclude_solution(IdlBindings, StateTypedIds, Exclusion),
892 b_test_boolean_expression(Exclusion, SmtBindings, [], WfStoreSmt).
893 exclude_idl_solution(_, _, _, _) :-
894 \+ initial_solution.
895
896 %% exclude_solution(+Bindings, +StateTypedIds, -Exclusion).
897 exclude_solution([], _, b(truth,pred,[])).
898 exclude_solution([Binding|T], StateTypedIds, Exclusion) :-
899 get_equality_from_binding(Binding, StateTypedIds, EQ),
900 exclude_solution(T, EQ, StateTypedIds, Exclusion).
901
902 exclude_solution([], Acc, _, Acc).
903 exclude_solution([Binding|T], Acc, StateTypedIds, Exclusion) :-
904 get_equality_from_binding(Binding, StateTypedIds, EQ),
905 safe_create_texpr(negation(EQ), pred, [], Neg),
906 safe_create_texpr(disjunct(Neg,Acc), pred, [], NAcc),
907 exclude_solution(T, NAcc, StateTypedIds, Exclusion).
908
909 %% get_equality_from_binding(+Binding, +TypedIds, -EQ).
910 get_equality_from_binding(Binding, TypedIds, EQ) :-
911 ( Binding = bind(VarName,Val)
912 ; Binding = binding(VarName,Val,_)
913 ),
914 ( member(b(identifier(VarName),TType,_), TypedIds)
915 -> Type = TType
916 ; infer_value_type(Val, Type)
917 ),
918 ( contains_any(Type)
919 -> add_error_and_fail(get_equality_from_binding, 'Cannot infer type of identifier to setup state for ', VarName)
920 ; EQ = b(equal(b(identifier(VarName),Type,[]),b(value(Val),Type,[])),pred,[])
921 ).
922
923 %% setup_theory_wf_store(+SmtVars, -SmtBindings, -WFStoreSMT).
924 setup_theory_wf_store(SmtVars, SmtBindings, WFStoreSMT) :-
925 set_up_typed_localstate(SmtVars, _, SmtTypedVals, [], SmtBindings, positive),
926 init_wait_flags(WFStoreSMT, [wf_smt_cdcl]),
927 b_tighter_enumerate_all_values(SmtTypedVals, WFStoreSMT),!.
928
929 log_solution :-
930 \+ initial_solution,
931 !,
932 asserta(initial_solution).
933 log_solution.
934
935 ground_state_binding(Binding) :-
936 Binding = bind(_,_),
937 ground(Binding).
938
939 get_typed_ids_in_scope_of_pred(Pred, TypedIds) :-
940 find_typed_identifier_uses(Pred, PTypedIds),
941 add_typed_ids_in_scope(PTypedIds, TypedIds).
942
943 add_typed_ids_in_scope(PTypedIds, TypedIds) :-
944 b_get_machine_variables(MachineVars),
945 b_get_machine_constants(MachineConstants),
946 append([PTypedIds,MachineVars,MachineConstants], TypedIds).
947
948 get_equalities_from_bindings([], _, b(truth,pred,[])).
949 get_equalities_from_bindings([bind(Id,Val)|T], TypedIds, EqConj) :-
950 get_equality_from_binding(bind(Id,Val), TypedIds, Eq),
951 get_equalities_from_bindings(T, TypedIds, Eq, EqConj).
952
953 get_equalities_from_bindings([], _, EqConj, EqConj).
954 get_equalities_from_bindings([bind(Id,Val)|T], TypedIds, EqAcc, EqConj) :-
955 get_equality_from_binding(bind(Id,Val), TypedIds, Eq),
956 safe_create_texpr(conjunct(Eq,EqAcc), pred, [], Conj),
957 get_equalities_from_bindings(T, TypedIds, Conj, EqConj).
958
959 % only for computing the amount of sat variables of benchmarks
960 get_amount_of_sat_variables(Pred, AmountOfSatVars) :-
961 simplify_negation(Pred, SPred),
962 reset_optimizer_state,
963 assert_ground_id_values(0, SPred),
964 replace_ids_with_ground_values(SPred, 0, [], AstCardOpt),
965 precompute_values(AstCardOpt, [instantiate_quantifier_limit(0)], AstPrecomputed),
966 (clean_up_pred(AstPrecomputed, _, CleanPred) -> true
967 ; add_internal_error('Clean up failed ', cdclt), CleanPred=AstPrecomputed),
968 ( CleanPred = b(truth,pred,_)
969 -> AmountOfSatVars = 1
970 ; CleanPred = b(falsity,pred,_)
971 -> AmountOfSatVars = 1
972 ; preprocess_predicate(false, false, CleanPred, LiftedPred, _, _),
973 predicate_to_sat(normal_make_wd, LiftedPred, _, _, _, SatVars1)
974 ),
975 length(SatVars1, AmountOfSatVars).
976
977 /* currently not used:
978 unfold_let(Pred, Unfolded) :-
979 unfold_let([], Pred, Unfolded).
980
981 unfold_let(IdTuples, b(identifier(Name),_,_), Replacement) :-
982 member((b(identifier(Name),_,_),Ast), IdTuples),
983 !,
984 Replacement = Ast.
985 unfold_let(IdTuples, b(Node,_,_), Replacement) :-
986 ( Node = let_predicate(Ids,Asts,Body)
987 ; Node = let_expression(Ids,Asts,Body)
988 ),
989 !,
990 maplist(unfold_let(IdTuples), Asts, NAsts),
991 zip_acc(Ids, NAsts, IdTuples, NewIdTuples), % TO DO: ideally remove IdTuples which are clashing with Ids
992 unfold_let(NewIdTuples, Body, Replacement).
993 unfold_let(IdTuples, b(Node,Type,Info), Replacement) :-
994 syntaxtransformation(Node,Subs,Names,NSubs,NewNode),!,
995 Replacement = b(NewNode,Type,Info),
996 exclude(hidden_by_local_var(Names),IdTuples,NIdTuples),
997 l_unfold_let(Subs,NIdTuples,NSubs).
998 unfold_let(I, Ast, _) :- add_internal_error('Not a typed expression:', unfold_let(I,Ast,_)),fail.
999
1000 hidden_by_local_var(Names,(TID,_)) :- def_get_texpr_id(TID,ID), member(ID,Names).
1001
1002 l_unfold_let([],_,[]).
1003 l_unfold_let([H|T],IdTuples,[NH|NT]) :-
1004 unfold_let(H,IdTuples,NH),
1005 l_unfold_let(T,IdTuples,NT).
1006
1007 zip_acc([], [], Acc, Acc).
1008 zip_acc([A|T1], [B|T2], Acc, Zipped) :-
1009 zip_acc(T1, T2, [(A,B)|Acc], Zipped). % TO DO: should we just store ID and not typed ID in A?
1010
1011 */
1012
1013 %% For debugging: transform bool formula back to SMT
1014 /*bool_formula_to_smt(b(truth,pred,I), b(truth,pred,I)).
1015 bool_formula_to_smt(b(falsity,pred,I), b(falsity,pred,I)).
1016 bool_formula_to_smt(b(equal(Id,Bool),pred,_), Smt) :-
1017 Id = b(identifier(_),boolean,IdInfo),
1018 member(smt_formula(TSmt), IdInfo),
1019 !,
1020 ( Bool = b(boolean_true,boolean,_)
1021 -> Smt = TSmt
1022 ; Smt = b(negation(TSmt),pred,[])
1023 ).
1024 bool_formula_to_smt(b(equal(Id,Bool),pred,I), Out) :- % bool ids from Tseitin optimization
1025 !,
1026 Out = b(equal(Id,Bool),pred,I).
1027 bool_formula_to_smt(b(conjunct(A,B),pred,I), Out) :-
1028 !,
1029 bool_formula_to_smt(A, SmtA),
1030 bool_formula_to_smt(B, SmtB),
1031 Out = b(conjunct(SmtA,SmtB),pred,I).
1032 bool_formula_to_smt(b(disjunct(A,B),pred,I), Out) :-
1033 !,
1034 bool_formula_to_smt(A, SmtA),
1035 bool_formula_to_smt(B, SmtB),
1036 Out = b(disjunct(SmtA,SmtB),pred,I).*/
1037 %%