1 % (c) 2015-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(smt_solvers_interface, [smt_solve_predicate/4,
6 smt_solve_predicate/5,
7 smt_solve_predicate_free/3,
8 smt_add_predicate/5,
9 smt_solve_predicate_in_state/5,
10 reset_smt_supported_interpreter/0,
11 smt_add_cnf/3, smt_add_extra_clause_cnf/2, smt_solve_cnf/2, smt_reset_cnf/1]).
12
13 :- use_module(library(terms), [term_size/2]).
14 :- use_module(library(sets), [list_to_set/2]).
15 :- use_module(library(lists), [same_length/2,maplist/2, maplist/3, maplist/4,
16 append/2, exclude/3, include/3, select/3,
17 nth0/3, some/2, is_list/1]).
18 :- use_module(probsrc(tools_timeout),[get_time_out_with_factor/2]).
19 :- use_module(probsrc(specfile),[get_state_for_b_formula/3]).
20 :- use_module(probsrc(debug), [debug_println/2, debug_mode/1, debug_level_active_for/1,debug_format/3]).
21 :- use_module(probsrc(bmachine), [b_get_machine_set/1]).
22 :- use_module(probsrc(kernel_objects), [infer_value_type/2,
23 equal_object/2]).
24 :- use_module(probsrc(bsyntaxtree), [map_over_typed_bexpr/3,
25 safe_create_texpr/4,
26 find_typed_identifier_uses/2,
27 find_typed_identifier_uses/3,
28 get_texpr_type/2,
29 get_texpr_expr/2,
30 get_texpr_id/2,
31 predicate_components_in_scope/3,
32 conjunction_to_list/2,
33 conjunct_predicates/2,
34 disjunction_to_list/2,
35 syntaxtraversion/6]).
36 :- use_module(probsrc(error_manager), [add_error_fail/3, add_message/2, add_message/3, add_message/4,
37 add_error/3, add_internal_error/2, add_warning/3]).
38 :- use_module(probsrc(tools), [start_ms_timer/1,stop_ms_timer_with_debug_msg/2,split_atom/3]).
39 :- use_module(probsrc(tools_strings), [atom_prefix/2]).
40 :- use_module(probsrc(translate), [translate_bexpression/2]).
41 :- use_module(probsrc(preferences), [get_preference/2, temporary_set_preference/3, reset_temporary_preference/2]).
42 :- use_module(probsrc(b_interpreter), [b_test_boolean_expression_cs/5]).
43 :- use_module(probsrc(tools_meta),[safe_time_out/3]).
44 :- use_module(probsrc(b_global_sets), [b_global_deferred_set/1,
45 unfixed_deferred_set/1,
46 b_get_global_enumerated_sets/1,
47 is_b_global_constant/3,
48 get_user_defined_scope/4,
49 list_contains_unfixed_deferred_set_id/1]).
50 :- use_module(probsrc(custom_explicit_sets), [expand_custom_set_to_list_now/2]).
51 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
52 :- use_module(probsrc(external_functions), [is_external_function_name/1]).
53 :- use_module(cdclt_solver('cdclt_preprocessing'), [preprocess_predicate/6]).
54 :- use_module(cdclt_solver('cdclt_pred_to_sat'), [predicate_to_sat/6]).
55 :- use_module(smt_solvers_interface(model_translation), [translate_smt_model_to_b_values/4,
56 consistent_deferred_set_sizes/0,
57 store_explicit_set_unique_id/2,
58 assert_virtual_deferred_set_id/2]).
59 :- use_module(smt_solvers_interface(ast_cleanup_for_smt)).
60 :- use_module(smt_solvers_interface(prob_state_predicates), [create_state_pred/4, create_state_pred/5]).
61 :- use_module(smt_solvers_interface(solver_dispatcher)).
62 :- use_module(smt_solvers_interface(smt_common_predicates)).
63
64 :- use_module(probsrc(module_information),[module_info/2]).
65 :- module_info(group,smt_solvers).
66 :- module_info(description,'This module provides an interface to SMT-solvers like CVC4 or Z3.').
67
68 :- dynamic backjumping_symbols/1, solve_in_state/0.
69
70 clear_state :-
71 reset_interface(z3),
72 garbage_collect,
73 trimcore,
74 retractall(solve_in_state),
75 model_translation:clear_translation_state.
76
77 init_smt_supported_interpreter :-
78 retractall(backjumping_symbols(_)), %clean smt backjumping information
79 (get_preference(smt_supported_interpreter,true) -> init_interface(z3) ; true).
80 reset_smt_supported_interpreter :-
81 (get_preference(smt_supported_interpreter,true) -> clear_state
82 ; true).
83
84 :- register_event_listener(start_solving,init_smt_supported_interpreter,'Init Z3 for new solving, clean backjumping'),
85 register_event_listener(end_solving,reset_smt_supported_interpreter,'Reset Z3 after solving').
86
87
88 :- block smt_add_predicate(-,?,?,?,?).
89 smt_add_predicate(_EnumWf, Pred, ProBLocalState, ProBState, Symbol) :-
90 backjump_on_symbol(Symbol),
91 smt_add_predicate_to_solver(z3, Pred, ProBLocalState, ProBState, Symbol).
92
93 smt_add_predicate_to_solver(Solver, Pred, ProBLocalState, ProBState, Symbol) :-
94 init_interface(Solver),
95 smt_clean_up_opts(axiomatic, Pred, [instantiate_quantifier_limit(20)], AxmCPred), % constructive translation isn't fully supported by the incremental solver
96 find_typed_identifier_uses(AxmCPred, [], Identifiers),
97 ( contains_introduced_identifiers(Identifiers, AxmCPred)
98 -> debug_format(9, 'z3: skip: ~w~n because there were introduced identifiers', [Symbol])
99 ; smt_solver_interface_call(Solver, push_frame),
100 create_state_pred(Identifiers, ProBLocalState, ProBState, StatePred),
101 conjunction_to_list(StatePred, StatePredConjuncts),
102 exclude(contains_unsupported_type_or_expression(axiomatic, Solver), StatePredConjuncts, FilteredStatePredConjuncts),
103 conjunct_predicates(FilteredStatePredConjuncts, FilteredStatePred),
104 conjunct_predicates([FilteredStatePred, AxmCPred], FullPred),
105 setup_sets(axiomatic, Solver, GlobalIdentifiers),
106 create_smt_state(axiomatic, Solver, Identifiers, IdentifierState, _),
107 append(IdentifierState, GlobalIdentifiers, GlobalState),
108 mk_expr_skip(axiomatic, Solver, FullPred, [], GlobalState, Expr),
109 translate_bexpression(FullPred, PPExpr),
110 debug_format(9, 'z3: add expr: ~w using symbol: ~w~n', [PPExpr, Symbol]),
111 !,
112 smt_add_predicate_aux(Solver, Expr, Symbol)
113 ).
114 smt_add_predicate_to_solver(Solver, _, _, _, _) :- % in case the predicate contains unsupported types, etc.
115 smt_solver_interface_call(Solver, pop_frame).
116
117 contains_introduced_identifiers(FreeIDs,TExpr) :-
118 syntaxtraversion(TExpr,_,Type,Infos,Subs,_),
119 (member(introduced_by(_),Infos) % identifier that has been introduced
120 -> % check if it is not bound by some quantifiers
121 get_texpr_id(TExpr,Identifier),
122 member(b(identifier(Identifier),Type,_),FreeIDs)
123 ; some(contains_introduced_identifiers(FreeIDs),Subs)).
124
125 smt_add_predicate_aux(Solver,Expr,Symbol) :-
126 get_preference(time_out,TO),
127 QuickTO is TO // 100,
128 % smt solver is called multiple times anyway
129 % and keeps its state inbetween
130 % thus we can use only a fraction of the time_out
131 % after e.g. 100 predicates, the whole timeout will be spent.
132 smt_solver_interface_call(Solver,add_interpreter_constraint(Expr,Symbol,QuickTO,SMTResult)),
133 ( SMTResult = unsat(Core)
134 -> % inconsistency detected
135 debug_format(9,'z3: false with core: ~w~n',[Core]),
136 store_core_for_backjumping(Core),
137 fail
138 ; true
139 ).
140 smt_add_predicate_aux(Solver,_,_) :-
141 % remove frame upon backtracking
142 smt_solver_interface_call(Solver,pop_frame), fail.
143
144 store_core_for_backjumping(Core) :-
145 retractall(backjumping_symbols(_)),
146 cleanup_core_for_backjumping(Core,CleanCore),
147 assertz(backjumping_symbols(CleanCore)).
148 cleanup_core_for_backjumping([],[]).
149 cleanup_core_for_backjumping([E|Es],[CE|CEs]) :-
150 split_atom(E,['|'],[CE]),
151 cleanup_core_for_backjumping(Es,CEs).
152
153 backjump_on_symbol(Symbol) :-
154 backjumping_symbols(Symbols),
155 member(Symbol,Symbols),
156 debug_format(9,'smt check for backjump:~ncurrent symbol: ~w~nbackjumping symbols: ~w~n',[Symbol,Symbols]),
157 !, debug_format(9,'backjumping!',[]), fail.
158 backjump_on_symbol(_) :-
159 retractall(backjumping_symbols(_)).
160
161 % solve a predicate freely (without any given state or values)
162 smt_solve_predicate_free(SolverName,Pred,Store) :-
163 debug_println(9,solving_with(SolverName)),
164 smt_solve_predicate(SolverName, Pred, _, Result),
165 debug_println(9,result(Result)),
166 % TODO: provide enumeration warnings / timeouts in other cases
167 Result = solution(Bindings),
168 maplist(translate_binding,Bindings,Store).
169
170 % translate solver binding to ProB interpreter store
171 translate_binding(binding(ID,Val,_),bind(ID,Val)).
172
173 % solve in a state stored in the state space
174 smt_solve_predicate_in_state(StateID, Solver, Pred, SolutionState, Result) :-
175 get_state_for_b_formula(StateID, Pred, FullStore),
176 !,
177 asserta(solve_in_state),
178 debug_format(19, 'Solving predicate with ~w in state ~w~n', [Solver,StateID]),
179 append(FullStore, SolutionState, SMTState),
180 smt_solve_predicate(Solver, Pred, SMTState, Result).
181 smt_solve_predicate_in_state(StateID, Solver, _, _, _) :-
182 debug_format(19, 'Cannot solve predicate with ~w in state ~w~n', [Solver,StateID]),
183 fail.
184
185 %% smt_solve_predicate(+SolverName, +Pred, +State, -Result).
186 smt_solve_predicate(SolverName, Pred, State, Result) :-
187 smt_solve_predicate(SolverName, [check_sat_skeleton(250),instantiate_quantifier_limit(50)], Pred, State, Result).
188
189 %% smt_solve_predicate(+Solver, +OptionList, +Pred, +State, -Result).
190 % valid options: decompose_into_components, check_sat_skeleton(+TimeOut)
191 smt_solve_predicate(SolverName, Options, Pred, State, Result) :-
192 translate_solver_name(SolverName,Solver,SelectedTranslations),!,
193 get_preference(time_out, TO),
194 temporary_set_preference(solver_for_reals,z3_solver,Old), % avoid b_compiler pre-computes floats, cf test 2319
195 safe_time_out(call_cleanup(smt_solve_predicate6(SelectedTranslations, Solver, Options, Pred, State, TResult),
196 reset_temporary_preference(solver_for_reals,Old)),
197 TO, TORes),
198 ( TORes == time_out
199 -> Result = time_out,
200 clear_state
201 ; Result = TResult
202 ).
203
204 translate_solver_name(z3sat,z3,[sat,sat_cdcl]). % specialized SAT solver for QF_FD; runs two SAT solvers in parallel using local search and CDCL
205 translate_solver_name(z3axm,z3,[axm_ninc]). % axiomatic translation
206 translate_solver_name(z3cns,z3,[cns_ninc]). % constructive translation
207 translate_solver_name(z3,z3,T) :- T=[axm_ninc,cns_ninc]. % multithreading of the above
208 translate_solver_name(cvc4,cvc4,[axm_inc]).
209 translate_solver_name(S,_,_) :- add_internal_error('Unknown solver name: ', S), fail.
210
211 %% smt_solve_predicate6(+SelectedSolvers, +Solver, +Options, +Pred, +State, -Result).
212 % +Solver is either cvc4 or z3.
213 % We provide different translations and solver configurations for Z3, e.g., (non-)incremental.
214 % For z3, SelectedSolvers is a list of atoms representing the names of specific solvers
215 % defined in the Z3 C++ interface.
216 smt_solve_predicate6(SelectedSolvers, Solver, Options, Pred, State, Result) :-
217 model_translation:clear_translation_state,
218 is_list(SelectedSolvers),
219 get_texpr_type(Pred, pred),
220 !,
221 start_ms_timer(T0),
222 smt_clean_up_pre(Pred, State, Options, CPred),
223 stop_ms_timer_with_debug_msg(T0,smt_clean_up_pre(Solver,Options)),
224 ( CPred = b(truth,pred,_)
225 -> Result = solution([])
226 ; CPred = b(falsity,pred,_)
227 -> Result = contradiction_found
228 ; catch(smt_solve_predicate_aux(SelectedSolvers, Solver, Options, CPred, State, Result),
229 SolverException, % exception most likely happened in the setup phase; in check_sat the exceptions are caught
230 treat_exception(Solver, SolverException, Result))
231 ).
232 % not a predicate or cleanup failed
233 smt_solve_predicate6(SelectedSolvers, _, _, _, _, error) :-
234 add_internal_error('Unknown solver config: ', SelectedSolvers).
235
236 % remove bindings from environment which are not relevant
237 % (otherwise we get errors like z3exception in get_model_string: invalid usage)
238 remove_useless_bindings(X,_,Res) :- var(X),!,Res=X.
239 remove_useless_bindings([],_,[]).
240 remove_useless_bindings([bind(Var,Val)|T],Ids,Res) :-
241 ( (get_texpr_id(TVar,Var), member(TVar,Ids))
242 -> Res = [bind(Var,Val)|RT]
243 ; Res=RT
244 ),
245 remove_useless_bindings(T,Ids,RT).
246
247 filter_unsupported_types_or_expressions(_, _, [], [], []).
248 filter_unsupported_types_or_expressions(TranslationType, Solver, [LP|T], FilteredLPs, UnsupportedLPs) :-
249 contains_unsupported_type_or_expression(TranslationType, Solver, LP),
250 !,
251 UnsupportedLPs = [LP|TUnsupportedLPs],
252 filter_unsupported_types_or_expressions(TranslationType, Solver, T, FilteredLPs, TUnsupportedLPs).
253 filter_unsupported_types_or_expressions(TranslationType, Solver, [LP|T], [LP|TFilteredLPs], UnsupportedLPs) :-
254 filter_unsupported_types_or_expressions(TranslationType, Solver, T, TFilteredLPs, UnsupportedLPs).
255
256 %% get_full_pred(+TranslationType, +Solver, +Pred, +ProBState, -FullPred, -FullProBState, -Filtered, -SkippedVars, -UnsupportedLPs).
257 get_full_pred(TranslationType, Solver, Pred, ProBState, FullPred, FullProBState, Filtered, SkippedVars, UnsupportedLPs) :-
258 find_typed_identifier_uses(Pred, Identifiers),
259 remove_useless_bindings(ProBState, Identifiers, FullProBState),
260 create_state_pred(Identifiers, [], FullProBState, StatePred, [skipped_variables(SkippedVars)]),
261 % print(state),nl,translate:nested_print_bexpr(StatePred),nl,
262 safe_create_texpr(conjunct(StatePred,Pred), pred, [], FullConj),
263 conjunction_to_list(FullConj, LPs),
264 filter_unsupported_types_or_expressions(TranslationType, Solver, LPs, FilteredLPs, UnsupportedLPs),
265 ( same_length(LPs, FilteredLPs)
266 -> Filtered = false
267 ; Filtered = true,
268 ( debug_mode(off)
269 -> true
270 ; include(contains_unsupported_type_or_expression(TranslationType, Solver), LPs, Unsupported),
271 conjunct_predicates(Unsupported,US),
272 add_message(Solver, 'Unsupported constraints were discarded for SMT solver: ', US, US)
273 )
274 ),
275 conjunct_predicates(FilteredLPs, FullPred).
276
277 validate_selected_solvers(cvc4, SelectedSolvers) :-
278 SelectedSolvers == [axm_inc],
279 !.
280 validate_selected_solvers(cvc4, _) :-
281 add_error_fail(validate_selected_solvers, 'Only axiomatic translation with incremental solver (axm_inc) available for cvc4.', []).
282 validate_selected_solvers(z3, SelectedSolvers) :-
283 validate_selected_z3_solvers(SelectedSolvers).
284
285 validate_selected_z3_solvers(SelectedSolvers) :-
286 AvailableSolvers = [axm_inc,axm_ninc,sat,sat_cdcl,cns_ninc], % see z3interface/main.cpp:available_solvers
287 findall(Solver, (member(Solver, SelectedSolvers), \+ member(Solver, AvailableSolvers)), UnavailableSolvers),
288 UnavailableSolvers == [],
289 !.
290 validate_selected_z3_solvers(_) :-
291 add_error_fail(validate_selected_z3_solvers, 'At least one selected Z3 solver is not available.', []).
292
293 add_translation_for_solver(TranslationType, Solver, ProBState, Pred, Options, TranslationsAcc, NewAcc, IsUnfilteredTruth, Result) :-
294 start_ms_timer(T0),
295 smt_clean_up_post(TranslationType, Pred, Options, CPred),
296 ( CPred = b(truth,pred,_)
297 -> Result = solution([])
298 ; CPred = b(falsity,pred,_)
299 -> Result = contradiction_found
300 ; get_full_pred(TranslationType, Solver, CPred, ProBState, FullPred, FullProBState, Filtered, SkippedVars, UnsupportedLPs),
301 stop_ms_timer_with_debug_msg(T0,add_translation_for_solver_preprocessing(TranslationType,Solver)),
302 start_ms_timer(T1),
303 ( nonvar(FullPred), FullPred = b(truth,pred,_)
304 -> % fail if all operators are unsupported
305 ( Filtered == false
306 -> IsUnfilteredTruth = true,
307 NewAcc = TranslationsAcc
308 ; length(UnsupportedLPs,Len),
309 ajoin(['Unsupported predicates (',Len,') for solver ',Solver,' (', TranslationType,'): '],Msg),
310 add_message(smt_solvers_interface, Msg, UnsupportedLPs),
311 fail
312 )
313 ; IsUnfilteredTruth = false,
314 setup_sets(TranslationType, Solver, GlobalIdentifiers),
315 find_typed_identifier_uses(FullPred, Ids),
316 create_smt_state(TranslationType, Solver, Ids, IdState, _),
317 append(IdState, GlobalIdentifiers, GlobalState),
318 mk_expr(FullPred, TranslationType, Solver, [], GlobalState, PExpr),
319 %format("~w:~n", [TranslationType]), translate:nested_print_bexpr_as_classicalb(FullAxmPred),nl,
320 ( debug:debug_mode(on)
321 -> translate_bexpression(FullPred, PPPred),
322 format('Sending ~w translation to ~w: ~w~n', [TranslationType,Solver,PPPred])
323 ; true
324 ),
325 flush_output,
326 % comment next line in if you want to directly test ProB on the translated constraint:
327 %write(solving_with_prob(TranslationType)),nl,(solver_interface:solve_predicate(FullPred,_,3,[],CBCResult) -> write(CBCResult) ; write(fail)),nl,
328 Translation = (TranslationType,PExpr,ProBState,FullProBState,Ids,GlobalState,Filtered,SkippedVars,UnsupportedLPs),
329 NewAcc = [Translation|TranslationsAcc]
330 ),
331 stop_ms_timer_with_debug_msg(T1,add_translation_for_solver_core(TranslationType,Solver))
332 ).
333
334 contains_solver_name_with_prefix(Prefix, SelectedSolvers) :-
335 member(Name, SelectedSolvers),
336 atom_prefix(Prefix, Name),
337 !.
338
339 %% remove_solvers_with_prefix(+Prefix, +SelectedSolvers, -NewSelectedSolvers).
340 % Remove solvers for specific translation, e.g., if all operators are unsupported.
341 remove_solvers_with_prefix(_, [], []).
342 remove_solvers_with_prefix(Prefix, [SelectedSolver|T], NT) :-
343 atom_prefix(Prefix, SelectedSolver),
344 !,
345 remove_solvers_with_prefix(Prefix, T, NT).
346 remove_solvers_with_prefix(Prefix, [SelectedSolver|T], [SelectedSolver|NT]) :-
347 remove_solvers_with_prefix(Prefix, T, NT).
348
349 combine_satisfiable_component_results([], SatComponentResult, NResultAcc) :-
350 !,
351 NResultAcc = SatComponentResult.
352 combine_satisfiable_component_results(solution(AccBindings), solution(ComponentBindings), NResultAcc) :-
353 append(AccBindings, ComponentBindings, NAccBindings),
354 NResultAcc = solution(NAccBindings).
355
356 create_term_size_pairs([], []).
357 create_term_size_pairs([component(C,_)|T], [NTS-C|NT]) :-
358 term_size(C, TS),
359 NTS is TS * -1, % so that we can use keysort which sorts in ascending order
360 create_term_size_pairs(T, NT).
361
362 sort_components_descending_term_size(Components, SortedComponents) :-
363 % term sizes are negative so that we can use keysort to derive a descending order
364 % but we don't need the actual term sizes anyway
365 create_term_size_pairs(Components, TermSizePairs),
366 keysort(TermSizePairs, SortedComponents).
367
368 %% solve_components_with_z3(+Components, +AvailableSolvers, +Options, +State, +ResultAcc, +UnknownOccurred, -Result).
369 % Log unknown in +UnknownOccurred so that a contradiction can possibly be found in a specific component
370 % although a prior component's satisfiability couldn't be decided.
371 solve_components_with_z3([], _, _, _, _, true, no_solution_found(solver_answered_unknown)).
372 solve_components_with_z3([], _, _, _, ResultAcc, false, ResultAcc).
373 solve_components_with_z3([ComponentTerm|T], AvailableSolvers, Options, State, ResultAcc, UnknownOccurred, Result) :-
374 ( ComponentTerm = component(Component,_)
375 ; ComponentTerm = _TermSize-Component
376 ), !,
377 smt_solve_pre_cleaned_predicate(AvailableSolvers, z3, Options, Component, State, ComponentResult),
378 constraint_uses_unfixed_deferred_set(Component, UsesDefSet),
379 ( ( ComponentResult == contradiction_found,
380 ( UsesDefSet == false
381 ; get_preference(z3_solve_for_animation, false) % this is a genuine contradiction without considering DEFAULT_SETSIZE
382 )
383 )
384 -> Result = contradiction_found
385 ; ( ComponentResult = solution(_)
386 -> combine_satisfiable_component_results(ResultAcc, ComponentResult, NResultAcc),
387 solve_components_with_z3(T, AvailableSolvers, Options, State, NResultAcc, UnknownOccurred, Result)
388 ; % unknown, unfixed deferred sets or translation failed
389 solve_components_with_z3(T, AvailableSolvers, Options, State, ResultAcc, true, Result)
390 )
391 ).
392
393 %% sat_skeleton_is_contradictory(+Pred, +Solver).
394 % Is true if a contradiction has been found for the predicate's SAT skeleton. Otherwise, the call fails.
395 sat_skeleton_is_contradictory(Pred, Solver) :-
396 start_ms_timer(T0),
397 preprocess_predicate(false, false, Pred, LiftedPred, _, _),
398 % abstract formula to SAT as is done by lazy SMT solvers
399 predicate_to_sat(normal, LiftedPred, _, _TopLevelWDPOs, SmtBoolFormula, SatVars),
400 findall(bind(IdName,_), member(b(identifier(IdName),_,_), SatVars), Bindings),
401 stop_ms_timer_with_debug_msg(T0, preprocess_predicate_to_sat_predicate_to_find_contradiction(Solver)),
402 start_ms_timer(T1),
403 ( b_test_boolean_expression_cs(SmtBoolFormula, [], Bindings, 'SMT Boolean abstraction', Solver)
404 -> stop_ms_timer_with_debug_msg(T1, no_contradiction_found),
405 fail
406 ; stop_ms_timer_with_debug_msg(T1, contradiction_found)
407 ).
408
409 %% smt_solve_predicate_aux(+SelectedSolvers, +Solver, +OptionsList, +CPred, +ProBState, -Result).
410 % smt_clean_up_pre/4 has been called on +CPred.
411 smt_solve_predicate_aux(_, Solver, Options, CPred, _, Result) :-
412 member(check_sat_skeleton(TimeOut), Options),
413 TimeOut > 0,
414 % don't translate to SMT-LIB if formula has static contradiction, e.g., a:INT & a/:INT
415 safe_time_out(sat_skeleton_is_contradictory(CPred, Solver), TimeOut, TimeOutRes),
416 TimeOutRes \== time_out,
417 !,
418 Result = contradiction_found,
419 clear_state.
420 smt_solve_predicate_aux(SelectedSolvers, Solver, Options, CPred, ProBState, Result) :-
421 member(decompose_into_components, Options),!,
422 % decompose predicate into components to be solved independently
423 % important to not split among deferred sets since we need to know the cardinality if is set
424 start_ms_timer(T0),
425 findall(DeferredSetId, b_get_machine_set(DeferredSetId), DeferredSetIds),
426 predicate_components_in_scope(CPred, DeferredSetIds, Components),
427 stop_ms_timer_with_debug_msg(T0,predicate_components_in_scope(SelectedSolvers)),
428 ( Components = [component(SingleComponent,_)]
429 -> smt_solve_pre_cleaned_predicate(SelectedSolvers, Solver, Options, SingleComponent, ProBState, FreshResult)
430 ; ( member(sort_components,Options)
431 -> sort_components_descending_term_size(Components, SortedComponents)
432 ; SortedComponents = Components
433 ),
434 solve_components_with_z3(SortedComponents, SelectedSolvers, Options, ProBState, solution([]), false, FreshResult)
435 ),
436 Result = FreshResult,
437 clear_state.
438 smt_solve_predicate_aux(SelectedSolvers, Solver, Options, CPred, ProBState, Result) :-
439 smt_solve_pre_cleaned_predicate(SelectedSolvers, Solver, Options, CPred, ProBState, Result).
440
441 %% smt_solve_pre_cleaned_predicate(+SelectedSolvers, +Solver, +CPred, +ProBState, -Result).
442 % smt_clean_up_pre/4 has been called on +CPred.
443 smt_solve_pre_cleaned_predicate(SelectedSolvers, Solver, Options, CPred, ProBState, Result) :-
444 validate_selected_solvers(Solver, SelectedSolvers),
445 ( init_interface(Solver)
446 -> % one translation for each type, contexts are copied in the C++ interface
447 % if more than one solver uses a specific translation
448 ( (contains_solver_name_with_prefix(axm, SelectedSolvers),
449 add_translation_for_solver(axiomatic, Solver, ProBState, CPred, Options, [], TranslationsAcc1, AxmIsUnfilteredTruth, AxmResult))
450 -> SelectedSolvers2 = SelectedSolvers
451 ; TranslationsAcc1 = [],
452 AxmIsUnfilteredTruth = false,
453 remove_solvers_with_prefix(axm, SelectedSolvers, SelectedSolvers2)
454 ),
455 ( ground(AxmResult)
456 -> Result = AxmResult
457 ; ( (contains_solver_name_with_prefix(cns, SelectedSolvers),
458 add_translation_for_solver(constructive, Solver, ProBState, CPred, Options, TranslationsAcc1, TranslationsAcc2, CnsIsUnfilteredTruth, CnsResult))
459 -> RestSelectedSolvers = SelectedSolvers2
460 ; TranslationsAcc2 = TranslationsAcc1,
461 CnsIsUnfilteredTruth = false,
462 remove_solvers_with_prefix(cns, SelectedSolvers2, RestSelectedSolvers)
463 ),
464 ( ground(CnsResult)
465 -> Result = CnsResult
466 ; ( (contains_solver_name_with_prefix(sat, SelectedSolvers),
467 add_translation_for_solver(sat, Solver, ProBState, CPred, Options, TranslationsAcc2, Translations, SatIsUnfilteredTruth, SatResult))
468 -> RestSelectedSolvers2 = RestSelectedSolvers
469 ; Translations = TranslationsAcc2,
470 SatIsUnfilteredTruth = false,
471 remove_solvers_with_prefix(sat, RestSelectedSolvers, RestSelectedSolvers2)
472 ),
473 ( ground(SatResult)
474 -> Result = SatResult
475 ; Translations \== [],
476 RestSelectedSolvers2 \== [],
477 constraint_uses_unfixed_deferred_set(CPred, UsesDefSet),
478 !,
479 ( (AxmIsUnfilteredTruth; CnsIsUnfilteredTruth; SatIsUnfilteredTruth)
480 -> Result = solution([])
481 ; catch(check_sat(RestSelectedSolvers2, Solver, UsesDefSet, Translations, Options, SolverResult, SolvedTranslation),
482 model_translation_failed, Result = no_solution_found(model_translation_failed)),
483 member((SolvedTranslation,_,_,_,_,_,Filtered,SkippedVars), Translations),
484 ( (SolverResult=solution(_), nonvar(SkippedVars), is_list(SkippedVars)) % is_list grounds list
485 -> Result = no_solution_found(complex_state_values(SkippedVars)),
486 add_message(smt_solve_predicate,'Some variable values were discarded as they are not supported: ',SkippedVars)
487 ; SolverResult = solution(_), Filtered == true
488 -> Result = no_solution_found(unsupported_predicates)
489 ; Result = SolverResult
490 )
491 )
492 )
493 ),
494 !, % not backtrackable
495 clear_state
496 )
497 ; Result = no_solution_found(solver_not_available)
498 ).
499 smt_solve_pre_cleaned_predicate(_,_,_,_Pred,_,no_solution_found(translation_or_setup_failed)) :-
500 clear_state.
501
502 mk_expr_skip(TranslationType, Solver, Pred, [], GlobalState, Expr) :-
503 smt_clean_up(TranslationType, Pred, AxmCPred),
504 !,
505 conjunction_to_list(AxmCPred, List),
506 exclude(contains_unsupported_type_or_expression(TranslationType, Solver), List, NList),
507 conjunct_predicates(NList, NewCPred),
508 mk_expr(NewCPred, TranslationType, Solver, [], GlobalState, Expr).
509 mk_expr_skip(_, _, Pred, _, _, _) :- !,
510 add_error_fail(smt_solvers_interface, 'mk_expr_skip failed', Pred).
511
512 %% check_sat(+SelectedSolvers, +Solver, +UsesDefSet, +Translations, -Result, -SolvedTranslation).
513 % SolvedTranslation is either axiomatic or constructive.
514 check_sat(SelectedSolvers, Solver, UsesDefSet, Translations, Options, Result, SolvedTranslation) :-
515 start_ms_timer(T1),
516 catch(check_sat_aux(SelectedSolvers, Solver, UsesDefSet, Translations, Options, Result, SolvedTranslation),
517 SolverException,
518 treat_exception(Solver, SolverException, Result)),
519 stop_ms_timer_with_debug_msg(T1,check_sat(SelectedSolvers,Solver, Options)).
520
521 treat_exception(Solver, Exc, Result) :-
522 known_solver_exception(Exc, Reason),
523 add_internal_error('Exception occurred during SMT solving: ', Reason),
524 print_diagnostics(Solver),
525 !,
526 reset_interface(Solver),
527 Result = no_solution_found(solver_answered_unknown).
528 treat_exception(Solver, Exc, _) :-
529 format(user_error,'Unknown exception in solver ~w: ~w~n', [Solver, Exc]),
530 throw(Exc).
531
532 :- use_module(probsrc(tools), [ajoin/2]).
533 print_diagnostics(Solver) :-
534 smt_solver_version(Solver,Version),
535 smt_solver_header_version(Solver,HVersion),!,
536 (Version=HVersion
537 -> format('~w version is ~w, ProB was compiled against: ~w~n',[Solver, Version,HVersion])
538 ; ajoin([Solver,' version is ',Version,', ProB was compiled against: '],Msg),
539 add_warning(smt_solvers_interface,Msg,HVersion)
540 ).
541 print_diagnostics(Solver) :- format('No version information available for ~w~n',[Solver]).
542
543 known_solver_exception(model_translation_failed, model_translation_failed).
544 known_solver_exception(z3_exception(Reason), Reason).
545 known_solver_exception(logic_exception(Reason), Reason).
546 known_solver_exception(error(representation_error(nofit(integer)),representation_error(_,_,nofit(integer))), integer_overflow).
547
548 constraint_uses_unfixed_deferred_set(Constraint, UsesDefSet) :-
549 find_typed_identifier_uses(Constraint, [], UsedIds),
550 ( list_contains_unfixed_deferred_set_id(UsedIds)
551 -> UsesDefSet = true
552 ; UsesDefSet = false
553 ).
554
555 check_sat_aux(_, cvc4, UsesDefSet, Translations, Options, Result, SolvedTranslation) :-
556 memberchk((axiomatic,AxmPExpr,_,_,_,_,_,_,_), Translations),
557 get_smt_time_out(Options,TO),
558 smt_solver_interface_call(cvc4, cvc4interface:smt_solve_query(AxmPExpr, TO, SMTResult)),
559 get_model_or_return_result(SMTResult, UsesDefSet, TO, axiomatic, Translations, cvc4, Result, SolvedTranslation),
560 SolvedTranslation == axiomatic.
561 check_sat_aux(SelectedSolvers, z3, UsesDefSet, Translations, Options, Result, SolvedTranslation) :-
562 ( memberchk((axiomatic,AxmPExpr,_,_,_,_,_,_,_), Translations),
563 !
564 ; AxmPExpr = -1 % do not solve any Z3 formula with axiomatic solver
565 ),
566 ( memberchk((constructive,CnsPExpr,_,_,_,_,_,_,_), Translations),
567 !
568 ; CnsPExpr = -1 % do not solve any Z3 formula with constructive solver
569 ),
570 ( memberchk((sat,SatPExpr,_,_,_,_,_,_,_), Translations),
571 !
572 ; SatPExpr = -1
573 ),
574 get_smt_time_out(Options,TO),
575 % format('Calling Z3 with time-out ~w, solvers:~w (~w:~w)~n',[TO,SelectedSolvers,AxmPExpr,CnsPExpr]),
576 % Selected Solvers can be axm_inc, axm_ninc, sat or cns_ninc
577 set_z3_sat_threads,
578 smt_solver_interface_call(z3, z3interface:smt_solve_query(SelectedSolvers, AxmPExpr, CnsPExpr, SatPExpr, TO, SMTResultData)),
579 ( debug_level_active_for(9)
580 -> write('; SMT TRANSLATION: '), nl, pretty_print_smt(z3), nl
581 ; true
582 ),
583 SMTResultData = result_tuple(TempSolvedTranslation,SMTResult),
584 %format('Calling get_model_or_return_result ~w~n',[SMTResult]),
585 get_model_or_return_result(SMTResult, UsesDefSet, TO, TempSolvedTranslation, Translations, z3, Result, SolvedTranslation).
586
587 get_smt_time_out(Options,TO) :-
588 member(smt_time_out_factor(TOFactor),Options),!,
589 get_time_out_with_factor(TOFactor,TO).
590 get_smt_time_out(_,TO) :- get_preference(time_out, TO).
591
592 add_state_to_bindings([], FullBindings, FullBindings).
593 add_state_to_bindings([bind(IdName,Value)|T], Bindings, FullBindings) :-
594 ( member(binding(IdName,ModelValue,_), Bindings)
595 -> equal_object(Value, ModelValue),
596 NewAcc = Bindings
597 ; infer_value_type(Value, Type),
598 translate_bexpression(b(value(Value),Type,[]), PrettyValue),
599 NewAcc = [binding(IdName,Value,PrettyValue)|Bindings]
600 ),
601 !,
602 add_state_to_bindings(T, NewAcc, FullBindings).
603 add_state_to_bindings([bind(IdName,_)|_], _, _) :-
604 add_error_fail(add_state_to_bindings, 'The synchronisation of the model found by Z3 with the global state bindings failed.', [IdName]).
605
606 get_model_or_return_result(unsat, UsesDefSet, _, SolvedTranslation, _, _, Solution, SolvedTranslationOut) :-
607 get_preference(z3_solve_for_animation, true), % behave such as ProB by considering DEFAULT_SETSIZE
608 !,
609 SolvedTranslation = SolvedTranslationOut,
610 ( (UsesDefSet == true, \+ solve_in_state)
611 -> Solution = no_solution_found(unfixed_deferred_sets)
612 ; Solution = contradiction_found
613 ).
614 get_model_or_return_result(unsat, _, _, SolvedTranslation, _, _, contradiction_found, SolvedTranslation).
615 get_model_or_return_result(unknown, _, _, SolvedTranslation, _, _, no_solution_found(solver_answered_unknown), SolvedTranslation).
616 get_model_or_return_result(time_out, _, _, SolvedTranslation, _, _, time_out, SolvedTranslation).
617 get_model_or_return_result(sat, _, TO, SolvedTranslation, Translations, Solver, Solution, SolvedTranslation) :-
618 memberchk((SolvedTranslation,_,ProBState,_,Ids,GlobalState,_,_,UnsupportedLPs), Translations),
619 ( UnsupportedLPs \== []
620 -> add_message(get_model_or_return_result, 'A solution has been found but some predicates are not supported and were not considered: ', UnsupportedLPs),
621 Solution = no_solution_found(solver_answered_unknown)
622 ; exclude(is_smt_temp_var, Ids, FilteredIDs),
623 % we replaced ProBState ids with values in ast_cleanup_for_smt so we add them to the solution here
624 ( catch(
625 translate_smt_model_to_b_values_with_timeout(TO,Solver, GlobalState, FilteredIDs, Bindings),
626 E,
627 (add_error(smt_solvers_interface,'Exception in model translation: ',E),
628 throw(model_translation_failed)))
629 -> ( (
630 get_preference(z3_solve_for_animation, true),
631 % Z3 behaves as ProB by considering its deferred set size preference
632 \+ consistent_deferred_set_sizes
633 )
634 -> Solution = no_solution_found(unfixed_deferred_sets)
635 ; add_state_to_bindings(ProBState, Bindings, FullBindings),
636 maplist(bind_in_prob_state(FullBindings), ProBState)
637 -> % for this solution, Z3 possibly considered a smaller deferred set size than ProB
638 % if Z3 considered a larger deferred set size, an error would have been thrown by model_translation:handle_globalsets_fdrange_contradiction/2
639 ( \+ consistent_deferred_set_sizes
640 -> add_message(get_model_or_return_result, 'Deferred set size considered by Z3 is smaller than the one of ProB (DEFAULT_SETSIZE)')
641 ; true
642 ),
643 Solution = solution(FullBindings)
644 ; throw(model_solution_extraction_failed)
645 )
646 ; add_warning(smt_solvers_interface,'Failure in model translation: ',Solver),
647 throw(model_translation_failed)
648 )
649 ).
650 %get_model_or_return_result(sat, _, TO, PreSolvedTranslation, Translations, Solver, Result, SolvedTranslation) :-
651 % memberchk((PreSolvedTranslation,_,_,Ids,_,_,_), Translations),
652 % next_result(Solver, PreSolvedTranslation, Translations, Ids, Result, SolvedTranslation).
653
654 translate_smt_model_to_b_values_with_timeout(TO,Solver, GlobalState, FilteredIDs, Bindings) :-
655 safe_time_out(translate_smt_model_to_b_values(Solver, GlobalState, FilteredIDs, Bindings),TO,TORes),
656 ( TORes = time_out
657 -> add_warning(smt_solvers_interface,'Time-out in model translation: ',Solver),
658 throw(model_translation_failed)
659 ; true
660 ).
661
662 bind_in_prob_state(Bindings,bind(Id,Val)) :-
663 member(binding(Id,Z3Val,_),Bindings), %format('~w: ~w = ~w~n',[Id,Z3Val,Val]),nl,
664 % Z3 may return solution in list form, ProB had it in AVL form: hence use equal_object
665 equal_object(Z3Val,Val).
666
667 /*next_result(_,PreSolvedTranslation,_,[],Result,SolvedTranslation) :- !,
668 % no global identifiers -> no other solution
669 Result = contradiction_found,
670 SolvedTranslation = PreSolvedTranslation.
671 next_result(Solver,_,Translations,_,Result,SolvedTranslation) :-
672 memberchk((axiomatic,AxmPExpr,AxmProBState,AxmIds,AxmGlobalState,AxmFiltered,AxmSkippedVars), Translations),
673 memberchk((constructive,CnsPExpr,CnsProBState,CnsIds,CnsGlobalState,CnsFiltered,CnsSkippedVars), Translations),
674 findall(Id,member(id(_,Id),AxmGlobalState),AxmExprIds),
675 findall(Id,member(id(_,Id),CnsGlobalState),CnsExprIds),
676 smt_solver_interface_call(Solver,conjoin_negated_state(axiomatic,AxmExprIds,AxmPExpr,NewAxmPExpr)),
677 smt_solver_interface_call(Solver,conjoin_negated_state(constructive,CnsExprIds,CnsPExpr,NewCnsPExpr)),
678 NewTranslations = [
679 (axiomatic,NewAxmPExpr,AxmProBState,AxmIds,AxmGlobalState,AxmFiltered,AxmSkippedVars),
680 (constructive,NewCnsPExpr,CnsProBState,CnsIds,CnsGlobalState,CnsFiltered,CnsSkippedVars)],
681 check_sat(Solver,NewTranslations,Result,SolvedTranslation).
682 */
683
684 % Unary and binary operators that have a direct counterpart in SMT-LIB.
685 unary_operator(negation).
686 unary_operator(unary_minus).
687 unary_operator(unary_minus_real).
688 unary_operator(convert_real).
689 binary_operator(floored_div).
690 binary_operator(equivalence).
691 binary_operator(implication).
692 binary_operator(less).
693 binary_operator(less_equal).
694 binary_operator(less_real).
695 binary_operator(less_equal_real).
696 binary_operator(greater).
697 binary_operator(greater_equal).
698 binary_operator(add).
699 binary_operator(modulo).
700 binary_operator(minus).
701 binary_operator(multiplication).
702 binary_operator(div).
703 binary_operator(power_of).
704 binary_operator(member).
705 binary_operator(subset).
706 binary_operator(union).
707 binary_operator(intersection).
708 binary_operator(set_subtraction).
709 binary_operator(add_real).
710 binary_operator(minus_real).
711 binary_operator(multiplication_real).
712 binary_operator(div_real).
713
714 % Collect couple types from a list of identifiers to reduce the list to a single couple afterwards (left-associative).
715 % We need the couple types for the constructors in SMT-Lib.
716 get_couple_types_comp_args([Arg1,Arg2|T], CoupleTypes) :-
717 Arg1 = b(identifier(_),Type1,_),
718 Arg2 = b(identifier(_),Type2,_),
719 get_couple_types_comp_args(T, couple(Type1,Type2), [couple(Type1,Type2)|D]-D, CoupleTypes).
720
721 get_couple_types_comp_args([], _, CoupleTypes-D, CoupleTypes) :-
722 D = [].
723 get_couple_types_comp_args([Arg|T], LastCoupleType, Acc-D, CoupleTypes) :-
724 Arg = b(identifier(_),Type,_),
725 D = [couple(LastCoupleType,Type)|ND],
726 get_couple_types_comp_args(T, couple(LastCoupleType,Type), Acc-ND, CoupleTypes).
727
728 mk_expr_maplist(TranslationType,Solver,LS,GS,Op,Expr) :-
729 mk_expr(Op,TranslationType,Solver,LS,GS,Expr).
730
731 mk_expr(b(Op,Type,_Infos),TranslationType,Solver,LS,GS,Expr) :-
732 mk_expr_aux(Op,Type,TranslationType,Solver,LS,GS,Expr).
733
734 % unary operators
735 mk_expr_aux(first_of_pair(Couple), _, TranslationType, Solver, LS, GS, Expr) :-
736 get_texpr_type(Couple, CoupleType),
737 mk_expr(Couple, TranslationType, Solver, LS, GS, AE),
738 smt_solver_interface_call(Solver, mk_op_couple_prj(TranslationType, first, AE, CoupleType, Expr)).
739 mk_expr_aux(second_of_pair(Couple), _, TranslationType, Solver, LS, GS, Expr) :-
740 get_texpr_type(Couple, CoupleType),
741 mk_expr(Couple, TranslationType, Solver, LS, GS, AE),
742 smt_solver_interface_call(Solver, mk_op_couple_prj(TranslationType, second, AE, CoupleType, Expr)).
743 /*
744 % change in Z3: lambda inside recursive functions was declared unsupported until proper support is provided (see https://github.com/Z3Prover/z3/issues/5813)
745 % see mk_op_iteration_func_decl in /extensions/z3interface/src/cpp/main.cpp
746 mk_expr_aux(Op, Type, TranslationType, Solver, LS, GS, Expr) :-
747 functor(Op, Functor, 1),
748 ( (Functor == closure, IsReflexive = 0)
749 ; (Functor == reflexive_closure, IsReflexive = 1)
750 ),
751 !,
752 arg(1, Op, A),
753 Type = set(CoupleType),
754 CoupleType = couple(_,ExistsVarType),
755 mk_expr(A, TranslationType, Solver, LS, GS, AE),
756 smt_solver_interface_call(Solver, mk_op_closure(TranslationType, IsReflexive, AE, Type, CoupleType, ExistsVarType, Expr)).
757 mk_expr_aux(iteration(A1,A2), Type, TranslationType, Solver, LS, GS, Expr) :-
758 !,
759 Type = set(CoupleType),
760 CoupleType = couple(_,ExistsVarType),
761 mk_expr(A1, TranslationType, Solver, LS, GS, AE1),
762 mk_expr(A2, TranslationType, Solver, LS, GS, AE2),
763 smt_solver_interface_call(Solver, mk_op_iteration(TranslationType, AE1, AE2, Type, CoupleType, ExistsVarType, Expr)).*/
764 mk_expr_aux(interval(A1,A2), _, TranslationType, Solver, LS, GS, Expr) :-
765 !,
766 mk_expr(A1, TranslationType, Solver, LS, GS, AE1),
767 mk_expr(A2, TranslationType, Solver, LS, GS, AE2),
768 smt_solver_interface_call(Solver, mk_op_interval(TranslationType, AE1, AE2, Expr)).
769 mk_expr_aux(direct_product(Arg1,Arg2), Type, TranslationType, Solver, LS, GS, Expr) :-
770 !,
771 Type = set(CoupleOutType),
772 CoupleOutType = couple(_,Couple2Type),
773 mk_expr(Arg1, TranslationType, Solver, LS, GS, Arg1E),
774 mk_expr(Arg2, TranslationType, Solver, LS, GS, Arg2E),
775 Arg1 = b(_,set(CoupleType1),_),
776 Arg2 = b(_,set(CoupleType2),_),
777 smt_solver_interface_call(Solver, mk_op_direct_product(TranslationType, Arg1E, Arg2E, Couple2Type, CoupleType1, CoupleType2, CoupleOutType, Expr)).
778 mk_expr_aux(parallel_product(Arg1,Arg2), Type, TranslationType, Solver, LS, GS, Expr) :-
779 !,
780 Type = set(CoupleOutType),
781 mk_expr(Arg1, TranslationType, Solver, LS, GS, Arg1E),
782 mk_expr(Arg2, TranslationType, Solver, LS, GS, Arg2E),
783 Arg1 = b(_,set(CoupleType1),_),
784 Arg2 = b(_,set(CoupleType2),_),
785 CoupleOutType = couple(ExistsCoupleType1,ExistsCoupleType2),
786 smt_solver_interface_call(Solver, mk_op_parallel_product(TranslationType, Arg1E, Arg2E, CoupleType1, CoupleType2, ExistsCoupleType1, ExistsCoupleType2, CoupleOutType, Expr)).
787 mk_expr_aux(composition(Arg1,Arg2), Type, TranslationType, Solver, LS, GS, Expr) :-
788 !,
789 Type = set(CoupleOutType),
790 Arg1 = b(_,set(CoupleType1),_),
791 CoupleType1 = couple(A,B),
792 Arg2 = b(_,set(CoupleType2),_),
793 CoupleType2 = couple(B,C),
794 CoupleOutType = couple(A,C),
795 mk_expr(Arg1, TranslationType, Solver, LS, GS, Arg1E),
796 mk_expr(Arg2, TranslationType, Solver, LS, GS, Arg2E),
797 smt_solver_interface_call(Solver, mk_op_composition(TranslationType, Arg1E, Arg2E, B, CoupleType1, CoupleType2, CoupleOutType, Expr)).
798 mk_expr_aux(cartesian_product(A1,A2), Type, TranslationType, Solver, LS, GS, Expr) :-
799 !,
800 Type = set(CoupleType),
801 mk_expr(A1, TranslationType, Solver, LS, GS, AE1),
802 mk_expr(A2, TranslationType, Solver, LS, GS, AE2),
803 smt_solver_interface_call(Solver, mk_op_cartesian(TranslationType, AE1, AE2, CoupleType, Expr)).
804 mk_expr_aux(identity(A), Type, TranslationType, Solver, LS, GS, Expr) :-
805 !,
806 Type = set(CoupleType),
807 CoupleType = couple(InnerSetType,_),
808 mk_expr(A, TranslationType, Solver, LS, GS, AE),
809 smt_solver_interface_call(Solver, mk_op_identity(TranslationType, AE, InnerSetType, CoupleType, Expr)).
810 mk_expr_aux(reverse(A), Type, TranslationType, Solver, LS, GS, Expr) :-
811 !,
812 Type = set(CoupleType),
813 mk_expr(A, TranslationType, Solver, LS, GS, AE),
814 smt_solver_interface_call(Solver, mk_op_reverse(TranslationType, AE, CoupleType, Expr)).
815 % binary operators
816 mk_expr_aux(comprehension_set(Args,Body), Type, TranslationType, Solver, LS, GS, Expr) :-
817 LambdaId = b(identifier('_lambda_result_'),_,_),
818 select(LambdaId, Args, LambdaArgs),
819 create_bounded_smt_state(TranslationType, Solver, LambdaArgs, State, ArgsE),
820 ArgsE = [Arg],
821 append(State, LS, NLS),
822 conjunction_to_list(Body, ConjList),
823 select(b(equal(LambdaId,BodyExpr),pred,Info), ConjList, RestConjList),
824 member(prob_annotation('LAMBDA-EQUALITY'), Info),
825 conjunct_predicates(RestConjList, BodyPred),
826 Type = set(CoupleType),
827 !,
828 mk_expr(BodyExpr, TranslationType, Solver, NLS, GS, BodyE),
829 mk_expr(BodyPred, TranslationType, Solver, NLS, GS, BodyP),
830 smt_solver_interface_call(Solver, mk_op_lambda(TranslationType, Arg, BodyP, BodyE, CoupleType, Expr)).
831 mk_expr_aux(comprehension_set(Args,Body), _, TranslationType, Solver, LS, GS, Expr) :-
832 !,
833 create_bounded_smt_state(TranslationType, Solver, Args, State, ArgsE),
834 append(State, LS, NLS),
835 mk_expr(Body, TranslationType, Solver, NLS, GS, BodyE),
836 length(ArgsE, ArgAmount),
837 ( ArgAmount == 1
838 -> ArgsE = [Arg],
839 smt_solver_interface_call(Solver, mk_op_comprehension_set_singleton(TranslationType, Arg, BodyE, Expr))
840 ; get_couple_types_comp_args(Args, CoupleTypes),
841 smt_solver_interface_call(Solver, mk_op_comprehension_set_multi(TranslationType, ArgsE, CoupleTypes, BodyE, Expr))
842 ).
843 mk_expr_aux(image(A,B), _, TranslationType, Solver, LS, GS, Expr) :-
844 !,
845 A = b(_,set(couple(Prj1Type,Prj2Type)),_),
846 mk_expr(A, TranslationType, Solver, LS, GS, AE),
847 mk_expr(B, TranslationType, Solver, LS, GS, BE),
848 smt_solver_interface_call(Solver, mk_op_image(TranslationType, AE,BE,couple(Prj1Type,Prj2Type),Prj1Type,Prj2Type,Expr)).
849 % conjunct and disjunct are deconstructed to lists
850 mk_expr_aux(conjunct(A,B),pred,TranslationType, Solver,LS,GS,Expr) :-
851 !,
852 conjunction_to_list(b(conjunct(A,B),pred,[]),List),
853 maplist(mk_expr_maplist(TranslationType, Solver,LS,GS),List,ExprList), % apply mk_expr on List
854 % truth/0 are removed from the conjunction during list / from list
855 % the list might be empty now!
856 ( ExprList = []
857 -> smt_solver_interface_call(Solver,mk_bool_const(boolean_true,Expr))
858 ; ( ExprList = [X]
859 -> Expr = X
860 ; smt_solver_interface_call(Solver,mk_op_arglist(TranslationType, conjunct,ExprList,Expr))
861 )
862 ).
863 mk_expr_aux(disjunct(A,B),pred,TranslationType, Solver,LS,GS,Expr) :-
864 !,
865 disjunction_to_list(b(disjunct(A,B),pred,[]),List),
866 maplist(mk_expr_maplist(TranslationType, Solver,LS,GS),List,ExprList),
867 smt_solver_interface_call(Solver,mk_op_arglist(TranslationType, disjunct,ExprList,Expr)).
868 % special case for if then else
869 mk_expr_aux(if_then_else(Pred,A,B),_,TranslationType, Solver,LS,GS,Expr) :-
870 !,
871 maplist(mk_expr_maplist(TranslationType, Solver,LS,GS),[Pred,A,B],ArgList),
872 smt_solver_interface_call(Solver,mk_op_arglist(TranslationType, if_then_else,ArgList,Expr)).
873 % special case for partition
874 mk_expr_aux(partition(S,Sets),pred,TranslationType, Solver,LS,GS,Expr) :-
875 !,
876 % definition: sets are disjoint and S is the union
877 maplist(mk_expr_maplist(TranslationType, Solver,LS,GS),Sets,SetExprs),
878 pairwise_union(TranslationType,SetExprs,Solver,UnionOfSets),
879 mk_expr(S,TranslationType, Solver,LS,GS,SExpr),
880 smt_solver_interface_call(Solver,mk_op(TranslationType, equal,SExpr,UnionOfSets,EqualToUnion)), % S = Union(Sets)
881 % enforce sets pairwise disjoint (= intersection is empty)
882 get_texpr_type(S,Type),
883 smt_solver_interface_call(Solver,mk_empty_set(TranslationType, Type,EmptySet)),
884 pairwise_disjoint(TranslationType,SetExprs,Solver,EmptySet,PWConstraint),
885 smt_solver_interface_call(Solver,mk_op_arglist(TranslationType, conjunct,[EqualToUnion,PWConstraint],Expr)).
886 % quantifiers
887 mk_expr_aux(forall(IDs,b(truth,pred,_),B),pred,TranslationType, Solver,LS,GS,Expr) :-
888 !,
889 create_bounded_smt_state(TranslationType, Solver,IDs,State,SMTExprs),
890 append(State,LS,NLS),
891 mk_expr(B,TranslationType, Solver,NLS,GS,BE),
892 smt_solver_interface_call(Solver,mk_quantifier(TranslationType, forall,SMTExprs,BE,Expr)).
893 mk_expr_aux(forall(IDs,A,B),pred,TranslationType, Solver,LS,GS,Expr) :-
894 !,
895 create_bounded_smt_state(TranslationType, Solver,IDs,State,SMTExprs),
896 append(State,LS,NLS),
897 mk_expr(A,TranslationType, Solver,NLS,GS,AE), mk_expr(B,TranslationType, Solver,NLS,GS,BE),
898 smt_solver_interface_call(Solver,mk_op(TranslationType, implication,AE,BE,InnerExpr)),
899 smt_solver_interface_call(Solver,mk_quantifier(TranslationType, forall,SMTExprs,InnerExpr,Expr)).
900 mk_expr_aux(exists(IDs,B),pred,TranslationType, Solver,LS,GS,Expr) :-
901 !,
902 create_bounded_smt_state(TranslationType, Solver,IDs,State,SMTExprs),
903 append(State,LS,NLS),
904 mk_expr(B,TranslationType, Solver,NLS,GS,InnerExpr),
905 smt_solver_interface_call(Solver,mk_quantifier(TranslationType, exists,SMTExprs,InnerExpr,Expr)).
906 % equality is a special case as it needs to distinguish between booleans and other types
907 mk_expr_aux(equal(A,B),pred,TranslationType, Solver,LS,GS,Expr) :-
908 !,
909 mk_expr(A,TranslationType, Solver,LS,GS,AE),
910 mk_expr(B,TranslationType, Solver,LS,GS,BE),
911 get_texpr_type(A,Type),
912 ( Type = boolean
913 -> smt_solver_interface_call(Solver, mk_op(TranslationType, equivalence, AE, BE, Expr))
914 ; smt_solver_interface_call(Solver, mk_op(TranslationType, equal, AE, BE, Expr))
915 ).
916 mk_expr_aux(convert_int_floor(Real),integer,TranslationType, Solver,LS,GS,Expr) :-
917 mk_expr(Real, TranslationType, Solver, LS, GS, RealExpr),
918 !,
919 number_codes(RealExpr, ECodes),
920 append([102,108,111,111,114], ECodes, EECodes),
921 atom_codes(EAtom, EECodes),
922 ( is_ground_real(Real)
923 -> IsGroundArg = 1
924 ; IsGroundArg = 0
925 ),
926 smt_solver_interface_call(Solver,mk_op_floor(TranslationType,IsGroundArg,EAtom,RealExpr,Expr)).
927 mk_expr_aux(convert_int_ceiling(Real),integer,TranslationType, Solver,LS,GS,Expr) :-
928 mk_expr(Real, TranslationType, Solver, LS, GS, RealExpr),
929 !,
930 number_codes(RealExpr, ECodes),
931 append([99,101,105,108,105,110,103], ECodes, EECodes),
932 atom_codes(EAtom, EECodes),
933 ( is_ground_real(Real)
934 -> IsGroundArg = 1
935 ; IsGroundArg = 0
936 ),
937 smt_solver_interface_call(Solver,mk_op_ceiling(TranslationType,IsGroundArg,EAtom,RealExpr,Expr)).
938 % records
939 mk_expr_aux(rec(ListOfFields),Type,TranslationType, Solver,LS,GS,Expr) :-
940 !,
941 findall(FieldExpr, member(field(_,FieldExpr),ListOfFields), FieldExprs),
942 maplist(mk_expr_maplist(TranslationType, Solver,LS,GS),FieldExprs,SMTFieldExprs),
943 smt_solver_interface_call(Solver,mk_record_const(TranslationType, Type,SMTFieldExprs,Expr)).
944 mk_expr_aux(record_field(Record,FieldName),Type,TranslationType, Solver,LS,GS,Expr) :-
945 !,
946 get_texpr_type(Record,record(RFields)),
947 nth0(FieldNr,RFields,field(FieldName,Type)),
948 % debug_format(9,'Field: ~w Type: ~w~n-> FieldNr: ~w~n',[FieldName,RFields,FieldNr]),
949 mk_expr(Record,TranslationType, Solver,LS,GS,SMTRecordExpr),
950 smt_solver_interface_call(Solver,mk_record_field(TranslationType, SMTRecordExpr,FieldNr,Expr)).
951 % couple construction
952 mk_expr_aux(couple(A,B),Type,TranslationType, Solver,LS,GS,Expr) :-
953 !,
954 mk_expr(A,TranslationType, Solver,LS,GS,AE),
955 mk_expr(B,TranslationType, Solver,LS,GS,BE),
956 smt_solver_interface_call(Solver,mk_couple(TranslationType, Type,AE,BE,Expr)).
957 % constants and identifiers
958 mk_expr_aux(identifier(Id),_,_,_Solver,LS,GS,Expr) :-
959 !,
960 lookup(Id,LS,GS,Expr).
961 mk_expr_aux(real(RealAtom),real,TranslationType, Solver,_LS,_GS,Expr) :-
962 !,
963 smt_solver_interface_call(Solver,mk_real_const(TranslationType, RealAtom,Expr)).
964 mk_expr_aux(integer(Int),integer,TranslationType, Solver,_LS,_GS,Expr) :-
965 !,
966 smt_solver_interface_call(Solver,mk_int_const(TranslationType, Int,Expr)).
967 mk_expr_aux(min_int,integer,TranslationType, Solver,_LS,_GS,Expr) :-
968 !,
969 get_preference(minint,MinInt),
970 smt_solver_interface_call(Solver,mk_int_const(TranslationType, MinInt,Expr)).
971 mk_expr_aux(max_int,integer,TranslationType, Solver,_LS,_GS,Expr) :-
972 !,
973 get_preference(maxint,MaxInt),
974 smt_solver_interface_call(Solver,mk_int_const(TranslationType, MaxInt,Expr)).
975 mk_expr_aux(boolean_true,boolean,_,Solver,_LS,_GS,Expr) :-
976 !,
977 smt_solver_interface_call(Solver,mk_bool_const(boolean_true,Expr)).
978 mk_expr_aux(boolean_false,boolean,_,Solver,_LS,_GS,Expr) :-
979 !,
980 smt_solver_interface_call(Solver,mk_bool_const(boolean_false,Expr)).
981 mk_expr_aux(string(S),string,TranslationType,Solver,_LS,_GS,Expr) :-
982 !,
983 smt_solver_interface_call(Solver,mk_string_const(TranslationType, S,Expr)).
984 mk_expr_aux(truth,pred,_,Solver,_LS,_GS,Expr) :-
985 !,
986 smt_solver_interface_call(Solver,mk_bool_const(boolean_true,Expr)).
987 mk_expr_aux(falsity,pred,_,Solver,_LS,_GS,Expr) :-
988 !,
989 smt_solver_interface_call(Solver,mk_bool_const(boolean_false,Expr)).
990 mk_expr_aux(bool_set,set(boolean),TranslationType, Solver,_LS,_GS,Expr) :-
991 !,
992 smt_solver_interface_call(Solver,mk_bool_const(boolean_true,True)),
993 smt_solver_interface_call(Solver,mk_bool_const(boolean_false,False)),
994 smt_solver_interface_call(Solver,mk_set(TranslationType, [True,False],Expr)).
995 mk_expr_aux(set_extension(List),set(T),TranslationType, Solver,LS,GS,Expr) :-
996 !,
997 maplist(mk_expr_maplist(TranslationType, Solver,LS,GS),List,SubExprs),
998 ( SubExprs = []
999 -> smt_solver_interface_call(Solver,mk_empty_set(TranslationType, set(T),Expr))
1000 ; smt_solver_interface_call(Solver,mk_set(TranslationType, SubExprs,Expr))
1001 ).
1002 mk_expr_aux(empty_set,Type,TranslationType, Solver,_LS,_GS,Expr) :-
1003 !,
1004 smt_solver_interface_call(Solver,mk_empty_set(TranslationType, Type,Expr)).
1005 % given values
1006 mk_expr_aux(value(V),Type,TranslationType, Solver,LS,GS,Expr) :-
1007 !,
1008 mk_value(Type,V,TranslationType, Solver,LS,GS,Expr).
1009 % ast nodes that can be ignored
1010 mk_expr_aux(convert_bool(P),boolean,TranslationType, Solver,LS,GS,Expr) :-
1011 !,
1012 mk_expr(P,TranslationType, Solver,LS,GS,Expr).
1013 % lets
1014 mk_expr_aux(let_expression(ListOfIDs,ListOfDefinitions,LetExpression),_Type,TranslationType, Solver,LS,GS,Expr) :-
1015 create_let_state(ListOfIDs,ListOfDefinitions,TranslationType, Solver,LS,GS,NewLS),
1016 !,
1017 mk_expr(LetExpression,TranslationType, Solver,NewLS,GS,Expr).
1018 mk_expr_aux(let_predicate(ListOfIDs,ListOfDefinitions,LetExpression),pred,TranslationType, Solver,LS,GS,Expr) :-
1019 create_let_state(ListOfIDs,ListOfDefinitions,TranslationType, Solver,LS,GS,NewLS),
1020 !,
1021 mk_expr(LetExpression,TranslationType, Solver,NewLS,GS,Expr).
1022 % -- cases with functor:
1023 mk_expr_aux(Op, Type, TranslationType, Solver, LS, GS, Expr) :-
1024 functor(Op, Functor, 1),
1025 (Functor == pow_subset; Functor == pow1_subset; Functor == fin_subset; Functor == fin1_subset),
1026 !,
1027 arg(1, Op, A),
1028 Type = set(set(InnerSetType)),
1029 mk_expr(A, TranslationType, Solver, LS, GS, AE),
1030 ( Functor == pow_subset
1031 -> smt_solver_interface_call(Solver, mk_op_pow_subset(TranslationType, AE, set(InnerSetType), Expr))
1032 ; Functor == pow1_subset
1033 -> smt_solver_interface_call(Solver, mk_op_pow1_subset(TranslationType, AE, set(InnerSetType), InnerSetType, Expr))
1034 ; Functor == fin_subset
1035 -> smt_solver_interface_call(Solver, mk_op_fin_subset(TranslationType, AE, set(InnerSetType), Expr))
1036 ; smt_solver_interface_call(Solver, mk_op_fin1_subset(TranslationType, AE, set(InnerSetType), InnerSetType, Expr))
1037 ).
1038 mk_expr_aux(Op, _, TranslationType, Solver, LS, GS, Expr) :-
1039 functor(Op, Functor, 1),
1040 (Functor == domain; Functor == range),
1041 !,
1042 arg(1, Op, A),
1043 mk_expr(A, TranslationType, Solver, LS, GS, AE),
1044 A = b(_,set(CoupleType),_),
1045 CoupleType = couple(Prj1Type,Prj2Type),
1046 ( Functor == domain
1047 -> smt_solver_interface_call(Solver, mk_op_domain(TranslationType, AE, CoupleType, Prj1Type, Prj2Type, Expr))
1048 ; smt_solver_interface_call(Solver, mk_op_range(TranslationType, AE, CoupleType, Prj1Type, Prj2Type, Expr))
1049 ).
1050 mk_expr_aux(Op, Type, TranslationType, Solver, LS, GS, Expr) :-
1051 functor(Op, Functor, 2),
1052 (Functor == domain_restriction; Functor == domain_subtraction; Functor == range_restriction; Functor == range_subtraction),
1053 !,
1054 Type = set(CoupleType),
1055 arg(1, Op, A1),
1056 arg(2, Op, A2),
1057 mk_expr(A1, TranslationType, Solver, LS, GS, AE1),
1058 mk_expr(A2, TranslationType, Solver, LS, GS, AE2),
1059 ( Functor == domain_restriction
1060 -> smt_solver_interface_call(Solver, mk_op_dom_res(TranslationType, AE1, AE2, CoupleType, Expr))
1061 ; Functor == domain_subtraction
1062 -> smt_solver_interface_call(Solver, mk_op_dom_sub(TranslationType, AE1, AE2, CoupleType, Expr))
1063 ; Functor == range_restriction
1064 -> smt_solver_interface_call(Solver, mk_op_ran_res(TranslationType, AE1, AE2, CoupleType, Expr))
1065 ; smt_solver_interface_call(Solver, mk_op_ran_sub(TranslationType, AE1, AE2, CoupleType, Expr))
1066 ).
1067 mk_expr_aux(Op,_,TranslationType, Solver,LS,GS,Expr) :-
1068 functor(Op,Functor,1),
1069 unary_operator(Functor),
1070 !,
1071 arg(1,Op,A),
1072 mk_expr(A,TranslationType, Solver,LS,GS,AE),
1073 smt_solver_interface_call(Solver,mk_op_arglist(TranslationType, Functor, [AE], Expr)).
1074 mk_expr_aux(Op, _, TranslationType, Solver, LS, GS, Expr) :-
1075 functor(Op, Functor, 1),
1076 ( Functor == general_union; Functor == general_intersection),
1077 !,
1078 arg(1, Op, A),
1079 A = b(_,set(set(InnerType)),_),
1080 mk_expr(A, TranslationType, Solver, LS, GS, AE),
1081 ( Functor == general_union
1082 -> smt_solver_interface_call(Solver, mk_op_general_union(TranslationType, AE, set(InnerType), InnerType, Expr))
1083 ; store_explicit_set_unique_id(A, UniqueIdName),
1084 smt_solver_interface_call(Solver, mk_op_general_intersection(TranslationType, UniqueIdName, AE, set(InnerType), InnerType, Expr))
1085 ).
1086 mk_expr_aux(Op,_,TranslationType, Solver,LS,GS,Expr) :-
1087 functor(Op,Functor,2),
1088 binary_operator(Functor),
1089 !,
1090 arg(1,Op,A),
1091 mk_expr(A,TranslationType, Solver,LS,GS,AE),
1092 arg(2,Op,B),
1093 mk_expr(B,TranslationType, Solver,LS,GS,BE),
1094 smt_solver_interface_call(Solver,mk_op(TranslationType, Functor,AE,BE,Expr)).
1095 % error case
1096 mk_expr_aux(Expr,_,_,_,_,_,_) :- !,
1097 add_error_fail(smt_solvers_interface,'mk_expr failed:',Expr).
1098
1099 create_let_state([],[],_,_,S,_,S).
1100 create_let_state([ID|IDs],[Def|Defs],TranslationType, Solver,StateSoFar,GS,State) :-
1101 get_texpr_id(ID,UnwrappedId),
1102 mk_expr(Def,TranslationType, Solver,StateSoFar,GS,Expr),
1103 create_let_state(IDs,Defs,TranslationType, Solver,[id(UnwrappedId,Expr)|StateSoFar],GS,State).
1104
1105 mk_value_maplist(Type,TranslationType, Solver,LS,GS,Val,Expr) :-
1106 mk_value(Type,Val,TranslationType, Solver,LS,GS,Expr).
1107
1108 mk_value(Type,Val,TranslationType, Solver,LS,GS,Expr) :-
1109 (mk_value_aux(Type,Val,TranslationType, Solver,LS,GS,Expr) -> true). % avoid spurious error messages upon backtrack
1110
1111 mk_value_aux(real,RealTerm,TranslationType, Solver,_LS,_GS,Expr) :-
1112 ( RealTerm = term(floating(Real))
1113 ; RealTerm = real(Real)
1114 ),
1115 float(Real),
1116 !,
1117 number_codes(Real, RealCodes),
1118 atom_codes(RealAtom, RealCodes),
1119 smt_solver_interface_call(Solver,mk_real_const(TranslationType,RealAtom,Expr)).
1120 mk_value_aux(real,real(RealAtom),TranslationType, Solver,_LS,_GS,Expr) :-
1121 !,
1122 smt_solver_interface_call(Solver,mk_real_const(TranslationType,RealAtom,Expr)).
1123 mk_value_aux(string,string(Atom),TranslationType, Solver,_LS,_GS,Expr) :-
1124 !,
1125 smt_solver_interface_call(Solver,mk_string_const(TranslationType,Atom,Expr)).
1126 mk_value_aux(integer,int(Int),TranslationType, Solver,_LS,_GS,Expr) :-
1127 !,
1128 smt_solver_interface_call(Solver,mk_int_const(TranslationType,Int,Expr)).
1129 mk_value_aux(boolean,pred_false,_,Solver,_LS,_GS,Expr) :-
1130 !,
1131 smt_solver_interface_call(Solver,mk_bool_const(boolean_false,Expr)).
1132 mk_value_aux(boolean,pred_true,_,Solver,_LS,_GS,Expr) :-
1133 !,
1134 smt_solver_interface_call(Solver,mk_bool_const(boolean_true,Expr)).
1135 % only supported thanks to z3 full sets
1136 mk_value_aux(set(integer),global_set('INTEGER'),TranslationType, z3,_LS,_GS,Expr) :-
1137 !,
1138 smt_solver_interface_call(z3,mk_full_set(TranslationType,set(integer),Expr)).
1139 mk_value_aux(set(string),global_set('STRING'),TranslationType, z3,_LS,_GS,Expr) :-
1140 !,
1141 smt_solver_interface_call(z3,mk_full_set(TranslationType,set(string),Expr)).
1142 mk_value_aux(set(global(X)),global_set(X),_,_Solver,LS,GS,Expr) :-
1143 lookup(X,LS,GS,Expr).
1144 mk_value_aux(set(X),avl_set(Val),TranslationType, Solver,LS,GS,Expr) :-
1145 expand_custom_set_to_list_now(avl_set(Val),Values),
1146 !,
1147 mk_value(set(X),Values,TranslationType, Solver,LS,GS,Expr).
1148 mk_value_aux(set(X),List,TranslationType, Solver,LS,GS,Expr) :-
1149 maplist(mk_value_maplist(X,TranslationType, Solver,LS,GS),List,SubExprs),
1150 !,
1151 ( SubExprs = []
1152 -> smt_solver_interface_call(Solver,mk_empty_set(TranslationType,set(X),Expr))
1153 ; smt_solver_interface_call(Solver,mk_set(TranslationType,SubExprs,Expr))
1154 ).
1155 mk_value_aux(couple(AT,BT),(A,B), TranslationType, Solver,LS,GS,Expr) :-
1156 mk_value(AT,A,TranslationType, Solver,LS,GS,AE),!,
1157 mk_value(BT,B,TranslationType, Solver,LS,GS,BE),
1158 !,
1159 smt_solver_interface_call(Solver,mk_couple(TranslationType, couple(AT,BT),AE,BE,Expr)).
1160 mk_value_aux(record(FieldTypes), rec(Fields), TranslationType, Solver, LS, GS, Expr) :-
1161 create_exprs_for_rec_value_fields(FieldTypes, Fields, TranslationType, Solver, LS, GS, SMTFieldExprs),
1162 !,
1163 smt_solver_interface_call(Solver, mk_record_const(TranslationType,record(FieldTypes),SMTFieldExprs,Expr)).
1164 mk_value_aux(global(Name),fd(Num,Name),_,_Solver,LS,GS,Expr) :-
1165 is_b_global_constant(Name,Num,Constant),
1166 !,
1167 lookup(Constant,LS,GS,Expr).
1168 % error case
1169 mk_value_aux(Type,Value,_,_,_,_,_) :- !,
1170 add_error_fail(smt_solvers_interface,'mk_value failed',[Type,Value]).
1171
1172 is_ground_real(b(unary_minus_real(Real),real,_)) :-
1173 is_ground_real(Real).
1174 is_ground_real(b(real(_),real,_)).
1175 is_ground_real(b(value(_),real,_)).
1176
1177 %% create_exprs_for_rec_value_fields(+FieldTypes, +Fields, +TranslationType, +Solver, +LS, +GS, -FieldExprs).
1178 create_exprs_for_rec_value_fields([], [], _, _, _, _, []).
1179 create_exprs_for_rec_value_fields([field(Name,Type)|TT], [field(Name,Value)|FT], TranslationType, Solver, LS, GS, [Expr|NT]) :-
1180 mk_value(Type, Value, TranslationType, Solver, LS, GS, Expr),
1181 create_exprs_for_rec_value_fields(TT, FT, TranslationType, Solver, LS, GS, NT).
1182
1183 pairwise_union(_, [S],_Solver,Out) :-
1184 !,
1185 Out = S.
1186 pairwise_union(TranslationType, [S|Sets],Solver,Expr) :-
1187 pairwise_union(TranslationType, Sets,Solver,SS),
1188 smt_solver_interface_call(Solver,mk_op(TranslationType,union,S,SS,Expr)).
1189
1190 pairwise_disjoint(TranslationType, [H,T],Solver,EmptySet,Constraint) :- !,
1191 pairwise_disjoint_mk_expr(TranslationType, Solver,H,T,EmptySet,Constraint).
1192 pairwise_disjoint(TranslationType, [H|T],Solver,EmptySet,Constraint) :-
1193 pairwise_disjoint(TranslationType, H,T,Solver,EmptySet,SubConstraints),
1194 pairwise_disjoint(TranslationType, T,Solver,EmptySet,SubConstraint),
1195 smt_solver_interface_call(Solver,mk_op_arglist(TranslationType,conjunct,[SubConstraint|SubConstraints],Constraint)).
1196
1197 pairwise_disjoint(TranslationType, E,[Last],Solver,EmptySet,[C]) :- !,
1198 pairwise_disjoint_mk_expr(TranslationType, Solver,E,Last,EmptySet,C).
1199 pairwise_disjoint(TranslationType, E,[H|T],Solver,EmptySet,[C|Cs]) :-
1200 pairwise_disjoint_mk_expr(TranslationType, Solver,E,H,EmptySet,C),
1201 pairwise_disjoint(TranslationType, E,T,Solver,EmptySet,Cs).
1202
1203 pairwise_disjoint_mk_expr(TranslationType, Solver,A,B,EmptySet,PWConstraint) :-
1204 smt_solver_interface_call(Solver,mk_op(TranslationType,intersection,A,B,Inter)),
1205 smt_solver_interface_call(Solver,mk_op(TranslationType,equal,Inter,EmptySet,PWConstraint)).
1206
1207 mk_sort(TranslationType,Solver,Set) :-
1208 smt_solver_interface_call(Solver,mk_sort(TranslationType,Set)).
1209
1210 setup_deferred_sets(_, _, [], DefSetIdentifiers) :-
1211 !,
1212 DefSetIdentifiers = [].
1213 setup_deferred_sets(TranslationType, Solver, DeferredSets, DefSetIdentifiers) :-
1214 % deferred sets and which are either not unfixed or ProB's default set size preference is not considered -> only create a sort
1215 maplist(mk_sort(TranslationType, Solver), DeferredSets),
1216 mk_deferred_set_identifiers(TranslationType, Solver, DeferredSets, DefSetIdentifiers).
1217
1218 %% create_virtual_enum_elms(+DefaultSetSize, +DefSet, -DefElms).
1219 % For a deferred set D and preference DEFAULT_SETSIZE of 3 we create 'D1', 'D2', and 'D3'.
1220 create_virtual_enum_elms(DefaultSetSize, DefSet, DefElms) :-
1221 create_virtual_enum_elms(1, DefaultSetSize, DefSet, DefElms).
1222
1223 create_virtual_enum_elms(Counter, DefaultSetSize, _, Out) :-
1224 Counter > DefaultSetSize,
1225 !,
1226 Out = [].
1227 create_virtual_enum_elms(Counter, DefaultSetSize, DefSet, [EnumElm|NT]) :-
1228 number_codes(Counter, NC),
1229 atom_codes(AC, NC),
1230 atom_concat(DefSet, AC, EnumElm),
1231 Counter1 is Counter + 1,
1232 assert_virtual_deferred_set_id(EnumElm, fd(Counter,DefSet)),
1233 create_virtual_enum_elms(Counter1, DefaultSetSize, DefSet, NT).
1234
1235 prepare_unfixed_deferred_sets_with_virtual_elms(_, [], []).
1236 prepare_unfixed_deferred_sets_with_virtual_elms(DefaultSetSize, [DefSet|T], [(DefSet,DefElms)|NT]) :-
1237 ( get_user_defined_scope(DefSet,Low,Up,_Span)
1238 -> % a specific deferred set's size might be user defined in the definitions
1239 DeferredSetSize is 1+Up-Low
1240 ; DeferredSetSize = DefaultSetSize
1241 ),
1242 create_virtual_enum_elms(DeferredSetSize, DefSet, DefElms),
1243 prepare_unfixed_deferred_sets_with_virtual_elms(DefaultSetSize, T, NT).
1244
1245 prepare_enumerated_sets_with_elms([], []).
1246 prepare_enumerated_sets_with_elms([EnumSet|T], [(EnumSet,EnumElms)|NT]) :-
1247 % find all global constants belonging to the given set
1248 findall(Cst, is_b_global_constant(EnumSet, _, Cst), EnumElms),
1249 prepare_enumerated_sets_with_elms(T, NT).
1250
1251 setup_sets(TranslationType, Solver, GlobalIdentifiers) :-
1252 ( get_preference(z3_solve_for_animation, true)
1253 -> % Z3 behaves as ProB by considering DEFAULT_SETSIZE preference
1254 findall(DS, (b_global_deferred_set(DS), unfixed_deferred_set(DS)), UnfixedDefSets),
1255 get_preference(globalsets_fdrange, DefaultSetSize),
1256 prepare_unfixed_deferred_sets_with_virtual_elms(DefaultSetSize, UnfixedDefSets, EnumDefSetPairs),
1257 findall(DS, (b_global_deferred_set(DS), \+ unfixed_deferred_set(DS)), DeferredSets),
1258 setup_deferred_sets(TranslationType, Solver, DeferredSets, DefSetIdentifiers)
1259 ; % Z3 behaves differently compared to ProB if deferred sets are used
1260 findall(X, b_global_deferred_set(X), DeferredSets),
1261 setup_deferred_sets(TranslationType, Solver, DeferredSets, DefSetIdentifiers),
1262 EnumDefSetPairs = []
1263 ),
1264 % enumerated sets -> create a dedicated datatype in SMT-LIB
1265 b_get_global_enumerated_sets(EnumeratedSets),
1266 % can not use setof / bagof for some reason
1267 list_to_set(EnumeratedSets, EnumeratedSetsNoDuplicates),
1268 prepare_enumerated_sets_with_elms(EnumeratedSetsNoDuplicates, EnumSetPairs),
1269 append(EnumSetPairs, EnumDefSetPairs, GlobalSetPairs),
1270 maplist(setup_enumerated_set(TranslationType, Solver), GlobalSetPairs, IdentifierLists),
1271 append([DefSetIdentifiers|IdentifierLists], GlobalIdentifiers).
1272
1273 % currently only functional for z3
1274 mk_deferred_set_identifiers(_, cvc4, _, []).
1275 mk_deferred_set_identifiers(TranslationType, z3, DeferredSets, DefSetIdentifiers) :-
1276 maplist(mk_deferred_set_identifiers2(TranslationType), DeferredSets, DefSetIdentifiers).
1277
1278 mk_deferred_set_identifiers2(TranslationType, SetName, id(SetName, SetExpression)) :-
1279 smt_solver_interface_call(z3, mk_full_set(TranslationType, set(global(SetName)), SetExpression)).
1280
1281 setup_enumerated_set(TranslationType, Solver, (SetName,SetElements), [SetIdentifier|Identifiers]) :-
1282 %b_global_set_cardinality(SetName, Cardinality), % don't use b_global_set_cardinality/2 here since it can be different than the actual cardinality due to the preference globalsets_fdrange
1283 length(SetElements, Cardinality),
1284 % make a new sort and create identifiers
1285 smt_solver_interface_call(Solver, mk_sort_with_cardinality(TranslationType, SetName, Cardinality, SetElements, EnumExprs)),
1286 SetIdentifier = id(SetName, SetExpression),
1287 create_enum_element_smt_state(SetElements, EnumExprs, Identifiers),
1288 smt_solver_interface_call(Solver, mk_set(TranslationType, EnumExprs, SetExpression)).
1289
1290 create_enum_element_smt_state([], [], []).
1291 create_enum_element_smt_state([IdName|TIds], [EnumExpr|TExprs], [id(IdName,EnumExpr)|T]) :-
1292 create_enum_element_smt_state(TIds, TExprs, T).
1293
1294 create_smt_state(TranslationType, Solver,Identifiers,State,Exprs) :-
1295 exclude(is_external_function_identifier,Identifiers,LessIdentifiers),
1296 maplist(create_smt_identifier(TranslationType, Solver),LessIdentifiers,State,Exprs).
1297
1298 create_bounded_smt_state(TranslationType, Solver,Identifiers,State,Exprs) :-
1299 maplist(create_bounded_smt_identifier(TranslationType, Solver),Identifiers,State,Exprs).
1300
1301 create_smt_identifier(TranslationType, Solver,b(identifier(Id),Type,_Infos),id(Id,Expr),Expr) :-
1302 ground(Id),
1303 !,
1304 smt_solver_interface_call(Solver,mk_var(TranslationType, Type,Id,Expr)).
1305 create_smt_identifier(_, _, b(identifier(_),Type,_Infos), _, _) :-
1306 add_error_fail(create_smt_identifier, 'Identifier name is not ground for type ~w~n', [Type]).
1307
1308 create_bounded_smt_identifier(TranslationType, Solver, b(identifier(Id),Type,_Infos), id(Id,Expr), Expr) :-
1309 ground(Id),
1310 !,
1311 smt_solver_interface_call(Solver,mk_bounded_var(TranslationType, Type,Id,Expr)).
1312 create_bounded_smt_identifier(_, _, b(identifier(_),Type,_Infos), _, _) :-
1313 add_error_fail(create_bounded_smt_identifier, 'Identifier name is not ground for type ~w~n', [Type]).
1314
1315 is_external_function_identifier(Id) :-
1316 get_texpr_id(Id,Name),
1317 is_external_function_name(Name).
1318
1319 lookup(Id,LS,GS,Expr) :-
1320 ( member(id(Id,Expr),LS) % id defined in local store
1321 ; member(id(Id,Expr),GS) % id defined in global store
1322 ).
1323
1324 contains_unsupported_type_or_expression(TranslationType, Solver, TExpr) :-
1325 contains_unsupported_type_or_expression(TranslationType, Solver, TExpr, _).
1326 contains_unsupported_type_or_expression(TranslationType, Solver, TExpr, Unsupported) :-
1327 map_over_typed_bexpr(smt_solvers_interface:contains_unsupported_aux(TranslationType, Solver), TExpr, Unsupported).
1328
1329 :- public contains_unsupported_aux/4.
1330 contains_unsupported_aux(TranslationType, Solver, TExpr, Expr) :-
1331 get_texpr_expr(TExpr, Expr),
1332 get_texpr_type(TExpr, Type),
1333 ( unsupported_type(TranslationType, Type, Solver)
1334 -> debug_println(19,unsupported_type_for_z3(TranslationType,Type,Solver))
1335 ; ( unsupported_expr(TranslationType, Expr, Type, Solver)
1336 -> functor(Expr,F,A),
1337 debug_println(19,unsupported_expr_for_z3(TranslationType,F/A))
1338 )
1339 ).
1340
1341 % these expressions are not supported by one or more translation types
1342 %% change in Z3: lambda inside recursive functions was declared unsupported until proper support is provided (see https://github.com/Z3Prover/z3/issues/5813)
1343 %% see mk_op_iteration_func_decl in /extensions/z3interface/src/cpp/main.cpp
1344 unsupported_expr(sat, Expr, _, _) :-
1345 !,
1346 \+ (Expr = conjunct(_,_); Expr = disjunct(_,_); Expr = identifier(_); Expr = equal(_,_); Expr = implication(_,_); Expr = equivalence(_,_);
1347 Expr = negation(_); Expr = boolean_true; Expr = boolean_false; Expr = value(pred_true); Expr = value(pred_false)).
1348 unsupported_expr(_, power_of_real(_,_),_,_).
1349 unsupported_expr(_, struct(_),_,_).
1350 unsupported_expr(constructive, closure(_),_,_).
1351 unsupported_expr(constructive, iteration(_,_),_,_).
1352 %%
1353 unsupported_expr(axiomatic, general_union(_),_,_).
1354 unsupported_expr(axiomatic, general_intersection(_),_,_).
1355 unsupported_expr(_,general_product(_,_,_),_,_).
1356 unsupported_expr(_,general_sum(_,_,_),_,_).
1357 unsupported_expr(axiomatic, iteration(_,_),_,_).
1358 unsupported_expr(axiomatic, closure(_),_,_).
1359 unsupported_expr(_,external_pred_call(Pred,_),_,_) :-
1360 Pred \= 'LEQ_SYM'. % introduced by symmetry breaking; we could also try and turn this off in ast_cleanup
1361 unsupported_expr(_,external_function_call(_,_),_,_).
1362 unsupported_expr(_,function(Name,_),_,_) :-
1363 is_external_function_name(Name).
1364 unsupported_expr(_, general_concat(_),_,_).
1365 % the following exprs should have been removed by a rewrite rule
1366 unsupported_expr(axiomatic, pow_subset(_),_,_).
1367 unsupported_expr(axiomatic, pow1_subset(_),_,_).
1368 unsupported_expr(axiomatic, fin_subset(_),_,_).
1369 unsupported_expr(axiomatic, fin1_subset(_),_,_).
1370 unsupported_expr(axiomatic, composition(_,_),_,_).
1371 unsupported_expr(axiomatic, comprehension_set(_,_),_,_).
1372 unsupported_expr(axiomatic, image(_,_),_,_).
1373 unsupported_expr(axiomatic, reverse(_),_,_).
1374 unsupported_expr(axiomatic, range(_),_,_).
1375 unsupported_expr(axiomatic, domain(_),_,_).
1376 unsupported_expr(_,min(_),_,_).
1377 unsupported_expr(_,max(_),_,_).
1378 unsupported_expr(_,card(_),_,_).
1379 unsupported_expr(_,finite(_),_,_).
1380 unsupported_expr(axiomatic, interval(_,_),_,_).
1381 unsupported_expr(_,integer_set(_),_,_).
1382 unsupported_expr(_,real_set(_),_,_).
1383 unsupported_expr(_,float_set(_),_,_).
1384 unsupported_expr(axiomatic,parallel_product(_,_),_,_).
1385 unsupported_expr(axiomatic,direct_product(_,_),_,_).
1386 unsupported_expr(axiomatic, domain_restriction(_,_),_,_).
1387 unsupported_expr(axiomatic, range_restriction(_,_),_,_).
1388 unsupported_expr(axiomatic, domain_subtraction(_,_),_,_).
1389 unsupported_expr(axiomatic, range_subtraction(_,_),_,_).
1390 unsupported_expr(_,overwrite(_,_),_,_).
1391 unsupported_expr(axiomatic, cartesian_product(_,_),_,_).
1392 unsupported_expr(_,function(_,_),_,_).
1393 unsupported_expr(_,not_equal(_,_),_,_).
1394 unsupported_expr(_,not_member(_,_),_,_).
1395 unsupported_expr(_,relations(_,_),_,_).
1396 unsupported_expr(_,partial_function(_,_),_,_).
1397 unsupported_expr(_,total_function(_,_),_,_).
1398 unsupported_expr(_,partial_injection(_,_),_,_).
1399 unsupported_expr(_,total_injection(_,_),_,_).
1400 unsupported_expr(_,partial_surjection(_,_),_,_).
1401 unsupported_expr(_,total_surjection(_,_),_,_).
1402 unsupported_expr(_,total_relation(_,_),_,_).
1403 unsupported_expr(_,surjection_relation(_,_),_,_).
1404 unsupported_expr(_,total_surjection_relation(_,_),_,_).
1405 % certain values are not supported yet
1406 unsupported_expr(_,value(X),_,_) :- \+ ground(X). % can not translate unknown values
1407 unsupported_expr(TranslationType,value(couple(A,B)),couple(AT,BT),Solver) :-
1408 unsupported_expr(TranslationType,value(A),AT,Solver) ;
1409 unsupported_expr(TranslationType,value(B),BT,Solver).
1410 unsupported_expr(_,value(global_set('INTEGER')),_,cvc4).
1411 unsupported_expr(_,value(V),Type,_) :-
1412 V \= [], % empty set can be translated
1413 unsupported_value_type(Type).
1414 unsupported_expr(_,value(fd(Num,SetName)),global(SetName),_) :-
1415 \+ is_b_global_constant(SetName,Num,_). % has been invented by prob but is unnamed
1416 % cvc4 does not support generating a full set of a sort, thus there
1417 % is currently no way of expressing a complete deferred set
1418 unsupported_expr(_,identifier(SetName),set(global(SetName)),cvc4).
1419 % operators only implemented for Z3 (the solver cvc4 uses cvc5, see extensions/cvc4interface)
1420 unsupported_expr(_,identity(_),_,cvc4).
1421 unsupported_expr(_,reflexive_closure(_),_,cvc4).
1422 unsupported_expr(_,convert_int_floor(_),_,cvc4).
1423 unsupported_expr(_,convert_int_ceiling(_),_,cvc4).
1424 unsupported_expr(_,power_of(_,Exponent),_,cvc4) :- % cvc5 only supports constant exponents
1425 \+ Exponent = b(integer(_),_,_),
1426 \+ Exponent = b(value(int(_)),_,_).
1427
1428 % some types are not supported / can not be translated at the moment
1429 unsupported_type(sat,Type,_) :-
1430 !,
1431 \+ (Type == pred; Type == boolean).
1432 unsupported_type(_,freetype,_).
1433 unsupported_type(_,any,_).
1434 unsupported_type(_,seq(_),_). % seq(S) is set(couple(integer,S)) and has been rewritten by seq_rewriter.pl
1435 unsupported_type(_,real,cvc4). % reals are only implemented for Z3
1436 unsupported_type(TranslationType,set(X),S) :-
1437 unsupported_type(TranslationType,X,S).
1438 unsupported_type(TranslationType,couple(A,B),S) :-
1439 unsupported_type(TranslationType,A,S) ; unsupported_type(TranslationType,B,S).
1440
1441 % currently unsupported values
1442 unsupported_value_type(set(T)) :-
1443 unsupported_value_type(T).
1444 unsupported_value_type(couple(A,B)) :-
1445 unsupported_value_type(A) ; unsupported_value_type(B).
1446 unsupported_value_type(global(S)) :-
1447 unfixed_deferred_set(S).
1448
1449
1450 % --------------------------------
1451
1452 % use_module(smt_solvers_interface(smt_solvers_interface)),smt_solvers_interface:smt_add_cnf([1,2,3],[[1],[2,3]]).
1453
1454 smt_add_cnf(Literals,Clauses) :-
1455 smt_add_cnf(z3sat,Literals,Clauses).
1456
1457 :- dynamic stored_solver_cnf_reference/1, stored_literal_avl_map/1.
1458
1459 :- use_module(library(avl),[list_to_avl/2, avl_fetch/3]).
1460 smt_add_cnf(Solver,Literals,Clauses) :-
1461 retractall(stored_solver_cnf_reference(_)),
1462 retractall(stored_literal_avl_map(_)),
1463 (init_interface(Solver) -> true
1464 ; throw(smt_cnf_no_result(solver_not_available))), % failing would mean the CNF is unsatisfiable
1465 smt_reset_cnf(Solver),
1466 format('Sending CNF to solver ~w~n',[Solver]),
1467 start_ms_timer(T0),
1468 maplist(add_literal(Solver),Literals,LitMap),
1469 list_to_avl([pred_true-1,pred_false-2|LitMap],LitAvl), % not sure we need pred_true-1 and pred_false-2 map
1470 assert(stored_literal_avl_map(LitAvl)),nl,
1471 debug_format(9,'Registered literals: ~w~n',[LitMap]),
1472 maplist(add_clause(Solver,LitAvl),Clauses,ClauseRefs),
1473 smt_solver_interface_call(Solver,mk_op_arglist(sat,conjunct,ClauseRefs,CNFRef)),
1474 tools:stop_ms_timer_with_msg(T0,sending_cnf_to_smt_solver(Solver)),
1475 assert(stored_solver_cnf_reference(CNFRef)).
1476
1477 add_clause(Solver,LitAvl,Clause,ClauseRef) :-
1478 maplist(translate_literal(Solver,LitAvl),Clause,ExprList),
1479 debug_format(9,'Sending clause to solver ~w~n',[ExprList]),
1480 smt_solver_interface_call(Solver,mk_op_arglist(sat,disjunct,ExprList,ClauseRef)).
1481
1482 smt_add_extra_clause_cnf(Solver,Clause) :-
1483 retract(stored_solver_cnf_reference(CNFRef)),
1484 stored_literal_avl_map(LitAvl),!,
1485 add_clause(Solver,LitAvl,Clause,NewClauseRef),
1486 smt_solver_interface_call(Solver,mk_op_arglist(sat,conjunct,[CNFRef,NewClauseRef],NewCNFRef)),
1487 debug_println(19,stored_new_clause(Clause)),
1488 assert(stored_solver_cnf_reference(NewCNFRef)).
1489 smt_add_extra_clause_cnf(Solver,Clause) :-
1490 add_internal_error('No CNF stored for adding clause:',smt_add_extra_clause_cnf(Solver,Clause)),fail.
1491
1492
1493 % pass the preference Z3_SAT_THREADS to the Z3 interface (used for Z3's sat and sat_cdcl solvers)
1494 set_z3_sat_threads :-
1495 get_preference(z3_sat_threads,Threads),
1496 smt_solver_interface_call(z3, z3interface:set_sat_threads(Threads)).
1497
1498 smt_solve_cnf(Solver,Model) :-
1499 \+ stored_solver_cnf_reference(_),!,
1500 add_internal_error('No CNF stored for solving:',smt_solve_cnf(Solver,Model)),fail.
1501 smt_solve_cnf(Solver,Model) :-
1502 stored_solver_cnf_reference(CNFRef),
1503 start_ms_timer(T1),
1504 get_preference(time_out, TO),
1505 SelectedSolvers = [sat,sat_cdcl],
1506 AxmRef = -1, % do not solve anything with axiomatic and constructive z3 solver
1507 CnsRef = -1,
1508 set_z3_sat_threads,
1509 smt_solver_interface_call(z3, z3interface:smt_solve_query(SelectedSolvers,AxmRef,CnsRef,CNFRef,TO,SMTResultData)),
1510 tools:stop_ms_timer_with_msg(T1,solving_cnf_with_smt_solver(Solver)),
1511 (debug_mode(off) -> true
1512 ; write('; SMT TRANSLATION: '), nl, pretty_print_smt(z3), nl
1513 ),
1514 write(result_data(SMTResultData)),nl,
1515 SMTResultData = result_tuple(_,SMTResult),
1516 ( SMTResult=sat
1517 -> %smt_solver_interface_call(z3,get_full_model_string(FullModel)),
1518 model_translation:get_full_model_as_avl(Solver,AVL),
1519 %avl:portray_avl(AVL),nl,
1520 avl:avl_to_list(AVL,List),
1521 convert_to_cnf_model(List,1,Model)
1522 ; SMTResult=unsat
1523 -> write('UNSAT'),nl,flush_output,
1524 fail
1525 ; % unknown or time_out: no contradiction was found, hence we must not fail
1526 throw(smt_cnf_no_result(SMTResult)) % caught in b2sat
1527 ).
1528
1529
1530 smt_reset_cnf(_Solver) :- clear_state.
1531
1532 convert_to_cnf_model([],_,R) :- !, R=[].
1533 convert_to_cnf_model([_-X|T],Nr,[Lit|TM]) :-
1534 is_bool(X,Val),!,
1535 (Val=true -> Lit=Nr ; Lit is -Nr),
1536 N1 is Nr+1,
1537 convert_to_cnf_model(T,N1,TM).
1538 convert_to_cnf_model(L,_,R) :- add_error(smt_solvers_interface,'Invalid model value:',L),R=[].
1539
1540 is_bool('z3-define-fun'([],'Bool',Val),Val).
1541
1542
1543 %:- use_module(probsrc(tools_meta), [translate_term_into_atom/2]).
1544 add_literal(Solver,Number,Number-Z3Ref) :-
1545 number_to_atom(Number,Atom),
1546 smt_solver_interface_call(Solver,mk_bounded_var(sat,boolean,Atom,Z3Ref)).
1547
1548 lookup_literal(Literal,LitAvl,Z3Expr) :-
1549 avl_fetch(Literal,LitAvl,Z3Expr).
1550
1551 % we need to ensure that atoms have same order as numbers; otherwise we need to sort model
1552 number_to_atom(Nr,Atom) :- number_codes(Nr,C),
1553 gen_leading_zeros(Nr,9999999,C0s,C),
1554 (10*Nr>=9999999 -> add_warning(smt_solvers_interface,'Too many SAT variables:',Nr) ; true),
1555 atom_codes(Atom,[0'x|C0s]).
1556
1557 gen_leading_zeros(Nr,Lim) --> {Nr>Lim},!.
1558 gen_leading_zeros(Nr,Lim) --> [0'0], {N1 is Nr*10}, gen_leading_zeros(N1,Lim).
1559
1560
1561 translate_literal(Solver,LitAvl,neg(PLiteral),LitRef) :- !,
1562 lookup_literal(PLiteral,LitAvl,Z3Expr) ,
1563 smt_solver_interface_call(Solver,mk_op_arglist(sat,negation,[Z3Expr],LitRef)).
1564 translate_literal(_Solver,LitAvl,Literal,Z3Expr) :-
1565 (prob_pred_literal(Literal) ; Literal > 0),
1566 !,
1567 lookup_literal(Literal,LitAvl,Z3Expr).
1568 translate_literal(Solver,LitAvl,Literal,LitRef) :-
1569 Literal < 0,
1570 PLiteral is Literal * -1,
1571 translate_literal(Solver,LitAvl,neg(PLiteral),LitRef).
1572
1573 prob_pred_literal(pred_true).
1574 prob_pred_literal(pred_false).
1575
1576