1 % (c) 2009-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
6 :- module(cbc_path_solver,[
7 create_testcase_path/5,
8 create_testcase_path_nondet/4,
9
10 testcase_path_timeout/9,
11 testcase_path_timeout_catch/9,
12 testcase_predicate_timeout/3,
13
14 testcase_initialise/5, % not a very nice API call; used in sap, refactor
15 testcase_set_up_events/9, % ditto
16 add_constants_to_state_space/5, add_operations_to_state_space/5, % ditto
17 remove_constants_from_state/4,
18 verify_alloy_command/5
19 ]).
20
21 :- use_module(probsrc(module_information),[module_info/2]).
22 :- module_info(group,cbc).
23 :- module_info(description,'Create paths for Event-B or Classical B via constraint solving').
24
25
26 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27 % test case generation for a given list of event by
28 % constraint solving
29
30 :- use_module(probsrc(b_interpreter)).
31 %:- use_module(b_interpreter_eventb).
32 :- use_module(probsrc(kernel_waitflags)).
33 :- use_module(probsrc(store)).
34 :- use_module(probsrc(debug)).
35 :- use_module(probsrc(bmachine)).
36 :- use_module(probsrc(state_space)).
37 :- use_module(probsrc(solver_interface)).
38 :- use_module(probsrc('cdclt_solver/cdclt_solver')).
39 :- use_module(probsrc(bsyntaxtree),[conjunct_predicates/2]).
40 :- use_module(probsrc('smt_solvers_interface/smt_solvers_interface')).
41 :- use_module(probsrc(tools), [start_ms_timer/1,stop_ms_walltimer_with_msg/2, ajoin/2]).
42 :- use_module(probsrc(error_manager),[add_internal_error/2, enter_new_error_scope/2, exit_error_scope/3,
43 add_error/3, add_message/3,
44 critical_enumeration_warning_occured_in_error_scope/0]).
45
46
47 % use the constraint solver to create a path from an initial state (and valuation of the constants)
48 % with the given list of events/operations and the provided target predicate
49 % INIT is either
50 % init: start from an initial state
51 % invariant start from a state satisfying the invariant
52 % typing start from a state without any constraint, apart from typing
53 % typing(Pred) start from a state where Pred holds (and typing)
54 % pred(P) start from invariant and predicate P
55 % create_testcase_path and create_testcase_path_nondet add the path to the state space
56 % and thus only support init
57
58 create_testcase_path(INIT,Events,EndPredicate,Timeout,Result) :-
59 check_init_from_root(INIT),
60 % allow user interrupts during the search, just fail if that happens
61 testcase_path_timeout(INIT,Timeout,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,R),
62 ( R==ok ->
63 add_constants_to_state_space(ConstantsState,TestStates,ConstTestStates,SetupSequence,StartStateId),
64 add_operations_to_state_space(Operations,StartStateId,ConstTestStates,TransInfos,OpSequence),
65 append(SetupSequence,OpSequence,Result)
66 ; Result = R).
67
68 % same as create_testcase_path: does not react to interrupts, no time-out, but can be backtracked !
69 create_testcase_path_nondet(INIT,Events,EndPredicate,Result) :-
70 check_init_from_root(INIT),
71 % allow user interrupts during the search, just fail if that happens
72 ? testcase_path(INIT,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos),
73 add_constants_to_state_space(ConstantsState,TestStates,ConstTestStates,SetupSequence,StartStateId),
74 add_operations_to_state_space(Operations,StartStateId,ConstTestStates,TransInfos,OpSequence),
75 append(SetupSequence,OpSequence,Result).
76
77 % only paths starting from the root can be added to the state space
78 check_init_from_root(init) :- !.
79 check_init_from_root(INIT) :-
80 add_internal_error('Path from a state other than the root cannot be added to the state space:',INIT),
81 fail.
82
83 % -------------------------------
84 :- use_module(probsrc(clpfd_interface),[catch_clpfd_overflow_call3/3]).
85 % copy of predicate in static_analysis to avoid meta_predicate error in Spider:
86 :- meta_predicate catch_enumeration_warning_and_overflow(0,0).
87 catch_enumeration_warning_and_overflow(Call,Handler) :-
88 % throw/1 predicate raises instantiation_error
89 catch_clpfd_overflow_call3(
90 catch(Call, enumeration_warning(enumerating(_),_Type,_,_,critical), call(Handler)),
91 message, % could also be silent
92 call(Handler)).
93
94 % Res=interrupt if the user interrupted the search; Res can also be timeout, clpfd_overflow or virtual_time_out
95 testcase_path_timeout_catch(Pred,TIMEOUT,Seq,P2,Csts,Ops,TestS,TI,Res) :-
96 enter_new_error_scope(ScopeID,testcase_path_timeout_catch),
97 % call_cleanup also exits the error scope for exceptions and outer time_outs (which catch/3 does not see)
98 call_cleanup(
99 ((catch_enumeration_warning_and_overflow(
100 cbc_path_solver:testcase_path_timeout(Pred,TIMEOUT,Seq,P2,Csts,Ops,TestS,TI,Res),
101 Res=virtual_time_out)
102 -> Found=true ; Found=false),
103 Done=true),
104 (Done==true -> true ; exit_error_scope(ScopeID,_,testcase_path_timeout_catch))),
105 (Found=true
106 -> exit_error_scope(ScopeID,_ErrOcc,testcase_path_timeout_catch)
107 ; (critical_enumeration_warning_occured_in_error_scope ->
108 debug_format(19,'Enumeration warning occurred and is treated as timeout due to failure to find solution.~n',[]),
109 exit_error_scope(ScopeID,_ErrOcc,testcase_path_timeout_catch),
110 Res=virtual_time_out
111 ; exit_error_scope(ScopeID,_ErrOcc,testcase_path_timeout_catch),
112 fail
113 )
114 ).
115
116
117 :- use_module(probsrc(tools_meta),[safe_time_out/3]).
118 :- use_module(extension('user_signal/user_signal'), [user_interruptable_call_det/2]).
119
120 testcase_path_timeout(INIT,0,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,R) :-
121 !,testcase_path_interrupt(INIT,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,R).
122 testcase_path_timeout(INIT,TimeoutMs,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,Result) :-
123 safe_time_out(testcase_path_interrupt(INIT,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,R),
124 TimeoutMs,
125 T),
126 (T==success -> Result=R ; Result=timeout).
127
128 testcase_path_interrupt(INIT,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,Result) :-
129 catch_clpfd_overflow_call3(
130 testcase_path_interrupt2(INIT,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,Result),
131 message, % no need to create warning or error; we return clpfd_overflow as result
132 Result=clpfd_overflow).
133
134 testcase_path_interrupt2(INIT,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos,Result) :-
135 user_interruptable_call_det(testcase_path(INIT,Events,EndPredicate,ConstantsState,Operations,TestStates,TransInfos),
136 Interrupt),
137 (Interrupt==ok -> Result=ok ; Result=interrupt).
138
139 add_constants_to_state_space(ConstantsState,TestStates,TestStates,[],root) :-
140 empty_state(ConstantsState),!.
141 add_constants_to_state_space(ConstantsState,TestStates,ConstTestStates,[Tuple],ConstantsID) :-
142 Tuple = (SetupID,Setup,root,ConstantsID),
143 specfile:create_setup_constants_operation(ConstantsState,complete_properties,Setup),
144 tcltk_interface:tcltk_add_new_transition_transid(root,Setup,ConstantsID,concrete_constants(ConstantsState),[],SetupID),
145 remove_constants_from_state(TestStates,ConstantsState,ConstantsID,ConstTestStates).
146
147 remove_constants_from_state([],_,_,[]).
148 remove_constants_from_state([InState|Irest],Constants,ConstId,[const_and_vars(ConstId,OutState)|Orest]) :-
149 append(OutState,Constants,InState),!, % assume constants are at hend
150 remove_constants_from_state(Irest,Constants,ConstId,Orest).
151
152
153 add_operations_to_state_space([],_,[],[],[]).
154 add_operations_to_state_space([Operation|Orest],PrevId,[State|Srest],[TransInfo|Trest],[Tuple|Irest]) :-
155 Tuple = (OpId,Operation,PrevId,NextId),
156 tcltk_interface:tcltk_add_new_transition_transid(PrevId,Operation,NextId,State,TransInfo,OpId),
157 add_operations_to_state_space(Orest,NextId,Srest,Trest,Irest).
158
159 testcase_path(INITIALISE,Events,EndPredicate,NormalisedConstantsState,OPS,StateSequence,TINFOS) :-
160 init_wait_flags(WF0,[testcase_path]),
161 opt_push_wait_flag_call_stack_info(WF0,using_state(cbc_path_solver,InitialState),WF),
162 (INITIALISE=init
163 -> OPS = [OpInit|Operations], TINFOS = [ITransInfo|OpTransInfos],
164 ? testcase_initialise(ConstantsState,InitialState,OpInit,ITransInfo,WF)
165 % TODO: push Init on WF call stack
166 ; OPS = Operations, TINFOS = OpTransInfos,
167 % TO DO: project away constants and variables not needed for OPS and Predicates
168 ? set_up_start_state(INITIALISE,ConstantsState,InitialState,WF)
169 ),
170 testcase_set_up_events(Events,InitialState,ConstantsState,Operations,States,FinalState,OpTransInfos,WF,WF2),
171 ? eval_predicate(EndPredicate,FinalState,WF2),
172 ? ground_wait_flags(WF2),
173 normalise_states([InitialState|States],StateSequence),
174 normalise_state(ConstantsState,NormalisedConstantsState).
175
176 % set up a start state for the options typing, typing(P), invariant and pred(P) (but not init)
177 set_up_start_state(Option,ConstantsState,InitialState,WF) :-
178 get_start_option_paras(Option,Typing,Pred), !,
179 (Typing=typing
180 -> set_up_a_typed_state(ConstantsState,InitialState,WF) % only set up types
181 ? ; set_up_a_valid_state(ConstantsState,InitialState,WF) % set up invariant
182 ),
183 (Pred=none -> true ; eval_predicate(Pred,InitialState,WF)).
184 set_up_start_state(Option,_,_,_) :-
185 add_internal_error('Illegal start option:',set_up_start_state(Option)),fail.
186
187 get_start_option_paras(typing,typing,none).
188 get_start_option_paras(typing(Pred),typing,Pred). % just use typing from invariant and add P
189 get_start_option_paras(invariant,invariant,none).
190 get_start_option_paras(pred(Pred),invariant,Pred). % add P to invariant
191
192
193 testcase_predicate_timeout(Pred,Timeout,Result) :-
194 ? catch((
195 safe_time_out(testcase_predicate_catch_overflow(Pred,R), Timeout, T),
196 (T==success -> Result=R ; Result=timeout)
197 ), enumeration_warning(_,_,_,_,_), Result=timeout).
198
199 testcase_predicate_catch_overflow(Pred,Result) :-
200 ? catch_clpfd_overflow_call3(
201 (testcase_predicate(Pred), Result=ok),
202 message, % no need to create warning or error; we return clpfd_overflow as result
203 Result=clpfd_overflow).
204
205 testcase_predicate(Option) :-
206 init_wait_flags(WF,[testcase_predicate]),
207 set_up_start_state(Option,_ConstantsState,_InitialState,WF),
208 ? ground_wait_flags(WF).
209
210 eval_predicate(Predicate,State,WF) :-
211 empty_state(EmptyState),
212 ? b_test_boolean_expression(Predicate,EmptyState,State,WF).
213
214 :- use_module(probsrc(b_state_model_check),[set_up_transition/7, set_up_initialisation/5]).
215
216
217 testcase_set_up_events([],State,_ConstState,[],[],State,[],WF,WF).
218 testcase_set_up_events([Event|Erest],InState,ConstantState,[Operation|Orest],
219 [InterState|Srest],OutState,[TransInfo|Trest],WF,WF3) :-
220 set_up_transition(Event,Operation,ConstantState,InState,InterState,TransInfo,WF),
221 push_wait_flag_call_stack_info(WF,after_event(Operation),WF2),
222 testcase_set_up_events(Erest,InterState,ConstantState,Orest,Srest,OutState,Trest,WF2,WF3).
223
224
225
226 testcase_initialise(ConstantState,InitialState,Initialisation,TransInfo,WF) :-
227 ? set_up_constants_state(ConstantState,WF),
228 set_up_initialisation(ConstantState,InitialState,Initialisation,TransInfo,WF). % TO DO: here I would like to be able to set up the invariant instead, if requested by another parameter
229
230 :- use_module(probsrc(b_global_sets),[static_symmetry_reduction_for_global_sets/1]).
231 :- use_module(probsrc(b_enumerate), [b_tighter_enumerate_all_values/2]).
232
233 set_up_constants_state(ConstantsState,_WF) :-
234 \+ not_all_transitions_added(root),
235 ? \+ state_space:max_reached_or_timeout_for_node(root),
236 % We should also check enumeration warnings : [DONE with max_reached_or_timeout_for_node]
237 (state_space:transition(root,_,N) -> true),
238 \+ ( state_space:transition(root,_,N2), N2\=N ),
239 state_space:visited_expression(N,concrete_constants(ConstantsState)),
240 !, % there is only one possible valuation of the constants
241 debug_format(19,'Reusing constant values from state id ~w (only solution for PROPERTIES/axioms)~n',[N]).
242 set_up_constants_state(ConstantState,WF) :-
243 b_get_properties_from_machine(Properties),
244 b_get_machine_constants(Constants),
245 empty_state(EmptyState),
246 set_up_typed_localstate(Constants,_FreshVars,TypedVals,EmptyState,ConstantState,positive),
247 static_symmetry_reduction_for_global_sets(ConstantState), % from b_global_sets
248 b_tighter_enumerate_all_values(TypedVals,WF),
249 ? b_test_boolean_expression(Properties,EmptyState,ConstantState,WF).
250
251 % set up a valid state satisfying the invariant
252 set_up_a_valid_state(ConstantState,ValidState,WF) :-
253 ? set_up_constants_state(ConstantState,WF),
254 b_get_machine_variables(Variables),
255 % create_target_state(Variables,Values,ConstantsState,ValidState,WF),
256 set_up_typed_localstate(Variables,_Values,TypedVals,ConstantState,ValidState,positive),
257 b_tighter_enumerate_all_values(TypedVals,WF),
258 b_get_invariant_from_machine(Invariant),
259 empty_state(EmptyState),
260 b_test_boolean_expression(Invariant,EmptyState,ValidState,WF).
261
262
263
264 set_up_constants_typed_state(ConstantState,WF) :-
265 b_get_machine_constants(Constants),
266 empty_state(EmptyState),
267 set_up_typed_localstate(Constants,_FreshVars,TypedVals,EmptyState,ConstantState,positive),
268 b_tighter_enumerate_all_values(TypedVals,WF).
269
270 % set up a valid state satisfying the typing conditions of the invariant; but not necessarily the invariant
271 set_up_a_typed_state(ConstantState,ValidState,WF) :-
272 set_up_constants_typed_state(ConstantState,WF),
273 b_get_machine_variables(Variables),
274 % create_target_state(Variables,Values,ConstantsState,ValidState,WF),
275 set_up_typed_localstate(Variables,_Values,TypedVals,ConstantState,ValidState,positive),
276 b_tighter_enumerate_all_values(TypedVals,WF).
277
278
279 %% verify_alloy_command(+CmdName, +Solver, -CmdIsValid, -IsCheckCmd, -Res).
280 % Verify a command by solving the translated operation's precondition conjoined with the machine properties.
281 % This is a special case of cbc path checking of length 1 but using a monolithic predicate.
282 % Assumes that a corresponding Alloy model is loaded.
283 % Solver is one of prob, probkodkod, probsmt or z3.
284 % fails after adding an error if the command or solver is unknown
285 verify_alloy_command(ProvidedCmdName, Solver, CmdIsValid, IsCheckCmd, Res) :-
286 (ProvidedCmdName = '_' , b_get_machine_operation(CmdName, _, _, _) -> true % _ as a wildcard for first command
287 ; CmdName = ProvidedCmdName),
288 if(b_get_machine_operation(CmdName, _, _, Body),
289 true,
290 (add_error(cbc_path_solver,'Unknown Alloy command name:',CmdName),
291 findall(Other,b_get_machine_operation(Other, _, _, _),OL),
292 add_message(cbc_path_solver,'Available B operations: ',OL),fail)),
293 (alloy_solver(Solver) -> true
294 ; add_error(cbc_path_solver,'Unknown solver for Alloy command (use prob, probkodkod, probsmt or z3):',Solver),
295 fail),
296 (verify_alloy_command2(CmdName, Body, Solver, CmdIsValid, IsCheckCmd, Res) -> true
297 ; add_internal_error('Call failed:',verify_alloy_command(ProvidedCmdName, Solver, CmdIsValid, IsCheckCmd, Res)),
298 fail).
299
300 alloy_solver(prob).
301 alloy_solver(probkodkod).
302 alloy_solver(probsmt).
303 alloy_solver(z3).
304
305 verify_alloy_command2(CmdName, Body, Solver, CmdIsValid, IsCheckCmd, Res) :-
306 get_precondition_from_translated_alloy_operation(Body, Precondition),
307 b_get_properties_from_machine(Properties),
308 conjunct_predicates([Properties,Precondition], Conj),
309 start_ms_timer(Timer),
310 ( Solver == prob
311 -> solve_predicate(Conj, _, 1, [use_smt_mode/true,use_clpfd_solver/true,use_chr_solver/false,clean_up_pred,allow_improving_wd_mode/true], Res)
312 ; Solver == probkodkod
313 -> solve_predicate(Conj, _, 1, [use_smt_mode/true,use_clpfd_solver/true,use_chr_solver/false,clean_up_pred,allow_improving_wd_mode/true,use_solver_on_load/kodkod], Res)
314 ; Solver == probsmt
315 -> cdclt_solve_predicate(Conj, _SolvedWDPred, Res)
316 ; Solver == z3,
317 smt_solve_predicate(z3, Conj, _, Res)
318 ),
319 ( atom_concat(check, _, CmdName)
320 -> validate_solver_result_for_command(check, Res, CmdIsValid),
321 IsCheckCmd = true
322 ; validate_solver_result_for_command(run, Res, CmdIsValid),
323 IsCheckCmd = false
324 ),
325 (silent_mode(on) -> true
326 ; (Res=solution(_) -> RS=solution ; RS=Res),
327 ajoin(['Checking Alloy command ',CmdName,' with ',Solver,'; result = ',RS],Msg),
328 stop_ms_walltimer_with_msg(Timer,Msg)).
329 % comment in to perform double-checking of result:
330 %(Solver=prob -> true ; eval_strings:double_check_smt_result(nostate(Solver),[],Conj,[],Res)).
331
332 %% validate_solver_result_for_command(+RunOrCheck, +Res).
333 % Note that check commands are negated to search for a counterexample.
334 validate_solver_result_for_command(RunOrCheck, Res, CmdIsValid) :-
335 Res == contradiction_found,
336 !,
337 ( RunOrCheck == check
338 -> CmdIsValid = true
339 ; CmdIsValid = false
340 ).
341 validate_solver_result_for_command(RunOrCheck, Res, CmdIsValid) :-
342 Res = solution(_),
343 ground(Res),
344 !,
345 ( RunOrCheck == run
346 -> CmdIsValid = true
347 ; CmdIsValid = false
348 ).
349 validate_solver_result_for_command(_, _, unknown).
350
351 % We generate precondition/2 in alloy2b. No other guards.
352 get_precondition_from_translated_alloy_operation(b(precondition(TPrecondition,_),subst,_), Precondition) :-
353 !,
354 Precondition = TPrecondition.
355 get_precondition_from_translated_alloy_operation(_, b(truth,pred,[])).