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 :- module(eclipse_interface,
6 [
7 clear_loaded_machines/0,
8 clear_loaded_machines_wo_errors/0,
9 set_application_type/1, % tell ProB wether it is being controlled via ProB1/Rodin or ProB2
10
11 load_b_file/1, load_b_file/2,
12 load_prob_file/1, load_prob_file/2, load_prob_tla_file/1,
13 load_eventb_file/1,
14 load_tla_file/1,
15 load_cnf_file/2,
16
17 find_shortest_trace_to_current_state/1,
18 find_shortest_trace_to_current_state2/2,
19
20 do_modelchecking/4, % for ProB1 for Rodin
21 do_ltl_modelcheck/6,
22
23 getAllOperations/1, % deprecated, remove in 2.0
24 get_machine_objects/5,
25
26 getErrorMessages/2,
27 getErrorMessagesWithSources/2,
28 get_state_errors/2,
29
30 getCurrentStateID/1,
31 getOperationParameterNames/2, % deprecated, remove in 2.0
32
33 % getCurrentStateValues/2, no longer exists ??!
34 getStateValues/2,
35
36 test_boolean_expression_in_node/2, test_boolean_expression_in_node/3,
37
38 setCurrentState/1,
39 computeOperationsForState/2, % Used in ProB 1.0
40
41 evaluate_expression/2,
42
43 %in contrast to evaluate_expression, it supports predicates and does typing
44 evaluate_raw_expression/3,
45 evaluate_raw_expressions/3,
46
47 sap_find_test_path/4,
48 execute_custom_operations/6,
49
50 evaluation_get_top_level/1,
51 evaluation_expand_formula/3,
52 evaluation_formula_text/3,
53 evaluation_get_values/3,
54 evaluation_insert_formula/3,
55
56 deadlock_freedom_check/1,
57 deadlock_freedom_check/2,
58 invariant_check/2,
59
60 refinement_check/2,
61
62 cbc_static_assertion_violation_checking/1,
63 cbc_dynamic_assertion_violation_checking/1,
64 get_vacuous_invariants/1, get_vacuous_guards/1,
65
66 quick_describe_unsat_properties/1,
67 unsat_properties_positions/1,
68 find_state_satisfying_predicate/2
69 ]).
70
71 :- use_module(module_information).
72 :- module_info(group,cli).
73 :- module_info(description,'This module provides the Prolog interface to Java and other languages (usually called via socket server).').
74
75 :- use_module(library(system),[environ/2]).
76 :- use_module(library(lists)).
77
78 :- use_module(error_manager).
79 :- use_module(self_check).
80 :- use_module(bsyntaxtree).
81 :- use_module(version).
82 :- use_module(eventhandling,[announce_event/1]).
83 :- use_module(tools, [safe_atom_codes/2]).
84
85 :- use_module(model_checker).
86
87 :- use_module(b_global_sets,[enum_global_type_limited/2]).
88 :- use_module(translate).
89 :- use_module(store).
90
91 :- use_module(extrasrc(bvisual2),[bv_get_top_level/1, bv_expand_formula/3, bv_get_values/3, bv_insert_formula/3,
92 bv_formula_text/3]).
93
94 :- use_module(library(codesio)).
95
96 :- use_module(state_space,[visited_expression/2, visited_expression_id/1]).
97 :- use_module(tcltk_interface).
98
99
100 :- use_module(b_state_model_check,[cbc_deadlock_freedom_check/3]).
101
102 :- use_module(extension('user_signal/user_signal'), [user_interruptable_call_det/2]).
103
104 %:- use_module(extension('counter/counter'), [get_counter/2]).
105 :- use_module(prob2_interface, [get_state/2]).
106
107
108 :- use_module(preferences,[set_prob_application_type/1]).
109 set_application_type(T) :- % Note: can also be set as probcli option
110 set_prob_application_type(T). % T can be tcltk, probcli, prob2, rodin,...
111
112 /* ------------------------- */
113 /* Machine Loading Interface */
114 /* ------------------------- */
115
116 :- use_module(specfile,[b_or_z_mode/0,set_animation_mode/1,set_animation_minor_mode/1,animation_mode/1,
117 set_currently_opened_b_file/1,
118 set_currently_opening_file/1,
119 set_failed_to_open_file/1, animation_minor_mode/1]).
120 :- use_module(bmachine_construction,[check_machine/4, get_constructed_machine_name/2]).
121 :- use_module(probltlsrc(ltl),[ltl_model_check_with_ce/4,ltl_formula_structure/3]).
122 :- use_module(probltlsrc(ltl_tools),[typecheck_temporal_formula/3]).
123 :- use_module(tcltk_interface, [find_shortest_trace_to_node/4]).
124
125 :- use_module(state_space).
126 :- use_module(bmachine).
127
128
129 %:- use_module(preferences,[reset_all_temporary_preferences/0]).
130 clear_loaded_machines :-
131 clear_loaded_machines_wo_errors,
132 reset_errors,
133 % now done via event-handling: reset_all_temporary_preferences,
134 garbage_collect_atoms,!. % reclaim atoms if possible
135 clear_loaded_machines :- add_error(clear_loaded_machines,'clear_loaded_machines Failed').
136
137 % new profiler
138 %:- use_module('../extensions/profiler/profiler.pl').
139
140 % old profiler
141 %:- use_module(runtime_profiler,[reset_runtime_profiler/0]).
142
143 :- use_module(eventhandling, [announce_event/1]).
144 clear_loaded_machines_wo_errors :-
145 announce_event(reset_specification),
146 announce_event(clear_specification).
147 % Now done via event_handling: reduce_graph_reset reset_runtime_profiler, reset_refinement_checker state_space_initialise, b_machine_hierarchy:reset_hierarchy, b_interpreter:reset_b_interpreter, reset_model_checker haskell_csp:clear_cspm_spec, b_machine_reset,
148 % reset_dynamics, % new profiler
149 % reset_eval_strings.
150
151
152 :- use_module(debug,[debug_println/2]).
153 :- use_module(parsercall,[call_tla2b_parser/1, tla2prob_filename/2]).
154 load_tla_file(Filename) :-
155 call_tla2b_parser(Filename),
156 tla2prob_filename(Filename,GeneratedProbFile),
157 load_prob_tla_file(GeneratedProbFile).
158 load_prob_tla_file(GeneratedProbFile) :-
159 load_prob_file(GeneratedProbFile,[animation_minor_mode(tla)]).
160 load_b_file(Filename) :- load_b_file(Filename,[]).
161 load_b_file(Filename,Options) :-
162 clear_loaded_machines_wo_errors,
163 set_animation_mode(b),
164 set_currently_opening_file(Filename),
165 (bmachine:b_load_machine_from_file(Filename,Options) % we can pass release_java_parser flag here
166 -> set_currently_opened_b_file(Filename)
167 ; set_failed_to_open_file(Filename),fail).
168
169 load_prob_file(Filename) :- load_prob_file(Filename,[]).
170 load_prob_file(Filename,Options) :- % one option is use_fastread
171 clear_loaded_machines_wo_errors,
172 set_animation_mode(b),
173 (member(animation_minor_mode(MM),Options) -> set_animation_minor_mode(MM) ; true),
174 set_currently_opening_file(Filename),
175 (bmachine:b_load_machine_probfile(Filename,Options)
176 -> set_currently_opened_b_file(Filename)
177 ; set_failed_to_open_file(Filename),fail).
178
179 load_eventb_file(Filename) :-
180 clear_loaded_machines_wo_errors,
181 set_animation_mode(b), set_animation_minor_mode(eventb),
182 set_currently_opening_file(Filename),
183 (b_load_eventb_project(Filename)
184 -> set_currently_opened_b_file(Filename)
185 ; set_failed_to_open_file(Filename),fail
186 ).
187
188 :- use_module(extension('satsolver/dimacs_parser'), [convert_dimacs_cnf2b/2]).
189 load_cnf_file(Filename,Options) :-
190 clear_loaded_machines_wo_errors,
191 set_animation_mode(b),
192 set_currently_opening_file(Filename),
193 (convert_dimacs_cnf2b(Filename,BFile), % convert .cnf file to .mch B file
194 load_b_file(BFile,Options)
195 -> set_currently_opened_b_file(Filename)
196 ; set_failed_to_open_file(Filename),fail
197 ).
198
199 % ----------------
200
201 get_event_infos(TransId,Infos) :-
202 findall(Info, transition_info(TransId,Info), Infos1),
203 filter_transition_infos(Infos1,Infos).
204
205 filter_transition_infos([],[]).
206 filter_transition_infos([I|Irest],[O|Orest]) :-
207 filter_transition_info(I,O),
208 filter_transition_infos(Irest,Orest).
209
210 filter_transition_info(event(StackI),event(StackO)) :- !,
211 filter_event_stack(StackI,StackO).
212 filter_transition_info(I,I).
213
214 filter_event_stack([],[]).
215 filter_event_stack([event(Name,Params)|Irest],[event(Name,Strings)|Orest]) :-
216 translate_bvalue_l(Params,Strings),
217 filter_event_stack(Irest,Orest).
218
219 translate_bvalue_l([],[]).
220 translate_bvalue_l([V|Vrest],[S|Srest]) :-
221 translate_bvalue(V,S),
222 translate_bvalue_l(Vrest,Srest).
223
224
225 :- use_module(prob2_interface,[do_modelchecking/5]).
226 % still used by ProB1 for Rodin:
227 %! do_modelchecking(+Time,+Options,-Result,-Stats)
228 do_modelchecking(Time, Options, Result, StatsRes) :-
229 MaxNumberOfStatesToCheck=100000,
230 do_modelchecking(MaxNumberOfStatesToCheck, Time, Options, Result, StatsRes).
231
232 % Mode is starthere, init, checkhere
233 % example call:
234 % XX=identifier(none,xx), Nr=integer(none,4), eclipse_interface:do_ltl_modelcheck(globally(ap(bpred(less(unknown,XX,Nr)))),500,init,Atomics,Structure,Result)
235 do_ltl_modelcheck(Formula,Max,Mode,Atomics,Structure,Result) :-
236 typecheck_temporal_formula(Formula,TypeCheckedFormula,Status),
237 ( Status=ok ->
238 ltl_formula_structure(TypeCheckedFormula,Atomics,Structure),
239 ltl_model_check_with_ce(TypeCheckedFormula,Max,Mode,Result1),
240 ltl_adapt_operations(Result1,Result)
241 ;
242 Atomics=[], Structure=[],
243 Result=typeerror([])).
244
245 ltl_adapt_operations(counterexample(CE1,LoopEntry,PathToCE1), counterexample(CE,LoopEntry,PathToCE)) :- !,
246 filter_ops_and_ids(PathToCE1,root,PathToCE),
247 ltl_adapt_ce(CE1,CE).
248 ltl_adapt_operations(Result,Result).
249
250 ltl_adapt_ce([],[]).
251 ltl_adapt_ce([atom(State,Evals,OpTuple)|Irest],[atom(State,Evals,Transition)|Orest]) :-
252 ltl_adapt_ce2(OpTuple,State,Transition),
253 ltl_adapt_ce(Irest,Orest).
254
255 ltl_adapt_ce2(none,_State,none).
256 ltl_adapt_ce2((TransId,Action,DstId),State,Transition) :-
257 create_operation_term(TransId,Action,State,DstId,Transition).
258
259
260 find_shortest_trace_to_current_state(TraceStrings) :-
261 find_shortest_trace_to_current_state2(TraceStrings, _).
262
263 find_shortest_trace_to_current_state2(TraceStrings, StateIDs) :-
264 current_state_id(ID),
265 find_shortest_trace_to_node(root,ID,TraceIds,StateIDs),
266 extract_term_trace_from_transition_ids(TraceIds,Trace),
267 translate_events(Trace,TraceStrings).
268
269
270 /* ------------------ */
271 /* getErrorMessages/1 */
272 /* ------------------ */
273 /* Returns a list of strings containing all error messages (of the error_manager).
274 Clears all the errors. Returns the empty list if no errors occurred since
275 the last call to getErrorMessages.
276 */
277
278 getErrorMessages(WarningsOnly,ListOfErrMsgs) :-
279 (real_error_occurred -> WarningsOnly = false ; WarningsOnly = true),
280 (get_all_errors_and_reset(ListOfErrMsgs) -> true ; ListOfErrMsgs=[]).
281
282 % the same, but as a list of msg(Source,ErrMsg), where Source is the source the message
283 % was raised with (e.g., setup_constants_inconsistent); used by GetErrorsCommand.java
284 getErrorMessagesWithSources(WarningsOnly,ListOfMsgs) :-
285 (real_error_occurred -> WarningsOnly = false ; WarningsOnly = true),
286 get_all_errors_with_sources_and_reset(ListOfMsgs).
287
288
289 /**
290 get_state_errors(+StateId,-Errors)
291
292 Takes a id for a given state in the state space and produces a list of all
293 state based errors.
294
295 #### called by:
296 * ProB Plugin: GetStateBasedErrorsCommand
297 */
298 get_state_errors(StateId,Errors) :-
299 findall(E, (state_error(StateId,_,E),E \== invariant_violated), Errs),
300 convert_errors(Errs,Errors).
301 :- use_module(error_manager,[extract_span_description/2]).
302 convert_errors([],[]).
303 convert_errors([Error|InRest],[error(Event,Short,Long)|OutRest]) :-
304 ( Error = eventerror(Event,EError,Trace) ->
305 translate_event_error(EError,Short),
306 explain_event_trace(Trace,LongStr,_Span),
307 safe_atom_codes(Long,LongStr)
308 ;
309 (get_event_from_state_error(Error,Event) -> true
310 ; Event = '*unknown*' % we don't know which event is responsible
311 ),
312 translate_state_error(Error,Short),
313 explain_state_error(Error,_Span,LongStr),
314 safe_atom_codes(Long,LongStr)
315 ),
316 convert_errors(InRest,OutRest).
317
318 get_event_from_state_error(abort_error(TYPE,_Msg,_ErrTerm,ErrorContext),Event) :-
319 (get_error_event_from_context(ErrorContext,Event) -> true ; functor(TYPE,Event,_)).
320 get_error_event_from_context(span_context(_,Context),Event) :-
321 get_error_event_from_context(Context,Event).
322 get_error_event_from_context(operation(Event,_State),Event).
323
324 /* ---------------------------- */
325 /* Syntax Information Interface */
326 /* ---------------------------- */
327
328 getAllOperations(L) :-
329 (b_or_z_mode
330 -> findall(OperationName, b_top_level_operation(OperationName), L)
331 ; L=[]). % FIXME: provide list for CSP-M
332
333
334 get_machine_objects(Sections,SetElements,Constants,Variables,Operations) :-
335 b_get_animated_sections(Sections),
336 findall(TId,
337 ( enum_global_type_limited(fd(Nr,Set),_),
338 translate_bvalue(fd(Nr,Set),String),
339 create_texpr(identifier(String),global(Set),[],TId)),
340 SetElements),
341 b_get_machine_constants(Constants),
342 b_get_machine_variables(Variables),
343 b_get_promoted_machine_operations(Operations1),
344 maplist(remove_op,Operations1,Operations).
345 remove_op(TId,NTId) :-
346 remove_bt(TId,identifier(Id),identifier(NId),NTId),
347 remove_op2(Id,NId).
348 remove_op2(op(Op),Op) :- !.
349 remove_op2(Op,Op).
350
351 /* ------------------- */
352 /* Animation Interface */
353 /* ------------------- */
354
355 /* get the ID of the current state */
356 getCurrentStateID(CurID) :-
357 current_state_id(CurID).
358
359 setCurrentState(ID) :- current_state_id(ID),!. % no need to jump
360 setCurrentState(ID) :- /* jumps to the given node; can be backtracked */
361 visited_expression_id(ID),
362 tcltk_interface:tcltk_goto_state(jump,ID).
363
364 :- use_module(specfile,[state_corresponds_to_initialised_b_machine/2]).
365
366 test_boolean_expression_in_node(ResID,BoolExpr) :-
367 test_boolean_expression_in_node(ResID,BoolExpr,'ProB1-Java in state').
368 test_boolean_expression_in_node(ResID,BoolExpr,Kind) :-
369 ? visited_expression(ResID,CurState),
370 (b_or_z_mode
371 -> state_corresponds_to_initialised_b_machine(CurState,CurBState)
372 ; CurState = CurBState),
373 set_context_state(ResID,test_boolean_expression_in_node), % also sets it for external functions
374 ? call_cleanup(b_interpreter:b_test_boolean_expression_cs(BoolExpr,[],CurBState,Kind,ResID),
375 clear_context_state).
376
377 /* USED IN PROB 1.0*/
378 computeOperationsForState(StateID, OpsAndIDs) :- /* compute the enabled operations
379 (without the backtrack options) for a state ID which is not necessarily the current one */
380 visited_expression_id(StateID),
381 tcltk_interface:tcltk_compute_options(StateID,OpsSTAndIDs),
382 %print('OpsSTAndIDs: '),print(OpsSTAndIDs),nl,
383 (filter_ops_and_ids(OpsSTAndIDs,StateID,OpsAndIDs) -> true
384 ; print(filter_ops_and_ids_failed(OpsSTAndIDs)),nl,fail).
385
386 /*
387 op(140,io,23,23,[[in(r14_1m)],'SetRoute',multi_span(460,35,460,71,16934,36,src_span(460,31,460,32,16930,1))],['{<< in(r14_1m) >>}','<< SetRoute >>','<< multi_span(460,35,460,71,16934,36,src_span(460,31,460,32,16930,1)) >>'],[],')
388 */
389
390
391 getOperationParameterNames(Operation,Paras) :-
392 b_get_machine_operation_parameter_names(Operation,Paras).
393
394 filter_ops_and_ids([],_,[]).
395 filter_ops_and_ids([OpTuple|T],StateID,[FOp|FT]) :-
396 ((OpTuple = (Id,OpTerm,Dst), create_operation_term(Id,OpTerm,StateID,Dst,FOp))
397 -> true
398 ; print(filter_op_failed(OpTuple,StateID)),nl, FOp = ('?')),
399 filter_ops_and_ids(T,StateID,FT).
400
401 filter_op(TransId,OpTerm,Src,Dst,JavaOpTerm) :-
402 (animation_mode(cspm) ->
403 filter_op_csp(TransId,OpTerm,Src,Dst,JavaOpTerm)
404 ;
405 filter_op1(TransId,OpTerm,Src,Dst,JavaOpTerm)).
406
407 filter_op1(TransId,OpTerm,Src,Dst,
408 op(TransId,Op,Src,Dst,Arguments,ArgumentsPretty,Infos,State)) :-
409 extract_args_and_return_values(OpTerm,Op,Arguments),
410 get_state(Dst,BState), translate:translate_bstate(BState,State),
411 prettyprint(Arguments,ArgumentsPretty),
412 get_event_infos(TransId,Infos).
413
414 filter_op_csp(TransId,OpTerm,Src,Dst,op(TransId,Op,Src,Dst,Arguments,ArgumentsPretty,Infos,CSPState)) :-
415 extract_csp_args_and_return_values(OpTerm,Op,Arguments),
416 translate:translate_event(OpTerm,PPEvent),
417 tools: split_atom(PPEvent,['.','!'],[_Op|ArgumentsPretty]),
418 get_state(Dst,CSPState),
419 get_event_infos(TransId,Infos).
420
421 extract_csp_args_and_return_values(io(Args,ChName,_SPAN),ChName,Args).
422 extract_csp_args_and_return_values(start_cspm(Name),Name,[]).
423 extract_csp_args_and_return_values(start_cspm_MAIN,'start_cspm_MAIN',[]).
424 extract_csp_args_and_return_values(tick(_),tick,[]).
425 extract_csp_args_and_return_values(tau(_),tau,[]).
426 extract_csp_args_and_return_values(_OP,'?',[]).
427
428 prettyprint([],[]).
429 prettyprint([H|T],[P|R]) :- translate_bvalue(H,P), prettyprint(T,R).
430
431 :- dynamic result_warning_emitted/0.
432
433 extract_args_and_return_values(Term,OpName,Arguments) :-
434 ( Term='-->'(OpTerm,Results) ->
435 ( result_warning_emitted -> true
436 ;
437 print('Warning: results of operations are currently treated like arguments'),nl,
438 assertz(result_warning_emitted)),
439 append(Results,Args,Arguments)
440 ; Term=OpTerm,Args=Arguments
441 ),
442 OpTerm =.. [OpName|Args].
443
444
445
446 % returns all variables and their values of the given state as a list
447 % - constants and variables that are defined for the machine but
448 % not present in the given state get the value '?'
449 % - for each variable a term of the form
450 % binding(Id,Value,PPValue,Tag)
451 % is in the result list, where
452 % Id is the variable's name,
453 % Value is its value a Prolog term
454 % PPValue is its pretty-printed value
455 % NOTE: Tag no longer generated: TO DO REVIEW:
456 % Tag is one of (cst,var,unknown), depending on whether the
457 % variable is a constant, a variable or not defined in the
458 % machine description but present in the state
459 getStateValues(CurID,VariableState) :- /* get variable values */
460 get_state(CurID,CurBState),
461 findall( binding(Id,nope,PPValue),
462 (member(bind(Id,Value),CurBState),
463 (translate_bvalue(Value,PPValue) -> true ; PPValue='**pretty-print failed**')),
464 VariableState).
465
466 /* ------------------------------- */
467
468 /* evaluates an expression in Prolog format and computes the result in the current state */
469 evaluate_expression(Expression,Result) :-
470 current_expression(_CurID,CurState),
471 b_interpreter:b_compute_expression_nowf(Expression,[],CurState,Result,'ProB1-Java',0).
472
473
474
475 %%
476 % Code for invariant debug
477 %
478
479 :- use_module(probsrc(eval_interface),[get_value_string_of_formula/5]).
480
481 evaluate_raw_expression(StateID, Raw, Val):-
482 bmachine:b_type_expression(Raw, [variables], _, TExpr, Errors),
483 ( var(TExpr) ->
484 print(error_while_typing_raw_expression(Errors)),nl,
485 flush_output,
486 !,
487 fail
488 ;
489 get_state(StateID, State),
490 get_value_string_of_formula(State, [], TExpr, 400, Val) % get_value_of_expression or predicate without wd errors
491 ).
492
493 % called in ProB1 for Rodin: de.prob.core/src/de/prob/core/command/EvaluateRawExpressionsCommand.java
494 evaluate_raw_expressions(StateID, Raws, Vals):-
495 maplist(evaluate_raw_expression(StateID), Raws, Vals).
496
497
498
499 /* ------------------------- */
500 /* Execute Operation */
501 /* ------------------------- */
502
503 % MaxNrOfSolutions is the maximum number of solutions ProB returns. Also we should consider existing solutions if the Predicate holds.
504 %:- use_module(succeed_max,[succeed_max_call/2]).
505
506 :- use_module(bmachine,[assert_temp_typed_predicate/1,reset_temp_predicate/0]).
507 :- use_module(b_global_sets,[inline_prob_deferred_set_elements_into_bexpr/2]).
508 /* PROB 1.0 - used by GetOperationByPredicateCommand2.java */
509 execute_custom_operations(CurID, OpName, ParsedPredicate, MaxNrOfSolutions, TOperations, Errors) :-
510 setCurrentState(CurID),
511 ( (OpName = '$initialise_machine';OpName = '$setup_constants' ) -> Scope = [prob_ids(visible),variables];
512 b_top_level_operation(OpName),
513 b_get_machine_operation(OpName,_,Parameters,_),
514 Scope = [identifier(Parameters),prob_ids(visible),variables] % prob scope allows one to use identifiers for deferred set elements
515 ),
516 (MaxNrOfSolutions<1
517 -> add_message(eclipse_interface,'execute_custom_operations MaxNrOfSolutions < 1: ',MaxNrOfSolutions)
518 ; true),
519 bmachine:b_type_expression(ParsedPredicate, Scope, _, TypedPred, Errors),
520 inline_prob_deferred_set_elements_into_bexpr(TypedPred,CP),
521 assert_temp_typed_predicate(CP),
522 set_context_state(CurID,execute_custom_operations),
523 findall(TO, execute_custom_operation(CurID,OpName,TO,MaxNrOfSolutions), TOperations),
524 reset_temp_predicate,
525 clear_context_state.
526
527 % TO DO: check if we need to recompute the operation effect: if the ParsedPredicate is TRUE
528 % (TRUE = equal(none,integer(none,1),integer(none,1)) ) & MaxNrOfSolutions <=
529 % what has already been used previously, we can simply reuse transition from the state space
530
531 execute_custom_operation(CurID,OpName,Operation_op,Max) :-
532 visited_expression(CurID,InState),
533 specfile:compute_operation_effect_max(InState,OpName,Operation,NewState,_TransPathInfo,Max),
534 % logger:writeln_log(sol(OpName,NewState)), %%
535 tcltk_interface:add_trans_id(CurID,Operation,NewState,NewID,TransId),
536 % logger:writeln_log(ids(OpName,Operation,NewID,TransId)), %%
537 create_operation_term(TransId,Operation,CurID,NewID, Operation_op).
538
539
540
541 % create a term op(...) with infos for Java interface about an operation-transition
542 create_operation_term(TransId,Op,CurID,NewID, JavaOpTerm) :-
543 (filter_op(TransId,Op,CurID,NewID, JavaOpTerm) -> true
544 ; add_error(eclipse_interface,'filter_op failed: ', filter_op(TransId,Op,CurID,NewID, JavaOpTerm)),fail).
545
546 /* ------------------------- */
547 /* SAP Testcase Generation */
548 /* ------------------------- */
549 :- use_module(cbcsrc(cbc_path_solver),[create_testcase_path/5]).
550
551 sap_find_test_path(Events,EndPredicate,Timeout,Operations) :-
552 type_predicate(EndPredicate,TypedPredicate),
553 (create_testcase_path(init,Events,TypedPredicate,Timeout,Trace) -> true ; Trace = []),
554 % Trace can be "timeout" or "interrupt", too
555 (is_list(Trace) -> op_tuples_to_full_operations(Trace,Operations) ; Operations=Trace).
556
557 op_tuples_to_full_operations([],[]).
558 op_tuples_to_full_operations([(Id,OpTerm,Src,Dst)|Trest],[Op|Orest]) :-
559 create_operation_term(Id,OpTerm,Src,Dst,Op),
560 op_tuples_to_full_operations(Trest,Orest).
561
562 type_predicate(Predicate,TypedPredicate) :-
563 b_type_expression(Predicate,[variables],pred,TypedPredicate,Errors),
564 add_all_perrors(Errors,[],sap_target_predicate_type_error),
565 no_real_perror_occurred(Errors).
566
567 /* ------------------------- */
568 /* Formula evaluation */
569 /* ------------------------- */
570 evaluation_get_top_level(Tops) :-
571 % Currently, we do not want to see the rodin information positons
572 % in the expression viewer
573 suppress_rodin_positions(CHNG),
574 bv_get_top_level(TopIds),
575 findall( top(Id,Label,Children),
576 ( member(Id,TopIds), bv_expand_formula(Id,Label,Children) ),
577 Tops),
578 reset_suppress_rodin_positions(CHNG).
579 evaluation_expand_formula(Id,Label,Children) :-
580 % Currently, we do not want to see the rodin information positons
581 % in the expression viewer
582 suppress_rodin_positions(CHNG),
583 bv_expand_formula(Id,Label,Children),
584 reset_suppress_rodin_positions(CHNG).
585 % the formula of an entry of the formula tree as text (its label may differ,
586 % e.g. the name of an event for its guard, or with a proof info icon);
587 % Kind is expression, predicate or none (e.g. for a section such as invariants)
588 % used by the ProB Rodin Plugin to offer graphs, e.g. the projection of the state space
589 evaluation_formula_text(Id,Kind,Text) :-
590 suppress_rodin_positions(CHNG),
591 call_cleanup(bv_formula_text(Id,Kind,Text),
592 reset_suppress_rodin_positions(CHNG)).
593 evaluation_get_values(Ids,StateId,Values) :-
594 bv_get_values(Ids,StateId,Values).
595 evaluation_insert_formula(AST,ParentId,Id) :-
596 b_type_expression(AST,[variables],_,Typed,Errors),
597 % this also calls ast_cleanup; we could temporarily set OPTIMIZE_AST to false
598 ( Errors == [] ->
599 bv_insert_formula(Typed,ParentId,Id)
600 ;
601 add_error_and_fail(eclipse_interface,'Could not type-check AST','')).
602
603 /* ------------------------------- */
604 /* Find state satisfying predicate */
605 /* ------------------------------- */
606 :- use_module(b_state_model_check,[b_set_up_valid_state_with_pred/2]).
607 find_state_satisfying_predicate(Predicate,Result) :-
608 b_type_expression(Predicate,[variables],pred,TPredicate,Errors),
609 ( Errors == [] ->
610 find_state_satisfying_predicate1(TPredicate,Result)
611 ;
612 Result = errors(Errors)).
613 :- use_module(clpfd_interface,[catch_clpfd_overflow_call1/1]).
614 find_state_satisfying_predicate1(Predicate,Result) :-
615 user_interruptable_call_det(clpfd_interface:catch_clpfd_overflow_call1(
616 b_state_model_check:b_set_up_valid_state_with_pred(State,Predicate)),
617 InterruptResult),!,
618 ( InterruptResult = interrupted ->
619 Result = interrupted
620 ; State = time_out ->
621 Result = interrupted
622 ;
623 Result = state_found(Transition,StateId),
624 create_helper_transition(root,find_valid_state,State,StateId,Transition)).
625 find_state_satisfying_predicate1(_Predicate,no_valid_state_found).
626
627
628 /* ------------------------- */
629 /* Check for deadlocks */
630 /* ------------------------- */
631
632 :- use_module(solver_interface, [call_with_smt_mode_enabled/1]).
633
634 deadlock_freedom_check(Result) :-
635 create_texpr(truth,pred,[],Predicate),
636 deadlock_freedom_check1(Predicate,Result).
637 deadlock_freedom_check(Predicate,Result) :-
638 b_type_expression(Predicate,[variables],pred,TPredicate,Errors),
639 ( Errors == [] ->
640 deadlock_freedom_check1(TPredicate,Result)
641 ;
642 Result = errors(Errors)).
643 deadlock_freedom_check1(Predicate,Result) :-
644 % always do a deadlock check with SMT mode enabled
645 call_with_smt_mode_enabled(deadlock_freedom_check2(Predicate,Result)).
646 deadlock_freedom_check2(Predicate,Result) :-
647 user_interruptable_call_det(clpfd_interface:catch_clpfd_overflow_call1(
648 b_state_model_check:cbc_deadlock_freedom_check(CheckResult,Predicate,0)),
649 InterruptResult),!,
650 ( InterruptResult = interrupted ->
651 Result = interrupted
652 ; CheckResult = time_out ->
653 Result = interrupted
654 ; CheckResult = deadlock(State) ->
655 Result = deadlock(Transition,StateId),
656 create_helper_transition(root,deadlock_check,State,StateId,Transition)
657 ; CheckResult = no_deadlock(ImpreciseOps),
658 b_state_model_check:add_cbc_deadlock_imprecise_warning(ImpreciseOps),
659 Result = no_deadlock_found).
660 deadlock_freedom_check2(_Predicate,no_deadlock_found).
661
662 create_helper_transition(SrcId,Op,DstState,DstId,Transition) :-
663 tcltk_interface:tcltk_add_new_transition_transid(SrcId,Op,DstId,DstState,[],TransId),
664 transition(SrcId,Action,TransId,DstId),!,
665 create_operation_term(TransId,Action,SrcId,DstId,Transition).
666
667
668 /* ------------------------------- */
669 /* Find values */
670 /* ------------------------------- */
671 %find_values(Commands,Predicate,MaxNumberSolutions,Solutions) :-
672 % setup_userdef_state_space(Commands,root,State,Ids,ConstantsId).
673
674 %setup_userdef_state_space2(copy_state(Id),CState,State,Ids,ConstantsId) :-
675 % visited_expression(Id,S),
676 % ( S=concrete_constants(Constants) ->
677 % (CState=root -> ConstantsId = S ; ConstantsId = CState),
678
679
680 /* ------------------------------- */
681 /* Check for invariant violations */
682 /* ------------------------------- */
683
684 invariant_check(all,Result) :-
685 findall(OpName,b_is_operation_name(OpName),Ops),
686 invariant_check2(Ops,Result).
687 invariant_check(ops(Ops),Result) :-
688 invariant_check2(Ops,Result).
689 invariant_check2(Ops,Result) :-
690 call_with_smt_mode_enabled(user_interruptable_call_det(invariant_check3(Ops,Res,[]), Status)),
691 (Status = interrupted -> Result = interrupted ; Result = Res).
692 invariant_check3([]) --> !.
693 invariant_check3([Op|Rest]) -->
694 invariant_check_for_single_op(Op),
695 invariant_check3(Rest).
696 :- use_module(clpfd_interface,[catch_clpfd_overflow_call1/1]).
697 invariant_check_for_single_op(OpName,In,Out) :-
698 ( clpfd_interface:catch_clpfd_overflow_call1(
699 b_state_model_check:state_model_check_invariant(OpName,State1,Operation,State2)) ->
700 In = [counterexample(OpName,Trans1,Trans2)|Out],
701 atom_concat( invariant_check_ , OpName, RootTrans),
702 create_helper_transition(root, RootTrans,State1,StateId1,Trans1),
703 create_helper_transition(StateId1,Operation,State2,_StateId2,Trans2)
704 ;
705 In = Out).
706
707 /* ------------------------------- */
708 /* CBC Refinement Checking */
709 /* ------------------------------- */
710 :- use_module(symbolic_model_checker(cbc_refinement_checks), [cbc_refinement_check/2]).
711 refinement_check(ResultsString,Result) :-
712 call_with_smt_mode_enabled(cbc_refinement_check(ResultsString,Result)).
713
714 /* ----------------------------- */
715 /* CBC Static Assertion Checking */
716 /* ----------------------------- */
717 :- use_module(b_state_model_check, [cbc_static_assertions_check/1, cbc_dynamic_assertions_check/1]).
718 cbc_static_assertion_violation_checking(Result) :-
719 user_interruptable_call_det(catch_clpfd_overflow_call1(cbc_static_assertions_check(State)),InterruptResult), !,
720 ( InterruptResult = interrupted ->
721 Result = interrupted
722 ; State = time_out ->
723 Result = interrupted
724 ; State = no_counterexample_found ->
725 Result = no_counterexample_found
726 ; functor(State,no_counterexample_exists,_) -> % arity is 3
727 Result = no_counterexample_exists
728 ;
729 State = counterexample_found(RealState),
730 Result = counterexample_found(Transition,StateId),
731 transition_name(static,TransName),
732 create_helper_transition(root,TransName,RealState,StateId,Transition)).
733 cbc_dynamic_assertion_violation_checking(Result) :-
734 user_interruptable_call_det(catch_clpfd_overflow_call1(cbc_dynamic_assertions_check(State)),InterruptResult), !,
735 ( InterruptResult = interrupted ->
736 Result = interrupted
737 ; State = time_out ->
738 Result = interrupted
739 ; State = no_counterexample_found ->
740 Result = no_counterexample_found
741 ; functor(State,no_counterexample_exists,_) -> % arity is 0
742 Result = no_counterexample_exists
743 ;
744 State = counterexample_found(RealState),
745 Result = counterexample_found(Transition,StateId),
746 transition_name(dynamic,TransName),
747 create_helper_transition(root,TransName,RealState,StateId,Transition)).
748
749 transition_name(dynamic,Name) :- animation_minor_mode(eventb),!,
750 Name = 'context_theorems_check'.
751 transition_name(dynamic,dynamic_asserion_check).
752 transition_name(static,Name) :- animation_minor_mode(eventb),!,
753 Name = 'invariant_theorems_check'.
754 transition_name(static,static_asserion_check).
755
756 /* ------------------------- */
757 /* Generate Visualizations */
758 /* ------------------------- */
759
760 get_vacuous_invariants(L) :-
761 findall(I,vacuous_invariant(I),L).
762
763 vacuous_invariant(Inv) :-
764 b_get_invariant_from_machine(Invariant),
765 ? b_interpreter:member_conjunct(Inv,Invariant,_),
766 get_texpr_expr(Inv,IE),get_disj_lhs(IE,LHS),
767 print('Checking vor vacuity: '), translate:print_bexpr(Inv),nl,
768 ? (test_boolean_expression_in_node(ResID,LHS,'vacuous invariant')
769 -> print(rhs_triggered_in_state(ResID)),nl,nl, % Implication/disjunction trigger in at least one state
770 fail
771 ; print(' *** VACUOUS *** '),nl,nl
772 ).
773
774 get_disj_lhs(implication(LHS,_),LHS).
775 get_disj_lhs(disjunction(LHS,_),NLHS) :- create_negation(LHS,NLHS).
776
777 get_vacuous_guards(L) :-
778 findall(G,vacuous_guard(_,G),L).
779
780 :- use_module(debug,[debug_format/3]).
781 :- use_module(probsrc(tools_strings),[ajoin/2]).
782 vacuous_guard(OpName,Result) :-
783 get_guard_with_one_negated(OpName,Guard,Neg),
784 translate:translate_bexpression_with_limit(Guard,GuardTS),
785 debug_format(19,'Checking vor vacuity: ~w : ~w~n',[OpName,GuardTS]),
786 %translate:print_bexpr(Neg),nl,
787 (test_boolean_expression_in_node(ResID,Neg,'vacuous guard')
788 -> debug_println(19,guard_individually_false_in(ResID)),
789 fail
790 ; debug_println(19,' *** VACUOUS *** '),
791 ajoin([OpName,' : ',GuardTS],Result)
792 ).
793
794
795 :- use_module(b_operation_guards,[get_operation_enabling_condition/7]).
796 %:- use_module(b_ast_cleanup, [clean_up/3]).
797 :- use_module(b_interpreter_components,[construct_optimized_exists/3]).
798
799 % get a guard, by translating all parameters into existential quantifiers
800 get_guard_with_one_negated(OpName,SingleGuard,FullModifiedGuard) :-
801 get_operation_enabling_condition(OpName,Parameters,EnablingCondition,_BecomesSuchVars,_Precise,false,true),
802 % TO DO: partition; avoid lifting becomes_such_that conditions
803 % (in EventB the feasibility PO will ensure that Guard => BecomeSuchThat is ok)
804 negate_one_guard(EnablingCondition,SingleGuard,ModifiedEnablingCondition),
805 construct_optimized_exists(Parameters,ModifiedEnablingCondition,FullModifiedGuard).
806
807 :- use_module(probsrc(bsyntaxtree),[conjunction_to_list/2]).
808 negate_one_guard(Conjunct,SingleGuard,ModifiedConjunct) :-
809 conjunction_to_list(Conjunct,L),
810 append(Rest1,[SingleGuard|Rest2],L),
811 create_negation(SingleGuard,NegSingleGuard),
812 append(Rest1,[NegSingleGuard|Rest2],NewGuard), % TO DO: better treatment for well-definedness !?
813 conjunct_predicates(NewGuard,ModifiedConjunct).
814
815 :- use_module(b_interpreter, [tcltk_quick_describe_unsat_properties/2, tcltk_unsatisfiable_components_exist/0,
816 get_unsat_properties_positions/1]).
817 % used by QuickDescribeUnsatPropertiesCommand.java and itself by ExploreStateCommand.java
818 quick_describe_unsat_properties(Res) :-
819 tcltk_unsatisfiable_components_exist
820 -> tcltk_quick_describe_unsat_properties(list(TRes),_Status), % sometimes this can be 'The properties were satisfiable' if tcltk_unsatisfiable_components_exist faulty
821 Res = unsat_properties(TRes) % TO DO: use Status to say unsat or unknown_properties
822 ; Res = no_unsat_properties_found.
823 % used by GetUnsatPropertiesPositionsCommand.java, for problem markers on the axioms
824 unsat_properties_positions(Res) :-
825 (tcltk_unsatisfiable_components_exist -> get_unsat_properties_positions(Res) ; Res = []).
826 % TODO: integrate WD prover and Z3 bup core here