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 % tcltk_interface.pl
6 :- module(tcltk_interface,[
7 tcltk_goto_state/2,
8 tcltk_add_new_transition_transid/6,
9 tcltk_add_new_transition/5,
10 tcltk_get_options/1, tcltk_get_options_dest_info/1, tcltk_get_state/1, tcltk_get_state/2,
11 tcltk_get_options_or_candidates/2, tcltk_get_options_candidate_nr_name/2,
12 potentially_enabled_operation/4,
13 tcltk_get_options_nr_description/2,
14 tcltk_get_history_nr_description/2,
15 tcltk_get_history_nr_origin_str/2, tcltk_edit_history_nr_origin_str/1,
16
17 tcltk_get_state_errors/1, tcltk_get_detailed_state_error/6,
18 tcltk_open_state_error_in_editor/1,
19 tcltk_get_line_col/5,
20 tcltk_current_state_invariant_violated/0,
21 tcltk_get_status/3,
22 tcltk_get_ops_with_virtual_timeout/1,
23 tcltk_get_ops_with_real_timeout/1,
24 tcltk_get_ops_user_interrupt_occurred/0,
25
26 tcltk_compute_options/2,
27 can_generate_dot_from_last_state_error/0,
28 tcltk_initialise/0, tcltk_reset/0, reset_animation_history/0,
29
30 tcltk_perform_nr/1, tcltk_random_perform/0, tcltk_random_perform/1,
31 tcltk_perform_nr_option/3,
32 tcltk_perform_action_term/2,
33 tcltk_is_sync_event/1,
34
35 tcltk_exists_an_open_node/0, tcltk_goto_an_open_node/0,
36 tcltk_goto_max_reached_node/0, tcltk_goto_timeout_node/0,
37 tcltk_state_exists_with_invariant_violated/0,
38 tcltk_goto_an_invariant_violation/0, tcltk_goto_node_with_id/1,
39 tcltk_try_goto_node_with_id/1,
40 tcltk_current_node_has_no_real_transition/0, tcltk_current_node_has_real_transition/0,
41 tcltk_current_node_has_partial_transition/0,
42 tcltk_goto_a_non_deterministic_node/1, tcltk_goto_a_non_deterministic_output_node/1,
43 tcltk_goto_a_branching_node/0, tcltk_goto_a_non_resetable_node/0,
44 tcltk_state_space_only_has_root_node/0, tcltk_no_constants_or_no_inititalisation_found/0,
45 tcltk_goto_event_list_property_violation/3, tcltk_goto_state_enabling_operation/2,
46 tcltk_find_max_reached_node/0, tcltk_find_max_reached_node/1,
47 tcltk_search_among_existing_nodes/6,
48 find_invariant_violation_among_not_checked_nodes/1,
49
50 tcltk_model_check/11, do_model_check/12,
51 tcltk_set_dbf_mode/1, tcltk_dbf_modes/1,
52 tcltk_mark_current_node_to_be_recomputed_wo_timeout/0,
53 tcltk_mark_current_node_to_be_recomputed_with_random_enum/0,
54 tcltk_finish_current_node_to_be_recomputed_with_random_enum/0,
55 tcltk_hash_model_checking_imprecise/0,
56 tcltk_clear_state_space_and_refocus_to_current_state/0,
57
58 tcltk_constraint_based_check/1,
59 tcltk_constraint_based_check_op/2, tcltk_constraint_based_check_op/3,
60 tcltk_constraint_based_check/2, tcltk_constraint_based_check_with_timeout/2, tcltk_constraint_based_check_with_timeout/3,
61 tcltk_cbc_find_trace/2, tcltk_cbc_find_trace/4,
62 tcltk_cbc_refinement_check/2,
63 tcltk_constraint_find_valid_state/0,
64 tcltk_constraint_find_maximal_valid_state/0,
65 tcltk_constraint_find_dynamic_assertion_violation/0,
66 tcltk_constraint_find_valid_state_with_pred/3,
67 tcltk_constraint_find_deadlock_state/1,
68 tcltk_constraint_find_deadlock_state_with_goal/2,
69 tcltk_constraint_find_deadlock_state_with_goal/3,
70 tcltk_constraint_find_static_assertion_violation/1,
71 tcltk_check_if_feasible_operation/4,
72 cbc_constraint_find_static_assertion_violation/2,
73
74 tcltk_can_backtrack/0, tcltk_can_backtrack/1,
75 tcltk_can_forward/0, tcltk_can_forward/1,
76 tcltk_prepare_for_reload/0,
77 tcltk_backtrack/0, tcltk_backtrack/1, tcltk_fast_backtrack/0, tcltk_fast_forward/0, tcltk_forward/0,
78 tcltk_execute_trace_to_current_node/0, tcltk_find_shortest_trace_to_current_node/1,
79 tcltk_execute_longest_trace_from/1,
80 tcltk_get_history/1,
81 tcltk_perform_action_string/3,
82 tcltk_perform_action/2,
83 tcltk_perform_action/4,
84
85 tcltk_open_xtl_file/1,
86 tcltk_open_z_file/1, tcltk_open_z_tex_file/1,
87 tcltk_open_alloy_file/1, tcltk_open_alloy_prolog_ast_file/1,
88 tcltk_open_cspm_file/1,
89 tcltk_add_csp_file/1,
90 tcltk_load_packaged_eventb_file/1,
91 tcltk_load_cnf_file/1,
92
93 tcltk_verify_alloy_cmd/4,
94 tcltk_get_alloy_cmd_names/1,
95 tcltk_load_alloy_cmd_in_current_translation/1,
96
97 tcltk_machine_has_assertions/0,
98 tcltk_unique_top_level_operation/1, tcltk_top_level_operations/1,
99
100 compute_all_transitions_if_necessary/0,
101 compute_all_transitions_if_necessary/2,
102 compute_state_information_if_necessary/0, % compute transitions and invariant
103 compute_invariant_if_necessary/3,
104 check_invariantKO/2,
105 check_invariantKO/3,
106 catch_clpfd_overflow_call_for_state/4,
107 compute_ample_set/3,
108 compute_all_transitions/2,
109 add_transition/4,
110 add_trans_id/5,
111 add_trans_id_infos/6,
112
113 tcltk_has_eventtrace/1, tcltk_show_eventtrace/2,
114 tcltk_execute_model/3,
115 tcltk_execute_trace_to_node/1,
116 find_shortest_trace_to_node/4,
117
118 tcltk_explore_csp_process/2, tcltk_visualize_csp_process/2,
119 get_csp_process_id/2, get_csp_process_stats/1,
120
121 tcltk_add_user_executed_operation/2, tcltk_add_user_executed_operation/3,
122 tcltk_add_user_executed_operation_typed/4, tcltk_add_user_executed_operation_typed/6,
123 tcltk_add_user_executed_statement/3,
124 tcltk_add_user_modify_variable_transition/2, tcltk_add_user_modify_variable_transition/4,
125 tk_get_possible_language_specific_top_level_event/3,
126
127 tcltk_analyse_option/2,
128 tcltk_analyse/6,
129 tcltk_show_typing_of_variables_and_constants/1,
130 tcltk_show_current_state/1,
131 tcltk_eval/4, interruptable_tcltk_eval/4,
132 tcltk_eval_as_table/2,
133 tcltk_find_value_as_table/3, find_value_in_cur_state/4, tcltk_find_value_as_graph/3,
134 tcltk_time_call/1, eval_elapsed_time/1,
135 tcltk_check_csp_assertions/2, tcltk_check_csp_assertion/4, tcltk_check_csp_assertion/5,
136 checkAssertion/5,
137 tcltk_get_vacuous_guards/1,
138 tcltk_get_vacuous_invariants/1, tcltk_get_vacuous_invariants_table/1,
139 tcltk_operations_covered_info/3, operation_name_covered/1,
140 tcltk_show_expression_as_dot/2,
141 generate_dot_from_formula/2,
142 generate_dot_from_invariant/1, generate_dot_from_properties/1, generate_dot_from_assertions/1,
143 generate_dot_from_deadlock_po/1, generate_dot_from_goal/1, generate_dot_from_last_span_predicate/1,
144 generate_dot_from_operation/2, generate_dot_from_operation_with_params/4,
145 write_dot_file_for_pred_expr/2,
146 write_dot_file_for_value_as_tree/2,
147 evaluate_expression_over_history_to_csv_file/2, tcltk_evaluate_expression_over_history/2,
148 translate_error_for_tclk/2,
149 tcltk_set_initial_machine/0, tcltk_clear_machine/0,
150 % set_tcltk_cspm_mode/0, unset_tcltk_cspm_mode/0,
151 tcltk_open_b_file/1, tcltk_open_b_file_for_minor_mode/2,
152 tcltk_run_ltsmin/5,
153 tcltk_save_history_as_trace_file/1,
154 tcltk_animate_until/4,
155
156 tcltk_bv_get_tops/1,
157 tcltk_bv_get_structure/3,
158 tcltk_bv_is_leaf/2,
159 tcltk_bv_get_values/3,
160 tcltk_bv_get_value/3,
161 tcltk_bv_show_formula_as_dot_tree/2,
162 tcltk_bv_show_formula_as_dot_graph/2,
163 tcltk_bv_show_value_as_dot_tree/2,
164 tcltk_bv_get_pp_formula_string/2,
165 tcltk_show_identifier_value_as_dot_tree/2, % a version of the above independent of bvisual
166 tcltk_bv_get_unlimited_value/3, tcltk_bv_get_unlimited_value_atom/2,
167
168 tcltk_get_constants_predicate/1, tcltk_get_constants_predicate/3,
169
170 get_cbc_data_base_id_checks/1, get_cbc_data_base_text_checks/1,
171
172 tcltk_write_uml_sequence_chart/1,
173
174 get_ltl_formulas_from_file/2,
175 tcltk_mcts_auto_play/0, tcltk_mcts_auto_play/1, mcts_auto_play_available/0,
176 tcltk_simplify_predicate/2, % not used
177 tcltk_get_possible_completions/2,
178
179 tcltk_start_simulation/0,
180 tcltk_peform_simulation_steps/4, tcltk_simulation_time/1, tcltk_delay_until_next_step/1,
181 tcltk_backtrack_simulation_step/0, tcltk_can_backtrack_simulation_step/0,
182 tk_get_simb_history_table/1, tcltk_get_simb_history_length/1,
183 tk_get_simb_scheduling_table/1, tk_get_simb_activations/1, tk_get_simb_activation_details/3,
184 tk_get_simb_scheduling_table_stats/1,
185 tcltk_print_simb_activation_graph/1
186 ]).
187
188
189 :- meta_predicate call_pred_on_expanded_state(3,-,-,-).
190 :- meta_predicate map_over_history(3,-).
191 :- meta_predicate tcltk_time_call(0).
192 :- meta_predicate catch_clpfd_overflow_call_for_state(-,-,0,0).
193 :- meta_predicate add_csp_process_id1(-,-,1).
194
195 %prob_use_module(X) :- load_files(X,[if(changed),load_type(source),compilation_mode(compile)]).
196
197 /* load all necessary modules */
198 :- use_module(library(random)).
199 :- use_module(library(lists)).
200
201 :- use_module(library(ordsets)).
202 :- use_module(library(avl)).
203
204 :- use_module(module_information).
205 :- module_info(group,tcltk).
206 :- module_info(description,'Interface between the Tcl/Tk GUI, the CLI and the internal modules.').
207
208 :- use_module(typechecker).
209 :- use_module(self_check).
210 :- use_module(probsrc(preferences)).
211 :- use_module(probsrc(debug)).
212 :- use_module(error_manager).
213 :- use_module(kernel_waitflags).
214 :- use_module(probsrc(tools)).
215 :- use_module(probsrc(specfile)).
216 :- use_module(probsrc(state_space_exploration_modes)).
217 :- use_module(probsrc(translate)).
218 :- use_module(probsrc(b_state_model_check)).
219 :- use_module(probsrc(bmachine)).
220 :- use_module(probsrc(b_interpreter)).
221 :- use_module(probsrc(b_trace_checking)).
222 :- use_module(probsrc(bsyntaxtree)).
223 :- use_module(kernel_objects).
224 :- use_module(probsrc(state_space)).
225 :- use_module(extension('plspec/plspec/plspec_core'),[set_error_handler/1]).
226 :- use_module(extension('plspec/plspec/prettyprinter'),[pretty_print_error/1]).
227 prob_plspec_error_handler(ErrTerm) :- pretty_print_error(ErrTerm),
228 add_internal_error('Error detected by plspec',ErrTerm).
229 :- set_error_handler(tcltk_interface:prob_plspec_error_handler).
230 :- use_module(model_checker).
231 :- use_module(dotsrc(visualize_graph)).
232 :- use_module(dotsrc(state_space_reduction)).
233 :- use_module(dotsrc(state_custom_dot_graph)).
234 :- use_module(succeed_max).
235 %:- use_module(testcase_generator).
236 :- use_module(prozsrc(proz),[open_proz_file/2]).
237 :- use_module(dotsrc(reduce_graph_state_space)).
238 :- use_module(b_read_write_info).
239 %:- use_module(flow).
240 :- use_module(probltlsrc(ltl),[parse_and_preprocess_formula/3, parse_ltlfile/2,
241 pp_ltl_formula/2, ltl_model_check_with_ce1/5,
242 is_fairness_implication/1, tcltk_play_ltl_counterexample/2]).
243 :- use_module(probltlsrc(ctl),[ctl_model_check_with_ce/6, tcltk_play_ctl_counterexample/2]).
244 %:- use_module('promela/promela_ncprinter').
245 :- use_module(extrasrc(bvisual2),[bv_get_top_level/1, bv_expand_formula/3, bv_get_values/3, bv_get_btvalue/4,
246 bv_get_stored_formula_expr/2, bv_is_explanation_node/1, bv_get_value_unlimited/3]).
247 :- use_module(b_show_history).
248 :- use_module(probcspsrc(haskell_csp),[parse_single_csp_declaration/3]).
249 %:- use_module(probcspsrc(slicer_csp),[slice_from_program_point/14]).
250 :- use_module(value_persistance, [save_constants/1,add_new_transitions_to_cache/1]).
251 :- use_module(cbcsrc(cbc_path_solver),[create_testcase_path_nondet/4,verify_alloy_command/5]).
252 :- use_module(dotsrc(dot_graph_generator), [gen_dot_graph/3, gen_dot_graph/6, list_to_dot_record/2, use_new_dot_attr_pred/7]).
253 :- use_module(dotsrc(uml_generator),[write_uml_sequence_chart/1]).
254
255 /* main program
256 * ============
257 */
258
259
260 /*
261 Start server for LTSmin
262 */
263
264 :- use_module(extension('ltsmin/ltsmin'),[start_ltsmin/4]).
265
266
267 % Backend = symbolic or sequential
268 tcltk_run_ltsmin(Backend,NoDead,NoInv,UsePOR,Res) :-
269 % in case of POR we can also enable/disable use_cbc_analysis preference
270 (UsePOR == true -> MoreFlags = [por] ; MoreFlags=[]),
271 start_ltsmin(Backend, [NoDead, NoInv], MoreFlags,Result),
272 get_check_name(NoDead,NoInv,Kind),
273 process_ltsmin_result(Result,Kind,Res).
274
275 % get_check_name(+NoDead,+NoInv,-Kind)
276 get_check_name(true,false,Kind) :- Kind = 'INVARIANT'.
277 get_check_name(false,true,Kind) :- Kind = 'DEADLOCK'.
278 get_check_name(false,false,Kind) :- Kind = 'DEADLOCK or INVARIANT'. % default for ProB2 if neither nodead nor noinv given
279 get_check_name(true,true,Kind) :- Kind = 'LTL'. % neither deadlocks nor invariants checked
280
281 :- use_module(tools_printing,[format_with_colour_nl/4]).
282 :- use_module(extension('ltsmin/ltsmin_trace'),[csv_to_trace/3]).
283 process_ltsmin_result(ltsmin_model_checking_aborted,_Kind,model_checking_aborted) :- !,
284 add_warning(ltsmin_model_checking_aborted,'LTSMin was aborted (e.g., by CTRL-C)').
285 process_ltsmin_result(ltsmin_model_checking_ok,Kind,no_counter_example_found) :-
286 format_with_colour_nl(user_output,green,'LTSMin found no ~w Counter Example',Kind).
287 process_ltsmin_result(ltsmin_counter_example_found(CsvFile),Kind,counter_example_found) :-
288 format_with_colour_nl(user_output,[red,bold],'LTSMin found ~w Counter Example',Kind),
289 csv_to_trace(CsvFile,States,Transitions),
290 length(Transitions,TLen), format('*** REPLAYING TRACE with length ~w: ~w~n', [TLen, Transitions]),
291 % print(States),nl,
292 % length(States,SLen), print(state_len(SLen)),nl,
293 (replay_ltsmin_trace(States,Transitions) -> true
294 ; add_error(process_ltsmin_result,'Could not replay trace:',Transitions)).
295
296 replay_ltsmin_trace([],[]).
297 replay_ltsmin_trace([State|TS],[TransName|TT]) :-
298 (find_successor_state(State,TransName)
299 -> replay_ltsmin_trace(TS,TT)
300 ; add_error(replay_ltsmin_trace,'Could not execute:',trans_to(TransName,State)),fail).
301
302 :- use_module(state_space,[visited_expression/2]).
303 find_successor_state(EState,'$init_state') :- !,
304 tcltk_reset,
305 compute_all_inits, !,
306 is_initial_state_id(NewID),
307 visited_expression(NewID,State), % print(found_initial(State,EState,NewID)),nl,
308 expand_const_and_vars_to_full_store(State,EState), !,
309 tcltk_execute_trace_to_node(NewID).
310 find_successor_state(EState,TransName) :-
311 tcltk_get_options(_),
312 current_options(Options), % print(Options),nl,
313 member( (_,_Action,ActionOpAsTerm,NewID), Options),
314 get_operation_name(ActionOpAsTerm,TransName),
315 visited_expression(NewID,State), % print(found_transition(State,EState,NewID,ActionOpAsTerm)),nl,
316 expand_const_and_vars_to_full_store(State,EState), !, % TODO: only compare variables
317 tcltk_goto_state(ActionOpAsTerm,NewID).
318
319 % compute all INITIALISATIONS
320 compute_all_inits :- compute_all_transitions_if_necessary(root), fail.
321 compute_all_inits :- is_concrete_constants_state_id(ID), compute_all_transitions_if_necessary(ID), fail.
322 compute_all_inits.
323
324 /* -------------------------------------------------------------------- */
325
326 %tcltk_find_untyped_vars(Vs) :- find_untyped_vars(Vs), Vs \== [].
327
328 %tcltk_find_untyped_consts(Vs) :- find_untyped_consts(Vs), Vs \== [].
329
330
331 tcltk_find_max_reached_node :- tcltk_find_max_reached_node(_).
332 tcltk_find_max_reached_node(ID) :- max_reached_or_timeout_for_node(ID).
333
334
335 tcltk_current_node_has_no_real_transition :-
336 \+ tcltk_current_node_has_real_transition.
337 tcltk_current_node_has_real_transition :-
338 current_state_id(CurID),
339 transition(CurID,Trans,_),
340 (CurID \= root -> true
341 ; Trans = '$partial_setup_constants'
342 -> properties_were_filtered(Nr), Nr>0 % we probably have the partial transition due to prob-ignore pragmas
343 % TODO: detect whether any of the other non-ignored conjuncts were false/unknown
344 ; true),!.
345 tcltk_current_node_has_partial_transition :-
346 current_state_id(CurID),
347 transition(CurID,'$partial_setup_constants',_),!.
348
349 /* --------------------------------------------------------------------- */
350 tcltk_goto_state(ActionAsTerm,StateID) :-
351 (var(StateID) -> print_message(var_state(tcltk_goto_state(ActionAsTerm,StateID))) ; true),
352 (visited_expression_id(StateID)
353 -> true
354 ; ajoin(['State ',StateID,' does not exist. Could be due to insufficient memory. Transition: '],Msg),
355 add_warning(tcltk_goto_state,Msg,ActionAsTerm),
356 fail
357 ),
358 (current_state_id(CurID) -> true ; print('*** no_current_state_id ***'),nl),
359 ((transition(CurID,ActionAsTerm,OpID,StateID)
360 ; ActionAsTerm=jump, % jump is used by ProB2 and eclipse interface; TODO: use $jump or something similar to avoid confusion with real operation names
361 transition(CurID,_,OpID,StateID)
362 )
363 -> /* ok: proper transition */
364 set_current_state_id(StateID),
365 add_to_op_trace_ids(OpID),
366 add_id_to_history(CurID)
367 ; (CurID=StateID
368 -> true
369 ; ActionAsTerm=jump, find_id_in_history(StateID,Pos)
370 -> tcltk_backtrack(Pos)
371 ; ActionAsTerm=jump, find_id_in_forward_history(StateID,Pos)
372 -> tcltk_forward(Pos)
373 ; set_current_state_id(StateID),
374 add_to_op_trace_ids(jump(StateID)),
375 add_id_to_history(CurID)
376 )
377 ).
378
379 find_id_in_history(StateId,Position) :- history(H), nth1(Position,H,StateId).
380 find_id_in_forward_history(StateId,Position) :- forward_history(H), nth1(Position,H,forward(StateId,_)).
381
382 add_id_to_history(CurID) :-
383 (retract(history(History))-> true
384 ; add_warning(add_id_to_history,'No history for: ',CurID),History=[]),
385 (History=[],CurID\=root
386 -> add_message(add_id_to_history,'Adding missing root to history: ',CurID),
387 assertz(history([CurID,root])) % fix error in synchronisation between ProB2UI and prolog; should be fixed now
388 ; assertz(history([CurID|History]))
389 ),
390 retractall(forward_history(_)).
391
392
393
394 tcltk_add_new_transition(FromID,Action,ToID,ToTempl,TransInfo) :-
395 tcltk_add_new_transition_transid(FromID,Action,ToID,ToTempl,TransInfo,_TransId).
396
397 tcltk_add_new_transition_transid(FromID,Action,ToID,ToTempl,TransInfo,TransId) :-
398 add_new_transition_transid_with_infos(FromID,[],Action,ToID,ToTempl,TransInfo,TransId).
399
400 % variation with precomputed infos for the initial id (FromID)
401 add_new_transition_transid_with_infos(FromID,PrecomputedInfos,Action,ToID,ToTempl,TransInfo,TransId) :-
402 get_operation_internal_name(Action,OpName), % will use $initialise_machine; important for test 961 and PROOF_INFO
403 get_id_of_node_and_add_if_required_with_skip_check(ToTempl,ToID,Exists,FromID,OpName,PrecomputedInfos),
404 %% print_message(tcltk_add_new_transition(FromID,Action,ToID,Exists)), %%
405 ( Exists=exists,
406 (preferences:preference(store_only_one_incoming_transition,true),
407 \+ operation_not_yet_covered(OpName) % otherwise store at least one transition to achieve coverage
408 %-> transition(FromID,_,_,_) % add transition to prevent deadlock being detected
409 ; transition(FromID,Action,TransId,ToID), % identical transition already exists
410 (preference(eventtrace,true) % STORE_DETAILED_TRANSITION_INFOS; TODO: should we use a separate preference?
411 -> check_relevant_transition_info_stored(TransInfo,TransId) % check if we also have the same transition infos
412 ; true
413 )
414 )
415 -> true % // the transition already exists
416 ; % we have a new transition:
417 (preferences:preference(forget_state_space,true)
418 -> (any_transition(FromID,_,_) -> true
419 ; store_transition(FromID,'$NO_DEADLOCK',FromID,TransId)) /* just add dummy transition */
420 ; store_transition(FromID,Action,ToID,TransId),
421 (store_transition_infos(TransInfo,TransId) -> true
422 ; add_internal_error('storing transition info failed', store_transition_infos(TransInfo,TransId))
423 )
424 ),
425 mark_operation_as_covered(OpName),
426 (FromID \= ToID, b_or_z_mode, not_all_transitions_added(ToID)
427 -> add_additional_destination_infos(FromID,OpName,ToID) % e.g., PROOF_INF
428 ; true
429 )
430 ).
431
432 % a version that checks for query/skip operations and then simply returns old id
433 get_id_of_node_and_add_if_required_with_skip_check(_ToTempl,ToID,Exists,FromID,OpName,_PrecomputedInfos) :-
434 animation_mode(b), % csp_and_b mode is *not* ok ; see test 1701 for example
435 b_operation_cannot_modify_state(OpName),
436 !,
437 Exists=exists,ToID=FromID.
438 get_id_of_node_and_add_if_required_with_skip_check(ToTempl,ToID,Exists,FromID,OpName,PrecomputedInfos) :-
439 get_id_of_node_and_add_if_required(ToTempl,ToID,Exists,FromID,OpName,PrecomputedInfos).
440
441
442 :- use_module(probsrc(bit_sets),[bitset_intersection/3]).
443 % will only be called for ToID different from FromID
444 add_additional_destination_infos(FromID,ActionName,ToID) :- %print(add_dest(FromID,ActionName,ToID)),nl,
445 ( b_operation_preserves_invariant(ActionName,Full),
446 \+ invariant_still_to_be_checked(FromID),
447 \+ time_out_for_invariant(FromID), % invariant status of FromID unknown
448 \+ invariant_violated(FromID) % if Invariant does not hold in previous state,
449 % we have no idea about invariants in the new state (proof assumes invariant holds before)
450 ->
451 (retract(specialized_inv(ToID,OldMask)) -> true ; OldMask = empty),
452 (Full=full_invariant
453 -> assertz(specialized_inv(ToID,invariant_preserved))
454 % unfortunately we cannot yet retract invariant_not_yet_checked
455 ; OldMask=invariant_preserved
456 -> assertz(specialized_inv(ToID,invariant_preserved))
457 ; b_specialized_invariant_mask_for_op(ActionName,Mask) ->
458 (OldMask == empty -> NewMask = Mask ; bitset_intersection(Mask,OldMask,NewMask)),
459 assertz(specialized_inv(ToID,NewMask))
460 ; add_internal_error('Illegal operation: ',add_additional_destination_infos(FromID,ActionName,ToID) ),
461 assertz(specialized_inv(ToID,OldMask))
462 )
463 ; true
464 ).
465 /*
466 Store names of incoming transitions in an AVL tree
467 Used to calculate invariant in presence of proof information
468 */
469 % we could store this information to allow us to quickly generate traces from root to any state
470 %add_additional_destination_infos(FromID,ActionName,ToID) :-
471 % (reached_via(ToID,_,_) -> true ; %TODO: probably we should also store transition id
472 % assertz(reached_via(ToID,ActionName,FromID))).
473 % TO DO: we could store pge disabling information here disabled_operations
474
475
476
477
478 :- use_module(state_space_exploration_modes,[set_depth_breadth_first_mode/1,dbf_modes/3]).
479
480
481 tcltk_set_dbf_mode(Nr) :- dbf_modes(Nr,Mode,_),!,
482 set_depth_breadth_first_mode(Mode).
483 tcltk_set_dbf_mode(Nr) :- add_error(tcltk_set_dbf_mode,'Unknown mode: ',Nr).
484
485 tcltk_dbf_modes(list(Names)) :- findall(N,dbf_modes(_,_,N),Names).
486
487
488 :- dynamic prev_randomise_enumeration_order/1.
489
490
491 tcltk_mark_current_node_to_be_recomputed_wo_timeout :-
492 current_state_id(CurID),
493 format('Recomputing state id=~w without TIME_OUT~n',[CurID]),
494 tcltk_mark_node_for_recomputed(CurID),
495 (use_no_timeout(CurID) -> true ; assertz(use_no_timeout(CurID))).
496
497 % used for recomputing a state with random enumeration
498 tcltk_mark_current_node_to_be_recomputed_with_random_enum :-
499 current_state_id(CurID),
500 format('Recomputing state id=~w with random enumeration~n',[CurID]),
501 tcltk_mark_node_for_recomputed(CurID),
502 % retractall(transition(CurID,_,_,_)), % we no longer delete the transitions; this can cause problems with the history
503 % (if CurID appears earlier in the history and we remove the transition) and lead to error messages
504 % also: for the user it may be good to add new transitions incrementally
505 temporary_set_preference(randomise_enumeration_order,true,PREV),
506 assertz(prev_randomise_enumeration_order(PREV)).
507
508 tcltk_finish_current_node_to_be_recomputed_with_random_enum :-
509 retract(prev_randomise_enumeration_order(PREV)),
510 reset_temporary_preference(randomise_enumeration_order,PREV).
511
512 tcltk_mark_node_for_recomputed(ID) :-
513 (not_all_transitions_added(ID) -> true
514 ; add_id_at_front(ID)),
515 retractall(max_reached_for_node(ID)),
516 retractall(time_out_for_node(ID,_,_)),
517 % TODO: clear b_operation_cache:operation_cached_time_out for relevant nodes
518 (transition(ID,'$partial_setup_constants',ID2)
519 -> delete_node(ID2) ; true),
520 retractall(state_space:transition(ID,'$partial_setup_constants',_,_)).
521
522 transitions_computed_for_node(ID) :-
523 \+(not_all_transitions_added(ID)),
524 \+ is_not_interesting(ID).
525
526
527
528
529 tcltk_set_initial_machine :-
530 tcltk_clear_machine,
531 b_set_initial_machine,
532 set_animation_mode(b).
533
534 % new profiler
535 %:- use_module('../extensions/profiler/profiler.pl').
536 % old profiler
537 %:- use_module(runtime_profiler,[reset_runtime_profiler/0]).
538
539 % the following clears the entire state space and uses the current state as now starting initial state
540 tcltk_clear_state_space_and_refocus_to_current_state :-
541 Op = 'REFOCUS-ANIMATOR',
542 current_expression(_CurID,CurState),
543 (CurState = const_and_vars(ConstID,VarState) ->
544 visited_expression(ConstID,ConstState),
545 transition(root,SetupConstantAction,_,ConstID)
546 ; ConstState=[]),
547 announce_event(reset_specification),
548 (ConstState=[]
549 -> add_trans_id(root,Op,CurState,NewID,_TransId)
550 ; add_trans_id(root,SetupConstantAction,ConstState,NewConstID,_),
551 add_trans_id(NewConstID,Op,const_and_vars(NewConstID,VarState),NewID,_),
552 (retract_open_node(NewConstID) -> true ; true),
553 tcltk_goto_state(SetupConstantAction,NewConstID) % use action of transition; otherwise a jump is recorded
554 ),
555 tcltk_goto_state(Op,NewID),
556 (retract_open_node(root) -> true ; true).
557
558 :- use_module(eventhandling, [announce_event/1]).
559 tcltk_clear_machine :-
560 announce_event(reset_specification),
561 announce_event(clear_specification),
562 reset_tcltk_interface,
563 set_animation_mode(b),
564 bmachine:b_set_empty_machine,
565 reset_errors,
566 % reset_dynamics, % new profiler
567 % Now done via event handling: b_interpreter:reset_b_interpreter,reset_model_checker,
568 garbage_collect_atoms. % reclaim atoms if possible
569
570 :- use_module(prob2_interface, [start_animation/0, update_preferences_from_spec/0]).
571 tcltk_initialise :-
572 update_preferences_from_spec,
573 start_animation,
574 tcltk_try_reload.
575
576 tcltk_reset :- reset_errors,
577 reset_animation_history.
578
579 % reset the animation history to the root, keeping it as forward history; does not reset errors
580 reset_animation_history :-
581 history(H), op_trace_ids(T),
582 current_state_id(CurID),
583 (forward_history(FH) -> true ; FH=[]),
584 state_space_reset,
585 gen_forward_history(T,[CurID|H],FH,FwdHist),
586 retractall(forward_history(_)),
587 assertz(forward_history(FwdHist)).
588
589 gen_forward_history([],H,R,R) :- (H=[root] -> true ; print(unexpected_remaining_hist(H)),nl).
590 gen_forward_history([A|TT],[ID|TH],Acc,Res) :-
591 gen_forward_history(TT,TH,[forward(ID,A)|Acc],Res).
592
593
594
595 /* ---- getting available options ----- */
596
597 tcltk_get_options_dest_info(L) :-
598 tcltk_get_options_dest_info(L,[]). %[no_query_operations]).
599 tcltk_get_options_dest_info(list(DestinationInfos),Options) :-
600 debug_println(9,start_tcltk_get_options_dest_info),
601 % get a list of all options which are skip events
602 current_state_id(CurID),
603 compute_all_transitions_if_necessary(CurID),
604 tcltk_get_candidates_dest_info(List1),
605 findall(Res, (transition(CurID,ActionAsTerm,ID), % check no_query_operations
606 (member(no_query_operations,Options) -> \+ query_op_transition(ActionAsTerm) ; true),
607 option_dest_info(ID,ActionAsTerm,CurID,Res)),
608 DestinationInfos,List1).
609
610 option_dest_info(DestID,ActionAsTerm,CurID,Res) :- DestID=CurID,!,
611 (query_op_transition(ActionAsTerm) -> Res=query ; Res=skip).
612 option_dest_info(DestID,_,_,Res) :- not_all_transitions_added(DestID),!, Res=open.
613 option_dest_info(DestID,_,_,Res) :- invariant_violated(DestID),!,Res=invariant_violated.
614 option_dest_info(DestID,_,_,Res) :- is_deadlocked(DestID),!,Res=deadlock.
615 option_dest_info(DestID,_,_,Res) :- node_satisfies_goal(DestID),!,Res=goal.
616 option_dest_info(_DestID,_,_,unknown).
617
618 query_op_transition(Term) :- b_or_z_mode,
619 get_operation_name(Term,OpName),
620 b_operation_cannot_modify_state(OpName).
621
622 tcltk_get_options(Options) :- tcltk_get_options(Options,no_desc).
623
624 % get list of enabled operations/events:
625 tcltk_get_options(list(Options),GetDesc) :-
626 current_state_id(CurID), debug_println(9,start_tcltk_get_options(CurID)),
627 catch(tcltk_compute_options(CurID,TransSpecs),
628 user_interrupt_signal, (
629 assert_time_out_for_node(CurID,'unspecified_operation_interrupted_by_user',user_interrupt_signal),
630 tcltk_get_computed_options(CurID,TransSpecs)
631 )),
632 extract_actions(TransSpecs,CurID,ActionsAndIDs,Actions,GetDesc),
633 set_current_options(ActionsAndIDs),
634 debug_println(9,finished_tcltk_get_options(CurID)),
635 Actions = Options.
636
637 :- dynamic current_candidate_options/1.
638
639 % a newer version of tcltk_options which returns list of potentially enabled events
640 % in case MAX_OPERATIONS is set to 0; these virtual events are appended at the end of the
641 % current transitions (which at the start are empty; but can be populated by executed by predicate)
642 % if GetDesc = get_desc then it will try to get operation descriptions (e.g., via desc pragma)
643 tcltk_get_options_or_candidates(list(List),GetDesc) :-
644 retractall(current_candidate_options(_)),
645 tcltk_get_options(list(List1),GetDesc),
646 current_state_id(CurID),
647 (state_can_have_additional_candidates(CurID,List1,Candidates)
648 -> assert(current_candidate_options(Candidates)),
649 maplist(get_cand_name,Candidates,List2),
650 append(List1,List2,List)
651 ; List=List1).
652 get_cand_name(candidate(OpName,TO),OpNameRes) :-
653 (TO==true -> ajoin([OpName,' (*timeout*)'],OpNameRes) ; OpNameRes=OpName).
654
655 :- use_module(specfile,[max_operations_zero_for_setup_constants/0,max_operations_zero_for_initialisation/0]).
656 % check if a state can have additional, unexplored transition candidates
657 % either because of MAX_OPERATIONS or MAX_INITIALISATIONS or because of symbolic XTL transitions
658 state_can_have_additional_candidates(CurID,List1,Res) :- List1=[],
659 candidate_setup_constants_or_init(CurID,OpName),!,
660 Res = [candidate(OpName,false)].
661 state_can_have_additional_candidates(_,_,Res) :- \+ \+ max_op_zero_or_xtl_mode(_),
662 tcltk_get_candidate_operations(Res).
663
664 % check if SETUP_CONSTANTS or INITIALISATION were not computed due to MAX_INITIALISATION
665 candidate_setup_constants_or_init(root,Candidate) :- !, b_or_z_mode,
666 (b_machine_has_constants_or_properties
667 -> max_operations_zero_for_setup_constants,
668 Candidate = '$setup_constants'
669 ; max_operations_zero_for_initialisation,
670 Candidate = '$initialise_machine'
671 ).
672 candidate_setup_constants_or_init(CurID,'$initialise_machine') :- b_or_z_mode,
673 is_concrete_constants_state_id(CurID),
674 max_operations_zero_for_initialisation.
675
676 % in case of MAX_OPERATIONS=0 just show the potentially enabled (regular) operations
677 tcltk_get_candidate_operations(Candidates) :-
678 current_state_id(CurID),
679 findall(candidate(OpName,TimeOutOcc),
680 (max_op_zero_or_xtl_mode(OpName),
681 potentially_enabled_operation(CurID,OpName,TimeOutOcc,_Precise)
682 ),Candidates).
683
684 :- use_module(specfile,[max_operations_zero_for_operation/1]).
685 max_op_zero_or_xtl_mode(OpName) :-
686 xtl_mode,!,
687 xtl_transition_parameters(OpName,_Paras).
688 max_op_zero_or_xtl_mode(OpName) :- max_operations_zero_for_operation(OpName).
689
690 :- use_module(xtl_interface,[xtl_symbolic_transition_potentially_enabled/2]).
691 :- use_module(tools_timeout,[time_out_with_factor_call/4]).
692 % get operations with MAX_OPERATIONS=0 which are potentially enabled
693 potentially_enabled_operation(StateId,OpName,TimeOutOccurred,PreciseGuard) :- b_or_z_mode,!,
694 b_top_level_operation(OpName),
695 max_operations_zero_for_operation(OpName),
696 Simplify=true,
697 get_quantified_operation_enabling_condition(OpName, Guard, _, PreciseGuard, Simplify),
698 (time_out_with_factor_call(
699 eclipse_interface:test_boolean_expression_in_node(StateId,Guard,'operation Guard'),
700 0.1, [max_time_out(2000),
701 silent],
702 (format('TIME-OUT checking if ~w is enabled; assuming it could be.~n',[OpName]),TimeOutOccurred=true)
703 )
704 -> (var(TimeOutOccurred) -> TimeOutOccurred=false ; true)).
705 potentially_enabled_operation(StateId,OpName,false,imprecise) :- xtl_mode,!,
706 visited_expression(StateId,State),
707 xtl_symbolic_transition_potentially_enabled(OpName,State).
708
709 % get the name of a currently stored candidate option/operation
710 % the option list was empty and we inserted a list of candidate operations
711 % (e.g., because MAX_OPERATIONS was 0)
712 tcltk_get_options_candidate_nr_name(Nr,OpName) :-
713 current_candidate_options(List),
714 current_options(List1), length(List1,Len),
715 N1 is Nr-Len, % the candidate of potentially enabled events are listed after the regular options
716 nth1(N1,List,candidate(OpName,_)).
717
718 % get destination info for candidate operations in the Operations View
719 tcltk_get_candidates_dest_info(L) :- current_state_id(CurID),
720 current_candidate_options(Cands),!,
721 maplist(get_cand_dest(CurID),Cands,L).
722 tcltk_get_candidates_dest_info([]).
723 get_cand_dest(_,candidate(_,true),R) :- !, R=time_out.
724 get_cand_dest(CurID,candidate(OpName,_),Res) :-
725 transition(CurID,ActionTerm,_ActId,_DestID),
726 get_operation_name(ActionTerm,OpName),!,
727 % it is a candidate for which we already have a transition
728 Res = reached_candidate.
729 get_cand_dest(_,_,candidate).
730
731 :- use_module(tools_timeout,[time_out_call/2]).
732 :- use_module(translate,[translate_event_with_src_and_target_id/4]).
733 % GetDesc is either no_desc or get_desc
734 extract_actions([],_,[],[],_).
735 extract_actions([(ActionId,Term,Dst)|T],CurID,[(ActionId,Str,Term,Dst)|Srest],[Str|ET],GetDesc) :-
736 extract_action(CurID,Term,Dst,Str,GetDesc),
737 extract_actions(T,CurID,Srest,ET,GetDesc).
738
739 extract_action(CurID,ActionAsTerm,DestID,Str,get_desc) :-
740 tcltk_get_operation_description_for_trans(CurID,ActionAsTerm,DestID,Desc),!, Str=Desc.
741 extract_action(CurID,ActionAsTerm,DestID,Str,_) :-
742 time_out_call(translate_event_with_src_and_target_id(ActionAsTerm,CurID,DestID,Str), Str='**TIMEOUT**').
743
744 % compute transitions and invariant info
745 compute_state_information_if_necessary :-
746 current_state_id(CurID),
747 compute_state_information_if_necessary(CurID).
748 compute_state_information_if_necessary(CurID) :-
749 compute_all_transitions_if_necessary(CurID,true). % CheckInvariant=true
750
751 tcltk_compute_options(CurID,ActionsAndIDs) :-
752 compute_state_information_if_necessary(CurID),
753 %print(found_transitions(CurID)),nl,
754 tcltk_get_computed_options(CurID,ActionsAndIDs).
755
756 tcltk_get_computed_options(CurID,ActionsAndIDs) :-
757 findall((ActId,ActionAsTerm,DestID),
758 transition(CurID,ActionAsTerm,ActId,DestID),
759 % TO DO: sort or group, especially if we randomize transition/3
760 ActionsAndIDs).
761
762 tcltk_get_status(INVVIOLATED,MAXREACHED,TIMEOUT) :- debug_println(9,start_tcltk_get_status),
763 current_state_id(CurID),
764 (time_out_for_invariant(CurID) -> INVVIOLATED = 2
765 ; get_invariant_violated(CurID) -> INVVIOLATED = 1
766 ; not_invariant_checked(CurID) -> INVVIOLATED = 3
767 ; not_interesting(CurID) -> INVVIOLATED = 3
768 ; INVVIOLATED = 0
769 ),
770 (max_reached_for_node(CurID) -> MAXREACHED = 1
771 ; not_interesting(CurID) -> MAXREACHED = 2
772 ; MAXREACHED = 0),
773 (time_out_for_node(CurID,_,time_out) -> TIMEOUT = 1
774 ; time_out_for_node(CurID,_,user_interrupt_signal) -> TIMEOUT = 3 % CTRL-C
775 ; time_out_for_node(CurID,_,virtual_time_out(kodkod_timeout)) -> TIMEOUT = 1 % KODKOD; regular time-out
776 ; time_out_for_node(CurID,_,_) -> TIMEOUT = 2 % virtual_time_out
777 ; TIMEOUT = 0),
778 debug_println(9,got_status(INVVIOLATED,MAXREACHED,TIMEOUT)).
779
780 tcltk_get_ops_with_virtual_timeout(OpNameList) :-
781 current_state_id(StateId),
782 ops_with_timeout(StateId,OpNameList,virtual_time_out(_)).
783 tcltk_get_ops_with_real_timeout(OpNameList) :-
784 current_state_id(StateId),
785 ops_with_timeout(StateId,OpNameList,time_out).
786 % Note: possibilities are currently: time_out, user_interrupt_signal, virtual_time_out(_)
787 tcltk_get_ops_user_interrupt_occurred :-
788 current_state_id(StateId),
789 time_out_for_node(StateId,_,user_interrupt_signal).
790 ops_with_timeout(StateId,OpNameList,Type) :-
791 findall(OpName, time_out_for_node(StateId,OpName,Type), OpNameList).
792
793
794 %%fd_copy_term(X,Y,true) :- copy_term(X,Y).
795
796
797
798 /* --------------------------------------------------------------------- */
799
800 tcltk_get_history(list(StringHistory)) :- debug_println(9,start_tcltk_get_trace),
801 get_action_trace(History),
802 convert_trace_to_list_of_strings(History,StringHistory).
803
804 convert_trace_to_list_of_strings([],[]).
805 convert_trace_to_list_of_strings([action(AS,_)|T],[AS|CT]) :- !,
806 %truncate_atom(AS,1000,TruncatedAS), % especially SETUP_CONSTANTS, INITIALISATION can be very large; leading to performance issues
807 % get_action_trace now truncates
808 convert_trace_to_list_of_strings(T,CT).
809 convert_trace_to_list_of_strings([H|T],[H|CT]) :- convert_trace_to_list_of_strings(T,CT).
810
811 tcltk_write_uml_sequence_chart(File) :-
812 write_uml_sequence_chart(File).
813
814 /* --------------------------------------------------------------------- */
815
816 :- dynamic cached_state_as_strings/2.
817 :- use_module(probsrc(state_space),[try_compute_depth_of_state_id/2]).
818 %tcltk_get_state(list(List)) :- !,List=[]. % comment in to disable State Properties View in ProB Tcl/Tk
819 tcltk_get_state(list(List)) :- debug_println(9,start_tcltk_get_state),
820 current_expression(CurID,CurState),
821 compute_state_information_if_necessary(CurID),
822 (time_out_for_invariant(CurID) -> List = [invariant_time_out|List1]
823 ; invariant_violated(CurID) -> List = [invariant_violated|List1]
824 ; invariant_not_yet_checked(CurID) -> List = [invariant_not_checked|List1]
825 ; CurID=root -> List = List1
826 ; CurState = concrete_constants(_) -> List = List1
827 ; specfile:b_or_z_mode -> List=[invariant_ok|List1]
828 % only in b_or_z_mode do we add not_invariant_checked facts and check invariant while model checking/animating
829 ; List=List1),
830 (try_compute_depth_of_state_id(CurID,Depth),
831 translate:translate_properties_with_limit(['='(depth,Depth)],[DS])
832 -> List1 = [DS|StateAsStrings]
833 ; List1 = StateAsStrings),
834 (cached_state_as_strings(CurID,StateAsStrings) % TO DO: separate constant / variable properties ?
835 -> true
836 ; retractall(cached_state_as_strings(_,_)),
837 time_out_call(tcltk_get_state(StateAsStrings,CurState),
838 StateAsStrings = ['***TIMEOUT-PROPERTY***']),
839 assertz(cached_state_as_strings(CurID,StateAsStrings))
840 ),
841 debug_println(9,finished_tcltk_get_state).
842
843 tcltk_get_state(StateAsStrings,State) :-
844 %print(get_state),nl,
845 findall(Prop,property(State,Prop),StateProps),
846 %print(translating(StateProps)),nl,
847 translate:translate_properties_with_limit(StateProps,StateAsStrings).
848 %print(translated(StateAsStrings)),nl.
849
850
851 tcltk_get_state_errors(list(ErrorsAsStrings)) :-
852 get_current_state_errors(_CurID,Errors),
853 translate_state_errors(Errors,ErrorsAsStrings).
854
855 get_current_state_errors(CurID,Errors) :-
856 current_state_id(CurID),
857 findall(Error,( state_error(CurID,_,Error), Error \== invariant_violated ), Errors).
858
859 :- dynamic last_detailed_error/3.
860
861 reset_tcltk_interface :- debug_println(19,reset_tcltk),
862 retractall(cbc_inv_error_found(_,_)), reset_nr_cbc_sols,
863 retractall(find_flag(_,_)),
864 retractall(resetable_node(_)),
865 retractall(non_det_constant(_)),
866 retractall(current_candidate_options(_)),
867 retractall(cached_state_as_strings(_,_)),
868 retractall(last_detailed_error(_,_,_)).
869
870 tcltk_get_detailed_state_error(Num,ErrorMsg,Srow,Scol,Erow,Ecol) :-
871 retractall(last_detailed_error(_,_,_)),
872 get_current_state_errors(CurID,Errors),
873 nth0(Num,Errors,Error),
874 !,
875 explain_state_error(Error,Span,ErrorMsg),
876 assertz(last_detailed_error(CurID,Span,ErrorMsg)), % save info, so that we can debug if Span contains a span_predicate
877 %(generate_dot_from_last_span_predicate('~/Desktop/err.dot') -> true ; true),
878 (extract_line_col_for_main_file(Span,Srow,Scol,Erow,Ecol)
879 -> true
880 ; Srow= -1, Scol= -1, Erow= -2, Ecol= -2).
881
882
883 :- use_module(probsrc(tools_commands),[edit_file/2]).
884 :- use_module(specfile,[b_absolute_file_name_relative_to_opened_file/2]).
885 % show location of state error in external editor
886 tcltk_open_state_error_in_editor(Num) :-
887 get_current_state_errors(_,Errors),
888 nth0(Num,Errors,Error),
889 (get_state_error_span(Error,Span)
890 -> (extract_file_line_col(Span,FILE,LINE,_COL,_Erow,_Ecol)
891 -> b_absolute_file_name_relative_to_opened_file(FILE,AFILE),
892 edit_file(AFILE,LINE)
893 ; add_error(tcltk_open_state_error_in_editor,'Could not extract file position: ',Span)
894 )
895 ; add_error(tcltk_open_state_error_in_editor,'Could not extract source location for state error: ',Num)
896 ).
897
898 can_generate_dot_from_last_state_error :-
899 last_detailed_error(_CurID,ErrSpan,_),!,
900 get_inner_span(ErrSpan,span_predicate(_,_,_)).
901 can_generate_dot_from_last_state_error :-
902 current_state_id(CurID), state_error(CurID,_,_). % not sure if it is really possible to extract span predicate though
903 generate_dot_from_last_span_predicate(FileName) :-
904 current_state_id(CurID),
905 (last_detailed_error(CurID,ErrSpan,_ErrorMsg) % also works with expressions
906 -> true
907 ; tcltk_get_detailed_state_error(0,_,_,_,_,_), % try and generate error description
908 last_detailed_error(CurID,ErrSpan,_)
909 ),
910 get_inner_span(ErrSpan,span_predicate(P,LS,State)),
911 (State=[], visited_expression(CurID,S),
912 state_corresponds_to_initialised_b_machine(S,FullState)
913 -> true % span predicates from event trace do not have the current state, add state
914 ; FullState=State),
915 write_dot_file_for_pred_expr_and_state(P, LS, FullState,FileName).
916
917 get_inner_span(pos_context(Span1,_,_),SP) :- !,
918 get_inner_span(Span1,SP).
919 get_inner_span(SP,SP).
920
921 tcltk_current_state_invariant_violated :-
922 current_state_id(CurID),
923 get_invariant_violated(CurID).
924
925 tcltk_state_exists_with_invariant_violated :-
926 (invariant_violated(_) -> true). % would be too expensive for XTL mode
927
928 % also checks for other formalisms whether something similar to an invariant violation holds
929 get_invariant_violated(CurID) :- xtl_mode,!,
930 visited_expression(CurID,CurState),
931 xtl_invariant_violated(CurState).
932 get_invariant_violated(CurID) :- invariant_violated(CurID).
933
934 /* --------------------------------------------------------------------- */
935
936 :- use_module(b_trace_checking, [tcltk_save_history_as_trace_file/2]).
937 tcltk_save_history_as_trace_file(File) :-
938 tcltk_save_history_as_trace_file(prolog,File).
939
940
941 /* --------------------------------------------------------------------- */
942
943 :- use_module(translate, [get_bexpression_column_template/4]).
944 evaluate_bexpr_over_state(Stream,Expr,ValueTemplate,Columns,ResultColStrings,BState,OpName) :-
945 format(Stream,'~w,',[OpName]),
946 b_compute_expression_with_prob_ids(Expr,BState,Value),
947 copy_term((ValueTemplate,Columns),(Value,ResultCols)),
948 my_print_csv_value(ResultCols,Stream),
949 maplist(translate:translate_bvalue,ResultCols,ResultColStrings),
950 nl(Stream).
951
952 % evaluate an expression over the history and save the result to a CSV file
953 evaluate_expression_over_history_to_csv_file(Expr,File) :-
954 parse_machine_expression(Expr,TypedExpr),
955 get_bexpression_column_template(TypedExpr,ValueTemplate,ColHeaders,Columns),
956 format('Writing CSV file: ~w~n',[File]),
957 open(File,write,Stream),
958 format(Stream,'OPERATION,',[]),
959 my_print_csv_atoms(ColHeaders,Stream),
960 call_cleanup(map_over_history(evaluate_bexpr_over_state(Stream,TypedExpr,ValueTemplate,Columns),_),
961 close(Stream)),
962 format('Finished writing CSV file: ~w~n',[File]).
963
964
965 tcltk_evaluate_expression_over_history(Expr,list([list(['OPERATION','State Id'|ColHeaders])|ColumnLists])) :-
966 parse_machine_expression(Expr,TypedExpr),
967 get_bexpression_column_template(TypedExpr,ValueTemplate,ColHeaders,Columns),
968 map_over_history(evaluate_bexpr_over_state(user_output,TypedExpr,ValueTemplate,Columns),
969 ColumnLists).
970
971 map_over_history(Pred,ResColumnLists) :-
972 history(H), current_state_id(CurID),
973 reverse([CurID|H],RH),
974 get_action_trace(T), reverse(T,RT),
975 maplist(call_pred_on_expanded_state(Pred),RH,[action(root,root)|RT],ColumnLists),
976 prune_list(ColumnLists,ResColumnLists).
977 % remove unknown elements at front for Tk
978 prune_list([unknown|T],Res) :- !, prune_list(T,Res).
979 prune_list(R,R).
980
981 call_pred_on_expanded_state(_Pred,root,_,ColList) :- !, ColList=unknown.
982 call_pred_on_expanded_state(Pred,StateId,action(_,ActionTerm),ResColList) :-
983 get_operation_name(ActionTerm,OpName),
984 debug_format(9,'Processing state ~w (reached via ~w)~n',[StateId,OpName]),
985 visited_expression(StateId,State),
986 (state_corresponds_to_initialised_b_machine(State,BState)
987 -> call(Pred,ColList,BState,OpName), ResColList = list([OpName,StateId|ColList])
988 ; ResColList = unknown ).
989
990 :- use_module(eval_let_store,[extend_state_with_probids_and_lets/2]).
991 b_compute_expression_with_prob_ids(Expr,BState,Value) :-
992 extend_state_with_probids_and_lets(BState,BState2),
993 b_interpreter:b_compute_expression_nowf(Expr,[],BState2,Value,'Tcl/Tk',0).
994
995
996 my_print_csv_atoms([A,B|T],Stream) :- !, format(Stream,'"~w",',[A]),
997 my_print_csv_atoms([B|T],Stream).
998 my_print_csv_atoms([A],Stream) :- format(Stream,'"~w"~n',[A]).
999
1000 my_print_csv_value([A,B|T],Stream) :- !,
1001 my_print_csv_value([A],Stream),
1002 write(Stream,','),
1003 my_print_csv_value([B|T],Stream).
1004 my_print_csv_value([V],Stream) :-
1005 (no_quotes_necessary(V) -> true ; write(Stream,'"')),
1006 translate:print_bvalue_stream(Stream,V),
1007 (no_quotes_necessary(V) -> true ; write(Stream,'"')).
1008
1009 no_quotes_necessary(int(_)).
1010 no_quotes_necessary(pred_false).
1011 no_quotes_necessary(pred_true).
1012
1013
1014 /* --------------------------------------------------------------------- */
1015
1016 :- use_module(probltlsrc(ltl),[preprocess_formula/2]).
1017
1018 % it is actually more tcltk_animate_until
1019 tcltk_animate_until(FormulaAsAtom,StepsExecuted,Result) :-
1020 CheckingType = ltl_state_property, % no_loop means we check entire animation trace from CurID for LTL property
1021 tcltk_animate_until(FormulaAsAtom,CheckingType,StepsExecuted,Result).
1022 tcltk_animate_until(FormulaAsAtom,CheckingType,StepsExecuted,Result) :-
1023 current_state_id(CurID),
1024 MaxNrOfSteps = 1000,
1025 tcltk_animate_until(FormulaAsAtom,CurID,MaxNrOfSteps,CheckingType,StepsExecuted,Result,_,_).
1026 tcltk_animate_until(FormulaAsAtom,CurID,MaxNrOfSteps,CheckingType,StepsExecuted,Result,NewStateId,OpIds) :-
1027 parse_and_preprocess_formula(FormulaAsAtom,ltl,Ltl2),
1028 % TODO: warn if CheckingType=ltl_state_property and we do not have an atomic state property
1029 prob2_interface:find_trace_until_ltl(CurID,random,Ltl2,CheckingType,MaxNrOfSteps,Trace,Result),
1030 % Result: ltl_found, maximum_nr_of_steps_reached, deadlock
1031 length(Trace,StepsExecuted),
1032 (last(Trace,op(_,_,_,NewStateId)) -> true ; NewStateId=CurID),
1033 debug_format(19,'Found trace of length ~w to ~w~n',[StepsExecuted,Result]),
1034 maplist(get_trans_id,Trace,OpIds),
1035 execute_id_trace_from_current(OpIds).
1036
1037 get_trans_id(op(OpID,_Name,_CurID,_NextID),OpID).
1038
1039
1040
1041 tcltk_random_perform :- tcltk_random_perform2(_,fully_random).
1042 tcltk_random_perform(Kind) :- tcltk_random_perform2(_,Kind).
1043
1044 % Kind can be fully_random, no_self_loops, explore_open
1045 % TODO: other options like out_degree, ...
1046 tcltk_random_perform2(ActionId,Kind) :-
1047 current_options(Opts),
1048 current_state_id(CurID),
1049 (Kind=explore_open, exclude(is_already_explored,Opts,Options2), Options2 = [_|_]
1050 -> true % try and find unexplored successor
1051 ; is_heuristic(Kind),
1052 maplist(compute_heuristic(Kind),Opts,HOpts),
1053 sort(HOpts,SHOpts),
1054 keep_min_heuristic(SHOpts,Opts1)
1055 ->
1056 (exclude(is_already_explored,Opts1,Options2), Options2 = [_|_]
1057 -> true % among the nodes with the lowest heuristic value choose open nodes first; to try find new values
1058 ; Options2=Opts1)
1059 ; Kind=execute_first_enabled, Opts = [First|_] -> Options2 = [First]
1060 ; Kind\=fully_random,
1061 exclude(is_self_loop(CurID),Opts,Options2), Options2 = [_|_] -> true % try find different node
1062 ; Options2=Opts),
1063 length(Options2,Len),
1064 (Len>0
1065 -> L1 is Len+1,
1066 random(1,L1,RanChoice),
1067 tcltk_perform_nr_option(RanChoice,Options2,ActionId)
1068 ; true
1069 ).
1070
1071 is_already_explored((_Id,_Action,_,NextId)) :- \+ not_all_transitions_added(NextId).
1072 is_self_loop(CurId,(_Id,_Action,_,CurId)).
1073
1074 is_heuristic(heuristic).
1075 is_heuristic(min_out_degree).
1076 :- use_module(probsrc(state_space_exploration_modes),[compute_heuristic_function_for_state_id/2]).
1077 :- use_module(probsrc(state_space),[out_degree/2, compute_transitions_if_necessary/1]).
1078 compute_heuristic(Kind,(Id,Action,ActTerm,NextId),heurval(HeurVal,Id,Action,ActTerm,NextId)) :-
1079 compute_h2(Kind,NextId,HeurVal).
1080 compute_h2(heuristic,NextId,HeurVal) :-
1081 compute_heuristic_function_for_state_id(NextId,HeurVal).
1082 compute_h2(min_out_degree,NextId,HeurVal) :-
1083 compute_transitions_if_necessary(NextId),
1084 out_degree(NextId,HeurVal).
1085 %compute_h2(out_degree,NextId,HeurVal) :-
1086
1087 % only keep the maximal value
1088 keep_min_heuristic([heurval(HeurVal,Id,Action,ActTerm,NextId)|HT],
1089 [(Id,Action,ActTerm,NextId)|T]) :- keep_min2(HT,HeurVal,T).
1090 keep_min2([heurval(HeurVal,Id,Action,ActTerm,NextId)|HT],HeurVal,
1091 [(Id,Action,ActTerm,NextId)|T]) :- !, keep_min2(HT,HeurVal,T).
1092 keep_min2(_,_,[]).
1093
1094
1095 tcltk_get_line_col(Nr,list(StartLine),list(StartCol),list(EndLine),list(EndCol)) :-
1096 /* just get the location in the source code */
1097 current_options(Options),
1098 nth1(Nr,Options,(_Id,_Action,ActionAsTerm,_NewID)),
1099 %print(get_source_text(ActionAsTerm)),nl,
1100 time_out_call(get_source_text_positions(ActionAsTerm,StartLine,StartCol,EndLine,EndCol),
1101 add_error_and_fail(tcltk_get_line_col,'Timeout determining source code position: ',ActionAsTerm)),
1102 StartLine \= []. % otherwise fail
1103 % print(startlines(StartLine)),nl,print(startcols(StartCol)),nl,
1104 % print(endlines(EndLine)),nl, print(endcol(EndCol)),nl.
1105
1106 tcltk_is_sync_event(Nr) :-
1107 current_options(Options),
1108 nth1(Nr,Options,(_Id,_Action,ActionAsTerm,_NewID)),
1109 extract_span_from_event(ActionAsTerm,SPAN,_,_),
1110 extract_span_info(SPAN,Info),
1111 % print(extracted_span_info_for_sync(Info,SPAN)),nl,
1112 member(sharing,Info).
1113
1114 % get textual description of nth option in current options
1115 % is derived from description pragma attached to operations
1116 tcltk_get_options_nr_description(Nr,Desc) :-
1117 current_state_id(CurID),
1118 current_options(Options),
1119 nth1(Nr,Options,(_ActionId,_Action,ActionAsTerm,NewID)),
1120 tcltk_get_op_desc_or_other_info_for_trans(CurID,ActionAsTerm,NewID,Desc).
1121
1122 :- use_module(probsrc(bmachine),[source_code_for_identifier/6]).
1123 % get textual description for entry Nr in the Tk history view
1124 tcltk_get_history_nr_description(Nr,Desc) :-
1125 get_history_trans(Nr, CurID,ActionAsTerm,DestID),
1126 tcltk_get_op_desc_or_other_info_for_trans(CurID,ActionAsTerm,DestID,Desc).
1127
1128 get_history_trans(Nr, CurID,ActionAsTerm,DestID) :-
1129 op_trace_ids(OpTrace),
1130 nth0(Nr,OpTrace,TransId),
1131 history(StateIds),
1132 nth0(Nr,StateIds,CurID),
1133 transition(CurID,ActionAsTerm,TransId,DestID).
1134
1135 :- use_module(probsrc(bmachine),[source_code_for_identifier/6]).
1136 % show source code origin of entry number Nr in the Tk history view
1137 tcltk_get_history_nr_origin_str(Nr,Desc) :-
1138 get_history_trans(Nr, _CurID,ActionAsTerm,_DestID),
1139 get_operation_name(ActionAsTerm,OpID),
1140 source_code_for_identifier(OpID,operation,subst,OriginStr,_,_),
1141 Desc=OriginStr. %ajoin([OpID,' ', OriginStr],Desc).
1142
1143
1144 :- use_module(probsrc(tools_commands),[edit_file/2]).
1145 :- use_module(probsrc(error_manager),[extract_file_line_col/6]).
1146 % open source code in external editor for origin of entry number Nr in the history view
1147 tcltk_edit_history_nr_origin_str(Nr) :-
1148 get_history_trans(Nr, _CurID,ActionAsTerm,_DestID),
1149 get_operation_name(ActionAsTerm,OpID),
1150 source_code_for_identifier(OpID,operation,subst,_OriginStr,OriginTerm,_),
1151 extract_file_line_col(OriginTerm,FILE,LINE,_COL,_Erow,_Ecol),
1152 edit_file(FILE,LINE).
1153
1154 :- use_module(probsrc(state_space_exploration_modes),
1155 [compute_heuristic_function_for_state_id/2]).
1156 tcltk_get_operation_description_for_trans(CurID,ActionAsTerm,DestID,Desc) :-
1157 (b_or_z_mode ; xtl_mode),
1158 get_operation_description_for_transition(CurID,ActionAsTerm,DestID,Desc).
1159
1160 % this will also look for other info if available
1161 tcltk_get_op_desc_or_other_info_for_trans(CurID,ActionAsTerm,DestID,Desc) :-
1162 (tcltk_get_operation_description_for_trans(CurID,ActionAsTerm,DestID,Desc) -> true
1163 ; compute_heuristic_function_for_state_id(DestID,int(HeuristicVal)),
1164 ajoin(['Heuristic=',HeuristicVal],Desc)). % TODO: more infos, like deadlock, GOAL, ...
1165
1166 % counter-part to tcltk_get_options, to execute the option/operation number Nr in that list
1167 tcltk_perform_nr(Nr) :-
1168 current_options(Options),
1169 tcltk_perform_nr_option(Nr,Options,_).
1170
1171 tcltk_perform_nr_option(Nr,Options,ActionId) :-
1172 (nth1(Nr,Options,(ActionId,_Action,ActionAsTerm,NewID))
1173 -> (forward_history([forward(NewID,ActionId)|_FwdHist])
1174 -> tcltk_forward
1175 ; tcltk_perform_action_term(ActionAsTerm,NewID),
1176 retractall(forward_history(_))
1177 )
1178 ; tcltk_backtrack /* interpret as backtrack */
1179 ).
1180
1181
1182 tcltk_fast_backtrack :- tcltk_can_backtrack, !,
1183 tcltk_backtrack,
1184 current_state_id(CurID),
1185 compute_state_information_if_necessary(CurID),
1186 tcltk_fast_backtrack.
1187 tcltk_fast_backtrack.
1188
1189 tcltk_can_backtrack :- history([_|_]).
1190 tcltk_can_backtrack(Len) :- history(His), length(His,Len),Len>0.
1191 tcltk_can_backtrack_to_state_id(StateID) :- history([StateID|_]).
1192
1193 tcltk_backtrack :- \+ tcltk_can_backtrack,!,
1194 print_message('Cannot backtrack'),fail.
1195 tcltk_backtrack :-
1196 remove_from_op_trace_ids(LastTraceH), % remove last operation id from op_id trace
1197 retract(history(History)),
1198 retract(current_state_id(CurID)),!,
1199 History= [LastID|EHist],
1200 assertz(history(EHist)),
1201 %visited_expression(LastID,LastExpr,LastBody),
1202 assertz(current_state_id(LastID)),
1203 (retract(forward_history(FwdHist)) -> true ; FwdHist=[]),
1204 assertz(forward_history([forward(CurID,LastTraceH)|FwdHist])).
1205
1206 % used for right-clicks in history
1207 tcltk_backtrack(N) :- N =< 0, !.
1208 tcltk_backtrack(N) :- % TO DO: more efficient version
1209 tcltk_backtrack, N1 is N-1, tcltk_backtrack(N1).
1210
1211 :- dynamic saved_forward_history/2.
1212 :- volatile saved_forward_history/2.
1213
1214
1215 % save certain information to restore when reload is completed:
1216 tcltk_prepare_for_reload :-
1217 saved_forward_history([_|_],Mode), % tcltk_try_reload not executed; probably reloading failed
1218 animation_mode(Mode),
1219 current_state_id(root), %user has not performed another trace
1220 get_action_trace([]),!,
1221 format('Keeping saved forward history~n',[]). % so that user can fix error and re-load again
1222 tcltk_prepare_for_reload :-
1223 retractall(saved_forward_history(_,_)),
1224 get_action_term_trace(TrA),reverse(TrA,Tr),
1225 %print(prepare_reloading(Tr)),nl,
1226 maplist(gen_unknown_forward,Tr,SavedForwardHistory),
1227 animation_mode(Mode),
1228 % TO DO: add current forward history as well and restore when doing a reload with fastforward
1229 % forward_history(ForwHis), maplist(remove_forward_id,ForwHis,SavedPrevForwHis),
1230 assertz(saved_forward_history(SavedForwardHistory,Mode)).
1231
1232 %remove_forward_id(forward(_,Step),forward('$UNKNOWN',Step)).
1233 gen_unknown_forward(Step,forward('$UNKNOWN',Step)). % the forward ID is unknown
1234
1235 % try reloading certain information from previous load of same model
1236 tcltk_try_reload :-
1237 retract(saved_forward_history(SavedForwardHistory,Mode)),
1238 animation_mode(Mode), % we are in the same mode as when saved
1239 !,
1240 % TO DO: also retractall in other places
1241 %print(reloading(SavedForwardHistory)),nl,
1242 retractall(forward_history(_)),
1243 assertz(forward_history(SavedForwardHistory)).
1244 tcltk_try_reload.
1245
1246
1247 % go forward while possible
1248 tcltk_fast_forward :- tcltk_can_forward,!, tcltk_forward,
1249 current_state_id(CurID),
1250 compute_state_information_if_necessary(CurID),
1251 tcltk_fast_forward.
1252 tcltk_fast_forward.
1253
1254 tcltk_can_forward :- forward_history([_|_]).
1255 tcltk_can_forward(Len) :- forward_history(His), length(His,Len), Len>0.
1256
1257
1258 tcltk_forward(N) :- N =< 0, !.
1259 tcltk_forward(N) :- % TO DO: more efficient version
1260 tcltk_forward, N1 is N-1, tcltk_forward(N1).
1261
1262
1263 tcltk_forward :- \+ tcltk_can_forward,!,
1264 print_message('Cannot go forward'),fail.
1265 tcltk_forward :-
1266 retract(forward_history([forward(FwdID,LastTraceH)|FwdHist])),
1267 retract(history(EHist)),
1268 retract(current_state_id(CurID)),!,
1269 go_forward(FwdID,LastTraceH,FwdHist,CurID,EHist).
1270 go_forward('$UNKNOWN',ActionAsTerm,FwdHist,CurID,EHist) :-
1271 transition(CurID,ActionAsTerm,TransitionID,FwdID),!,
1272 %print(found(CurID,ActionAsTerm,TransitionID,FwdID)),nl,
1273 go_forward(FwdID,TransitionID,FwdHist,CurID,EHist).
1274 % TO DO: try and execute by predicate in case max_reached is true !
1275 go_forward('$UNKNOWN',ActionAsTerm,FwdHist,CurID,EHist) :-
1276 is_initialisation_op(ActionAsTerm),
1277 % maybe PROPERTIES/INITIALISATION has changed; try and replay with other values
1278 transition(CurID,ActionAsTerm2,TransitionID,FwdID),
1279 is_initialisation_op(ActionAsTerm2),
1280 !,
1281 %print(found(CurID,ActionAsTerm,TransitionID,FwdID)),nl,
1282 translate_event(ActionAsTerm,Action),
1283 format('Could not replay ~w.~nUsing other possible transition instead.~n',[Action]),
1284 go_forward(FwdID,TransitionID,FwdHist,CurID,EHist).
1285 go_forward('$UNKNOWN',ActionAsTerm,_FwdHist,CurID,EHist) :- !,
1286 assertz(forward_history([])),
1287 assertz(history(EHist)),
1288 assertz(current_state_id(CurID)),
1289 translate_event(ActionAsTerm,Action),
1290 add_error(tcltk_forward,'Cannot replay step after reload: ',Action).
1291 go_forward(FwdID,LastTraceH,FwdHist,CurID,EHist) :-
1292 assertz(forward_history(FwdHist)),
1293 assertz(history([CurID|EHist])),
1294 add_to_op_trace_ids(LastTraceH),
1295 assertz(current_state_id(FwdID)),
1296 re_execute_transition_if_necessary(CurID,LastTraceH,FwdID).
1297 %visited_expression(FwdID,FwdExpr,FwdBody).
1298
1299 is_initialisation_op(Op) :-
1300 (functor(Op,'$setup_constants',_) ; functor(Op,'$partial_setup_constants',_)
1301 ; functor(Op,'$initialise_machine',_)).
1302
1303 % re-execute operation with side-effects if necessary and if preference set
1304 % TO DO: tie into tcltk_perform so that not only the forward button but also double click
1305 % in operations pane works
1306 re_execute_transition_if_necessary(FromID,TransitionID,ToID) :-
1307 b_or_z_mode,
1308 get_preference(re_execute_operations_with_side_effects,true),
1309 bmachine_construction:external_procedure_used(_), % TO DO: check if operation itself has side-effects
1310 !,
1311 (re_execute_transition(FromID,TransitionID,ToID)
1312 -> true
1313 ; add_error(tcltk_forward,'Could not re-execute operation: ',TransitionID)).
1314 re_execute_transition_if_necessary(_,_,_).
1315
1316 re_execute_transition(FromID,TransitionID,ToID) :-
1317 transition(FromID,ActionTerm,TransitionID,ToID),
1318 %%print(trans(ActionTerm)),nl,
1319 get_operation_name(ActionTerm,OpName),
1320 debug_println(9,re_executing_operation(OpName,FromID,TransitionID,ToID)),
1321 visited_expression(FromID,InState),
1322 specfile:b_trans(InState,OpName,ActionTerm,_NewState,_TransInfo),
1323 debug_println(9,re_executed(OpName)).
1324
1325 % a version of tcltk_perform_action_term which can be given only the String (e.g., for trace checking)
1326 tcltk_perform_action_string(ActionString,ActionAsTerm,NewID) :-
1327 current_state_id(CurID),
1328 transition(CurID,ActionAsTerm,_,NewID),
1329 translate_event_with_src_and_target_id(ActionAsTerm,CurID,NewID,ActionString),
1330 tcltk_goto_state(ActionAsTerm,NewID).
1331 % translate_event_with_limit(ActionAsTerm,5000,ActionString). % should use same limit as below; otherwise trace checking will fail; ideally we should check ActionString is prefix
1332 %translate_event(ActionAsTerm,ActionString).
1333
1334 % perform the Action with term ActionAsTerm leading to new state NewID
1335 tcltk_perform_action_term(ActionAsTerm,NewID) :- %print(tcltk_perform_action_term(Action,ActionAsTerm,NewID)),nl,
1336 (var(ActionAsTerm)
1337 -> add_internal_error('Illegal call: ',tcltk_perform_action_term(ActionAsTerm,NewID)) ; true),
1338 tcltk_goto_state(ActionAsTerm,NewID).
1339
1340 /* allows one to execute an action in term form, from the current state: */
1341 %tcltk_perform_action(T,Cur) :- print_message(perf(T,Cur)),fail.
1342
1343 tcltk_perform_action(ActionAsTerm,NewID) :-
1344 current_state_id(CurID),
1345 tcltk_perform_action(CurID,ActionAsTerm,NewID).
1346 tcltk_perform_action(CurID,ActionAsTerm,NewID) :-
1347 tcltk_perform_action(CurID,ActionAsTerm,NewID,_).
1348 tcltk_perform_action(CurID,ActionAsTerm,TransitionID,NewStateID) :-
1349 transition(CurID,ActionAsTerm,TransitionID,NewStateID),
1350 tcltk_goto_state(ActionAsTerm,NewStateID).
1351
1352 tcltk_no_constants_or_no_inititalisation_found :-
1353 current_state_id(CurID),
1354 (CurID=root ; is_concrete_constants_state_id(CurID)),
1355 \+ candidate_setup_constants_or_init(CurID,_), % no additional unexplored candidates
1356 current_options([]).
1357
1358
1359
1360 /* ------------ */
1361 /* tcltk_open/1 */
1362 /* ------------ */
1363
1364
1365 %prolog_check_load_errors :-
1366 % (tcltk_find_untyped_consts(ErrRes)
1367 % -> add_error(prolog_open,'These constants were not given a proper type:', ErrRes)
1368 % ; true),
1369 % (tcltk_find_untyped_vars(ErrRes)
1370 % -> add_error(prolog_open,'These variables were not given a proper type:', ErrRes)
1371 % ; true).
1372
1373 tcltk_open_b_file_for_minor_mode(File,Minor) :- tcltk_open_b_file(File),
1374 set_animation_minor_mode(Minor).
1375
1376 tcltk_open_b_file(File) :-
1377 tcltk_clear_machine,
1378 set_animation_mode(b),
1379 print_message(loading_b_file(File)),flush_output,
1380 set_currently_opening_file(File),
1381 % to do: b_load_machine_probfile
1382 (b_load_aux(File)
1383 -> print_message(loaded),
1384 set_currently_opened_b_file(File)
1385 ; tcltk_set_failed_to_open_file(File),
1386 fail
1387 ).
1388
1389 tcltk_set_failed_to_open_file(File) :-
1390 set_failed_to_open_file(File),
1391 copy_current_errors_to_state(root,loading_context(File)).
1392
1393 :- use_module(probsrc(bmachine), [b_load_machine_from_file/1,b_load_machine_probfile/1]).
1394 :- use_module(tools,[get_filename_extension/2]).
1395 b_load_aux(File) :- get_filename_extension(File,'prob'),!,
1396 b_load_machine_probfile(File).
1397 b_load_aux(File) :-
1398 b_load_machine_from_file(File).
1399
1400 :- use_module(xtl_interface,[open_xtl_file/1]).
1401 tcltk_open_xtl_file(File) :- % TODO: redundant wrt load_xtl_spec_from_prolog_file
1402 tcltk_clear_machine,
1403 set_animation_mode(xtl),
1404 set_currently_opening_file(File),
1405 (open_xtl_file(File)
1406 -> set_currently_opened_file(File)
1407 ; tcltk_set_failed_to_open_file(File), fail).
1408
1409
1410 tcltk_open_cspm_file(File) :-
1411 tcltk_clear_machine,
1412 set_animation_mode(cspm),
1413 set_currently_opening_file(File),
1414 (xtl_interface:open_cspm_file(File)
1415 -> set_currently_opened_file(File)
1416 ; tcltk_set_failed_to_open_file(File), fail).
1417
1418 :- use_module(xtl_interface).
1419 %tcltk_open_promela_file(File) :-
1420 % tcltk_clear_machine,
1421 % set_animation_mode(promela), set_currently_opening_file(File),
1422 % xtl_interface:open_promela_file(File), set_currently_opened_file(File).
1423
1424 % disabled because Java parser seems broken
1425 %tcltk_open_smv_file(File) :-
1426 % tcltk_clear_machine,
1427 % set_animation_mode(smv), set_currently_opening_file(File),
1428 % xtl_interface:open_smv_file(File), set_currently_opened_file(File).
1429
1430 :- use_module(specfile,[type_check_csp_and_b/0]).
1431 :- use_module(library(file_systems),[file_exists/1,delete_file/1]).
1432
1433 tcltk_add_csp_file(File) :-
1434 \+ file_exists(File),!,
1435 add_error(csp_guide,'CSP guide file does not exist:',File).
1436 tcltk_add_csp_file(File) :-
1437 unset_animation_minor_modes(L), % we could be in z or tla or eventb mode
1438 set_animation_mode(csp_and_b),
1439 reset_animation_minor_modes(L),
1440 xtl_interface:open_cspm_file(File),
1441 notify_change_of_animation_mode,
1442 debug_format(19,'Added csp-guide file ~w~n',[File]),
1443 type_check_csp_and_b.
1444
1445 notify_change_of_animation_mode :-
1446 announce_event(change_of_animation_mode).
1447 % clear_applicable_flag. % no done via event handling
1448
1449
1450 tcltk_open_z_file(File) :-
1451 tcltk_clear_machine,
1452 tcltk_open_z_file2(File).
1453 tcltk_open_z_file2(File) :-
1454 set_currently_opening_file(File),
1455 open_proz_file(File,BMachine),
1456 set_animation_mode(b), set_animation_minor_mode(z),
1457 b_set_typed_machine(BMachine,File),
1458 !,
1459 set_currently_opened_b_file(File).
1460 tcltk_open_z_file2(File) :- tcltk_set_failed_to_open_file(File),fail.
1461
1462 :- use_module(parsercall,[call_fuzz_parser/2]).
1463 tcltk_open_z_tex_file(TexFile) :-
1464 tcltk_clear_machine,
1465 call_fuzz_parser(TexFile,FuzzFile),
1466 tcltk_open_z_file2(FuzzFile).
1467
1468
1469 :- use_module(eclipse_interface,[load_eventb_file/1]).
1470 tcltk_load_packaged_eventb_file(File) :-
1471 tcltk_clear_machine,
1472 load_eventb_file(File).
1473
1474 :- use_module(eclipse_interface,[load_cnf_file/2]).
1475 tcltk_load_cnf_file(File) :-
1476 tcltk_clear_machine,
1477 load_cnf_file(File,[]).
1478
1479 :- use_module(parsercall,[call_alloy2pl_parser/2]).
1480 :- use_module(probsrc('alloy2b/alloy2b')).
1481 tcltk_open_alloy_file(AlloyFile) :-
1482 tcltk_clear_machine,
1483 start_ms_timer(T1),
1484 formatsilent('Parsing Alloy file: ~w~n',[AlloyFile]),
1485 set_currently_opening_file(AlloyFile),
1486 call_alloy2pl_parser(AlloyFile,PrologFile),
1487 (silent_mode(off) -> stop_ms_walltimer_with_msg(T1,'parsing and type checking: ') ; true),
1488 %printsilent(generated_prolog_ast(PrologFile)),nls,
1489 start_ms_timer(T2),
1490 ( load_alloy_ast_prolog_file(PrologFile)
1491 -> true
1492 ; delete_file(PrologFile), % delete parsed Prolog file if model couldn't be loaded
1493 fail % since it's potentially empty due to the failure
1494 ),
1495 !,
1496 (silent_mode(off) -> stop_ms_walltimer_with_msg(T2,'loading and translation to B: ') ; true),
1497 set_currently_opened_b_file(AlloyFile).
1498 tcltk_open_alloy_file(AlloyFile) :- tcltk_set_failed_to_open_file(AlloyFile),fail.
1499
1500
1501 tcltk_open_alloy_prolog_ast_file(AlloyPrologFile) :-
1502 tcltk_clear_machine,
1503 start_ms_timer(T2),
1504 load_alloy_ast_prolog_file(AlloyPrologFile),
1505 !,
1506 (silent_mode(off) -> stop_ms_walltimer_with_msg(T2,'loading B translation of Alloy: ') ; true),
1507 set_currently_opened_b_file(AlloyPrologFile).
1508
1509 %% tcltk_load_alloy_cmd_in_current_translation(+CmdName).
1510 tcltk_load_alloy_cmd_in_current_translation(CmdName) :-
1511 alloy2b:load_command_in_current_translation(CmdName).
1512
1513 %% tcltk_get_alloy_cmd_names(-CmdNames).
1514 tcltk_get_alloy_cmd_names(CmdNames) :-
1515 alloy2b:get_command_names(CmdNames).
1516
1517 %% tcltk_verify_alloy_cmd(+CmdName, +SolverName, -CmdIsValid, -IsCheckCmd).
1518 tcltk_verify_alloy_cmd(CmdName, SolverName, CmdIsValid, IsCheckCmd) :-
1519 verify_alloy_command(CmdName, SolverName, CmdIsValid, IsCheckCmd, Res), !,
1520 ( Res = solution(Bindings)
1521 -> bindings_to_state(Bindings, State),
1522 tcltk_add_cbc_state(State, CmdName)
1523 ; true
1524 ).
1525 tcltk_verify_alloy_cmd(_, _, unknown, unknown). % unknown command or solver; error already reported
1526
1527 bindings_to_state([], []).
1528 bindings_to_state([Binding|T], [Bind|NT]) :-
1529 (Binding = binding(Id,Val,_); Binding = bind(Id,Val)),
1530 Bind = bind(Id,Val),
1531 bindings_to_state(T, NT).
1532
1533 /* --------------------------------------------------------------------- */
1534
1535 tcltk_exists_an_open_node :-
1536 not_all_transitions_added(_) ; not_interesting(_).
1537 tcltk_goto_an_open_node :-
1538 (not_all_transitions_added(ID) ; not_interesting(ID)),!,
1539 tcltk_goto_state(find_open_node,ID).
1540 tcltk_goto_max_reached_node :-
1541 (max_reached_for_node(ID) ; time_out_for_node(ID)),!,
1542 tcltk_execute_trace_to_node(ID).
1543 tcltk_goto_timeout_node :-
1544 time_out_for_node(ID),!,
1545 tcltk_execute_trace_to_node(ID).
1546 % tcltk_goto_state(find_max_reached_node,ID).
1547
1548 tcltk_goto_an_invariant_violation :-
1549 invariant_violated(ID),!,
1550 tcltk_goto_state(find_inv_violation,ID).
1551
1552
1553 tcltk_goto_node_with_id(ToID) :-
1554 current_state_id(ToID),!.
1555 tcltk_goto_node_with_id(ID) :-
1556 visited_expression_id(ID),
1557 tcltk_execute_trace_to_node(ID).
1558
1559 tcltk_try_goto_node_with_id(ID) :-
1560 (tcltk_goto_node_with_id(ID) -> true
1561 ; add_internal_error('Call failed:',tcltk_goto_node_with_id(ID))).
1562
1563 /* --------------------------------------------------------------------- */
1564
1565 % TO DO: clean up and move into model_checker module
1566
1567 tcltk_state_space_only_has_root_node :- transition(root,_,ID),
1568 \+ not_all_transitions_added(ID),!,fail.
1569 tcltk_state_space_only_has_root_node.
1570
1571 tcltk_search_among_existing_nodes(TclTkRes,FindDeadlocks,FindInvViolations,
1572 FindGoal,FindAssViolations,FindStateErrors) :-
1573 search_among_existing_nodes(Res,FindDeadlocks,FindInvViolations,
1574 FindGoal,FindAssViolations,FindStateErrors),
1575 translate_error_for_tclk(Res,TclTkRes).
1576
1577 % if tcltk_state_space_only_has_root_node is true: then we should call search_among_existing_nodes before doing open_search to ensure that we uncover state_errors in the root node
1578 % TODO: process mc_continue_after_error preference
1579 search_among_existing_nodes(invariant_violation,_FindDeadlocks,FindInvViolations,
1580 _FindGoal,_FindAssViolations,_FindStateErrors) :-
1581 (get_state_space_stats(_,_,PrN), PrN>100
1582 -> print_message('Search Among Processed Nodes'), print_message(number_of_nodes(PrN)) ; true),
1583 FindInvViolations=1,
1584 (invariant_violated(ResID) -> true
1585 ; find_invariant_violation_among_not_checked_nodes(ResID)),
1586 tcltk_execute_trace_to_node(ResID).
1587 search_among_existing_nodes(Error,_FindDeadlocks,FindInvViolations,
1588 _FindGoal,_FindAssViolations,_FindStateErrors) :-
1589 FindInvViolations=1,
1590 find_xtl_csp_invariant_violation_among_all_existing_nodes(ResID,Error), % could be xtl_error
1591 tcltk_execute_trace_to_node(ResID).
1592 search_among_existing_nodes(DEADLOCK,FindDeadlocks,_,_,_,_) :-
1593 FindDeadlocks=1,
1594 visited_expression_id(ResID),
1595 transitions_computed_for_node(ResID),
1596 is_deadlocked(ResID),
1597 (time_out_for_node(ResID)
1598 -> DEADLOCK = possible_deadlock_timeout
1599 ; get_preference(store_only_one_incoming_transition,true) -> DEADLOCK = possible_deadlock
1600 ; DEADLOCK = deadlock),
1601 print_message(deadlock_among_existing_nodes(ResID)),
1602 tcltk_execute_trace_to_node(ResID).
1603 search_among_existing_nodes(goal_found,_,_,FindGoal,_,_) :-
1604 FindGoal=1,
1605 %visited_expression(ResID,_CurState),
1606 %\+(not_all_transitions_added(ResID)), % if commented out: will also look at open nodes
1607 node_satisfies_goal(ResID),
1608 tcltk_execute_trace_to_node(ResID).
1609 search_among_existing_nodes(assertion_violation,_,_,_,FindAssViolations,_) :-
1610 FindAssViolations=1,
1611 b_machine_has_assertions,
1612 visited_expression(ResID,CurState),
1613 transitions_computed_for_node(ResID),
1614 state_violates_assertions(ResID,CurState),
1615 tcltk_execute_trace_to_node(ResID).
1616 search_among_existing_nodes(ERR,_,_,_,_,FindStateErrors) :- FindStateErrors=1,
1617 state_space:state_error(ResID,_,Error), Error \== invariant_violated,
1618 (Error = abort_error(ERR,_,_,_) -> true ; ERR = state_error(Error)),
1619 tcltk_execute_trace_to_node(ResID).
1620 search_among_existing_nodes(all,_,_,_,_,_).
1621
1622
1623 compute_all_transitions_if_necessary :-
1624 current_state_id(CurID),
1625 compute_all_transitions_if_necessary(CurID,false).
1626 :- public compute_all_transitions_if_necessary/1.
1627 compute_all_transitions_if_necessary(CurID) :-
1628 compute_all_transitions_if_necessary(CurID,false).
1629
1630 compute_all_transitions_if_necessary(CurID,CheckInvariant) :-
1631 (retract_open_node(CurID) % will assert not_invariant_checked
1632 -> set_context_state(CurID),
1633 % first check invariant, relevant if we want to use specialized_inv proof information
1634 visited_expression(CurID,State),
1635 % TO DO: this does not expand concrete_constants: the expansion may be done twice below:
1636 % once for compute_invariant (corresponds_to_b...) and once for compute_all_transitions (prepare_state_for_specfile_trans)
1637 prepare_state_for_specfile_trans(State,CurID,PreparedState),
1638 (CheckInvariant==true
1639 -> compute_invariant_if_necessary_and_requested(CurID,PreparedState) ; true),
1640 compute_all_transitions(CurID,PreparedState),
1641 clear_context_state
1642 ; true).
1643 %compute_all_transitions_if_necessary(CurID,CurState) :-
1644 % ((not_all_transitions_added(CurID);not_interesting(CurID))
1645 % -> compute_all_transitions(CurID,CurState) ; true).
1646
1647
1648 compute_invariant_if_necessary_and_requested(ID,State) :-
1649 enter_new_error_scope(ErrScID,compute_invariant_if_necessary_and_requested), % here we setup a new error scope; see comment for force_check_invariantKO below
1650 compute_invariant_if_necessary(ID,State),
1651 exit_error_scope(ErrScID,_ErrOcc,compute_invariant_if_necessary_and_requested). % should we do something with error occured result ?
1652
1653 compute_invariant_if_necessary(ID,State) :-
1654 animation_mode(MODE),compute_invariant_if_necessary(ID,State,MODE).
1655 compute_invariant_if_necessary(ID,State,MODE) :-
1656 ( check_invariantKO(MODE,ID,State) -> true ; true).
1657
1658 check_invariantKO(ID,State) :-
1659 animation_mode(MODE),check_invariantKO(MODE,ID,State).
1660 check_invariantKO(b,ID,State) :-
1661 check_invariantKO2(ID,State).
1662 check_invariantKO(csp_and_b,ID,State) :-
1663 check_invariantKO2(ID,State).
1664 % for XTL we do not use not_invariant_checked/1 facts; one should call xtl_invariant_violated/1
1665
1666 % check invariant for B state
1667 check_invariantKO2(ID,_) :- invariant_violated(ID),!.
1668 check_invariantKO2(ID,CurState) :-
1669 set_invariant_checked(ID), % only succeeds if we haven't checked invariant for ID yet
1670 % print(check_inv(ID)),nl,
1671 state_corresponds_to_initialised_b_machine(CurState),
1672 ( preferences:preference(do_invariant_checking,false) -> assertz(not_invariant_checked(ID))
1673 ; force_check_invariantKO(ID,CurState)).
1674
1675
1676 force_check_invariantKO(ID,CurBState) :-
1677 % Note: this checks the invariant without setting up a new error scope
1678 % (Reason: in the model checker it would be relatively expensive to set up an error scope for each state
1679 % the model checker stops anyway when the first error is found and then exits its error scope)
1680 catch_clpfd_overflow_call_for_state(ID, 'checking invariants',
1681 b_state_violates_invariant(ID,CurBState),true) ->
1682 %(b_state_violates_invariant(ID,CurBState) ->
1683 set_invariant_violated(ID).
1684 % TO DO ?: call state_satisfies_negation_of_invariant if double_evaluation_when_analysing is true ?
1685
1686 % try and find an invariant violation among those nodes that have not yet been checked
1687 find_invariant_violation_among_not_checked_nodes(ID) :-
1688 retract(not_invariant_checked(ID)), %print(checking_invariant(ID)),nl,
1689 visited_expression(ID,State),
1690 state_corresponds_to_initialised_b_machine(State),
1691 prepare_state_for_specfile_trans(State,ID,CurBState),
1692 force_check_invariantKO(ID,CurBState).
1693
1694 find_xtl_csp_invariant_violation_among_all_existing_nodes(ID,Error) :-
1695 animation_mode(MODE),
1696 (MODE=xtl ; MODE=csp), % invariant violations not stored, hence we need to re-check every node
1697 visited_expression(ID,State),
1698 find_invariant_error(MODE,ID,State,Error). % csp_error or xtl_error
1699
1700 :- use_module(probporsrc(ample_sets),[compute_ample_set2/3]).
1701 % computing ample sets (model_checker.pl)
1702 compute_ample_set(CurID,CurState,POROptions) :-
1703 catch_clpfd_overflow_call_for_state(CurID,'computing ample sets for POR',
1704 compute_ample_set2(CurID,CurState,POROptions),clear_context_state).
1705
1706
1707 %compute_all_transitions(CurID,CurState) :- get_preference(use_clpfd_solver,false),!,
1708 % compute_all_transitions2(CurID,CurState). % in principle this overflow cannot/should not happen with CLPFD FALSE
1709 % but no performance benefit can be measured by removing the catch
1710 compute_all_transitions(CurID,CurState) :-
1711 catch_clpfd_overflow_call_for_state(CurID,'computing all enabled transitions',
1712 compute_all_transitions2(CurID,CurState),clear_context_state).
1713
1714
1715 %catch_clpfd_overflow_call_for_state(_CurID, Call,_ExtraCleanUpCode) :-
1716 % preferences:preference(use_clpfd_solver,false),!, % Overflow should not occur
1717 % call(Call).
1718 :- use_module(clpfd_interface,[catch_clpfd_overflow_call2/2]).
1719 catch_clpfd_overflow_call_for_state(CurID, Context, Call,ExtraCleanUpCode) :-
1720 catch_clpfd_overflow_call2(Call,
1721 ( store_state_error(CurID,clpfd_overflow_error(Context),_),
1722 call(ExtraCleanUpCode)) ).
1723
1724
1725
1726
1727 :- use_module(probsrc(succeed_max),[reset_max_reached/0,max_reached/0, max_reached/1]).
1728 compute_all_transitions2(CurID,CurState) :- /* compute all outgoing transitions for a given node */
1729 % set_context_state(CurID), % error_context is set for each operation below anyway.
1730 reset_max_reached,
1731 prepare_state_for_specfile_trans(CurState,CurID,PreparedCurState), % will perform unpacking of constants just once, for example
1732 ((time_out_preference_disabled % e.g., when using probcli -disable_time_out
1733 ; use_no_timeout(CurID))
1734 -> add_transitions_fail_loop(CurID,PreparedCurState)
1735 ; preferences:preference(time_out,CurTO),
1736 add_transitions__with_timeout_fail_loop(CurID,PreparedCurState,CurTO)
1737 ),
1738 add_partial_transitions(CurID,PreparedCurState), % also copies unsat component infos
1739 (max_reached -> assert_max_reached_for_node(CurID),MaxReached=true ; MaxReached=false),
1740 % TO DO: use max_reached(OpID)
1741 (CurID==root -> save_constants(MaxReached) ; add_new_transitions_to_cache(CurID))
1742 . %,clear_context_state.
1743
1744 :- use_module(error_manager,[get_virtual_time_out_from_exception/2]). % used by time_out_with_enum_warning_for_findall
1745 % loop to compute successor states without a time_out
1746 add_transitions_fail_loop(CurID,CurState) :-
1747 catch(
1748 add_transitions_fail_loop2(CurID,CurState,TimeOutRes),
1749 Exc,
1750 get_virtual_time_out_from_exception(Exc,TimeOutRes)),
1751 (nonvar(TimeOutRes),
1752 (TimeOutRes=operation_time_out(Op,TimeOutRes2)
1753 -> assert_time_out_for_node(CurID,Op,TimeOutRes2)
1754 ; assert_time_out_for_node(CurID,'unspecified_operation',TimeOutRes))
1755 ; true).
1756
1757 add_transitions_fail_loop2(CurID,CurState,_) :-
1758 possible_trans_name_for_successors(CurState,ActionName),
1759 % we could check pge info here (e.g., store one Predecessor ID and look if ActionName can be enabled after)
1760 set_error_context(operation(ActionName,CurID)),
1761 add_transition(CurID,CurState,ActionName,_NewId), % TO DO: transmit animation_mode value?
1762 fail.
1763 add_transitions_fail_loop2(_,_,OpTimeOutRes) :-
1764 (enumeration_warning_occured_in_error_scope
1765 -> (virtual_time_out_occured_in_error_scope(TimeOutRes)
1766 -> % i.e., critical enumeration warning occurred
1767 (get_error_context(operation(ActionName,_))
1768 -> OpTimeOutRes = operation_time_out(ActionName,TimeOutRes)
1769 ; OpTimeOutRes = operation_time_out('unspecified_operation',TimeOutRes))
1770 ; true),
1771 clear_enumeration_warnings
1772 ; true % no warnings: sunshine case
1773 ),
1774 clear_error_context.
1775
1776 possible_trans_name_for_successors(CurState,ActionName) :-
1777 specfile_possible_trans_name_for_successors(CurState,ActionName),
1778 (preference(store_only_one_incoming_transition,true), % SAFETY_MODEL_CHECK
1779 nonvar(ActionName),
1780 b_or_z_mode,
1781 b_operation_cannot_modify_state(ActionName) % we have a skip operation
1782 -> operation_not_yet_covered(ActionName)
1783 % if operation covered: all we could is create a self-loop, which would not be added to the state space anyway
1784 ; true).
1785
1786
1787 :- use_module(library(timeout),[time_out/3]).
1788 my_timeout_test(1000000) :- write('.'), !, my_timeout_test(0).
1789 my_timeout_test(X) :- X1 is X+1, my_timeout_test(X1).
1790 :- public my_timeout_test/0.
1791 my_timeout_test :- time_out(my_timeout_test(0),500,TO), nl,
1792 print(time_out_result(TO)),nl, TO==time_out.
1793 :- assert_must_succeed(tcltk_interface:my_timeout_test).
1794
1795 add_transitions__with_timeout_fail_loop(CurID,CurState,CurTO) :-
1796 enter_new_error_scope(Level,add_transitions__with_timeout_fail_loop),
1797 call_cleanup(add_transitions__with_timeout_fail_loop2(Level,CurID,CurState,CurTO),
1798 exit_error_scope(Level,_,add_transitions__with_timeout_fail_loop)).
1799
1800 % old profiler
1801 :- use_module(runtime_profiler,[profile_failure_driven_loop/2]).
1802
1803 % the loop to compute all successors of state CurID with a time-out
1804 add_transitions__with_timeout_fail_loop2(Level,CurID,CurState,CurTO) :- % statistics(runtime,_),
1805 % TO DO: prepare computing the state: expanding const and vars, unpacking, ...
1806 possible_trans_name_for_successors(CurState,ActionName),
1807 profile_failure_driven_loop(ActionName,CurID),
1808 % Note: we enumerate possible transition names so that we can catch the time-out per name !
1809 % statistics(runtime,[T1,DeltaT]), print(delta_time(ActionName,DeltaT)),nl, %%
1810 % first enumerate possible Operations/... to obtain timeout per operation/...
1811 % TO DO: divide CurTO by number of transitions ???
1812 % We could also decide to have one time-out per state, only if that one is triggered move to
1813 % finer-grained timeouts
1814 % For probcli ../prob_examples/public_examples/B/Benchmarks/Cruise_finite1.mch --model-check, there are 35360 calls to timeout/3 (one per state the model checker reached and per transition group), with -disable-timeout none
1815 % In SICS 4.3.5 the runtime increased from 1.480 to 2.270 seconds = 0.022 ms per timeout call
1816 % In SICS 4.4.1 the runtime increased from 1.494 to 3.033 seconds. = 0.044 ms per timeout call.
1817 %% statistics(runtime,[T1,_]), print(try(ActionName,T1)),nl,%%
1818 set_error_context(operation(ActionName,CurID)),
1819 (nonvar(ActionName),translate_operation_name(ActionName,A2),
1820 get_specific_time_out_for_operation(A2,RealTimeOut) -> true ; RealTimeOut = CurTO),
1821 time_out_with_enum_warning_for_findall_in_current_error_scope(Level,
1822 (add_transition(CurID,CurState,ActionName,_NewId),fail), % fail inside meta-call;
1823 % so that time_out is for entire add_transition loop; not just for each single solution
1824 RealTimeOut,TimeOutRes),
1825 %% statistics(runtime,[T2,_]), TDiff is T2-T1, print(added_transition(CurID,ActionName,TDiff,TimeOutRes)),nl, %%
1826 %% add_transition(CurID,CurState,ActionName,_NewId) ,
1827 ((TimeOutRes==time_out ;
1828 nonvar(TimeOutRes),TimeOutRes=virtual_time_out(_), \+ max_reached(ActionName))
1829 % virtual time outs not relevant if we have already stopped earlier anyway;
1830 % TO DO: does not seem to work for INITIALISATION
1831 -> (TimeOutRes=virtual_time_out(_) -> true
1832 ; print_message('TIME OUT: '),print_message(CurID),
1833 print_message(RealTimeOut),print_message(ActionName)
1834 ),
1835 (var(ActionName)
1836 -> assert_time_out_for_node(CurID,'unspecified_operation',TimeOutRes)
1837 ; assert_time_out_for_node(CurID,ActionName,TimeOutRes) % TO DO: assert info per ActionSkeleton ?
1838 )
1839 ; true
1840 ),fail.
1841 add_transitions__with_timeout_fail_loop2(_,_,_,_) :- clear_error_context.
1842 % statistics(runtime,[_,DeltaT]), print(delta_time(end,DeltaT)),nl.
1843
1844 % compute and add transition to next states
1845 add_transition(CurID,CurState,ActionName,NewId) :-
1846 /* ActionName maybe pre-instantiated */
1847 extract_infos_from_prepared_state(CurState,PrecomputedInfos),
1848 specfile_trans(CurState,ActionName,Act,NewExpression,TransInfo,Residue),
1849 %% print_bt_message(specfile_trans(CurState,ActionName,Act,NewExpression,TransInfo,Residue)), %%
1850 add_trans_id_with_infos(CurID,PrecomputedInfos,Act,NewExpression,Residue,NewId,TransInfo,_).
1851
1852 :- use_module(kernel_tools,[add_call_residue_error/3]).
1853 % after being computed, add a new transition in the state space; adding the destination state if required
1854 add_trans_id_with_infos(CurID,PrecomputedInfos,Act,NewExpression,Residue,NewID,TransInfo,TransId) :-
1855 (Residue=[] -> true
1856 ; ajoin(['Prolog residue while computing transition ',Act,' in state ',CurID,':'],Msg),
1857 add_call_residue_error(add_trans_id,Msg,Residue)
1858 ),
1859 add_new_transition_transid_with_infos(CurID,PrecomputedInfos,Act,NewID,NewExpression,TransInfo,TransId).
1860
1861
1862
1863 add_trans_id(CurID,Act,NewExpression,NewID,TransId) :-
1864 add_trans_id_with_infos(CurID,[],Act,NewExpression,[],NewID,[],TransId).
1865
1866 add_trans_id_infos(CurID,Act,NewExpression,NewID,TransId,TransInfos) :-
1867 add_trans_id_with_infos(CurID,[],Act,NewExpression,[],NewID,TransInfos,TransId).
1868
1869 add_partial_transitions(root,CurState) :-
1870 % for the moment root is the only state where partial transitions are computed
1871 % note: some regular setup_constants transitions can cover partial_properties and are also partial transitions
1872 % (but which find values for all constants)
1873 \+ any_transition(root,_,_),
1874 % No transition was found, we try and extract deterministic values found for constants
1875 % and will add PARTIAL_SETUP_CONSTANTS if all constants valued or if preference allows it
1876 partial_trans(CurState,Act,NewExpression,Residue),
1877 add_trans_id_with_infos(root,[],Act,NewExpression,Residue,_NewID,[],_),fail.
1878 add_partial_transitions(_CurID,_).
1879
1880 /* --------------------------------------------------------------------- */
1881
1882 /* A bit like AO* algorithm: expands open nodes (i.e., states whose transitions
1883 have not yet been computed */
1884
1885 :- use_module(model_checker).
1886
1887 tcltk_model_check(Nr,TclTkRes,FindDeadlocks,FindInvViolations,FindGoal,FindAssViolations,
1888 FindStateErrors,StopFullCoverage,PartialOrderReduction,TIMELIMIT,TotalTime) :-
1889 statistics(walltime,[CurTime,_]), /* get current time in ms */
1890 LimitTime is CurTime+TIMELIMIT,
1891 %debug_println(10,start_tcltk_model_check(Nr,TIMELIMIT)),
1892 InspectExistingNodes = 0,
1893 (do_model_check(Nr,_A,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1894 FindAssViolations,FindStateErrors,StopFullCoverage,
1895 PartialOrderReduction,InspectExistingNodes)
1896 -> translate_error_for_tclk(Res,TclTkRes)
1897 ; add_internal_error('Call failed: ',do_model_check(Nr,_A,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1898 FindAssViolations,FindStateErrors,StopFullCoverage,
1899 PartialOrderReduction,InspectExistingNodes)),
1900 TclTkRes=error),
1901 statistics(walltime,[CurTime2,_]),
1902 TotalTime is CurTime2-CurTime,
1903 debug_println(10,tcltk_model_check(Nr,TotalTime,Res)).
1904
1905 translate_error_for_tclk([timeout,Nr],Res) :- !, Res=[timeout,Nr].
1906 translate_error_for_tclk(state_error(S),String) :- !, translate_state_err_for_tcltk(S,String).
1907 translate_error_for_tclk(S,R) :- atomic(S),!,R=S.
1908 translate_error_for_tclk(S,R) :- nonvar(S), add_error(translate_error_for_tclk,'Unknown Model Check result: ',S), R=unknown.
1909
1910 translate_state_err_for_tcltk(abort_error(TYPE,_,_,_),ERR) :- !, ERR = TYPE.
1911 translate_state_err_for_tcltk(eventerror(Event,Error,_),ERR) :- !,
1912 functor(Error,F,_),
1913 ajoin(['event_error:',Event,':',F],ERR).
1914 translate_state_err_for_tcltk(Error,ERR) :-
1915 functor(Error, StateError, _), atom_concat('state_error:',StateError,ERR).
1916
1917
1918
1919 do_model_check(_Nr,NodesAnalysed,_LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1920 FindAssViolations,FindStateErrors,_StopFullCoverage,
1921 _PartialOrderReduction,ForceInspectExistingNodes) :-
1922 (tcltk_state_space_only_has_root_node -> true % Then also look at the root node
1923 ; ForceInspectExistingNodes == 1),
1924 search_among_existing_nodes(Res,FindDeadlocks,FindInvViolations,FindGoal,
1925 FindAssViolations,FindStateErrors),
1926 Res \=all, NodesAnalysed=0.
1927 do_model_check(LimitNr,NodesAnalysed,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1928 FindAssViolations,FindStateErrors,StopFullCoverage,PartialOrderReduction,_) :-
1929 update_ass(FindAssViolations,FindAssViolations2),
1930 open_search(LimitNr,NodesAnalysed,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1931 FindAssViolations2,FindStateErrors,StopFullCoverage,PartialOrderReduction).
1932
1933 update_ass(1,FindAssViol) :- \+ b_machine_has_assertions,!, % no need to check assertions
1934 FindAssViol=0.
1935 update_ass(X,X).
1936
1937 /* --------------------------------------------------- */
1938
1939 /* constraint-based checking of refinements */
1940 :- use_module(symbolic_model_checker(cbc_refinement_checks), [cbc_refinement_check/2]).
1941 tcltk_cbc_refinement_check(list(List),ErrorOccured) :-
1942 cbc_refinement_check(List,ErrorOccured).
1943
1944 /* constraint-based/model search for invariant violations */
1945
1946 :- dynamic cbc_inv_error_found/2.
1947
1948 tcltk_constraint_based_check(L) :- tcltk_constraint_based_check(L,_).
1949 tcltk_constraint_based_check(list(List),ErrorsOrTimeoutWereFound) :-
1950 retractall(cbc_inv_error_found(_,_)),
1951 findall(Res, (tcltk_constraint_based_check_with_timeout(OpName,ErrorDesc),
1952 (ErrorDesc=ok -> true ; assertz(cbc_inv_error_found(OpName,ErrorDesc))),
1953 string_concatenate(' == ',ErrorDesc,Res1),
1954 string_concatenate(OpName,Res1,Res)), List),
1955 %%print(list(List)),nl, %%
1956 (cbc_inv_error_found(_,_) ->
1957 (cbc_inv_error_found(_,X),X\=time_out
1958 -> ErrorsOrTimeoutWereFound=true ; ErrorsOrTimeoutWereFound=time_out
1959 )
1960 ; ErrorsOrTimeoutWereFound = false).
1961
1962 % can also be called with uninstantiated OpName
1963 tcltk_constraint_based_check_with_timeout(OpName,ErrorDesc) :-
1964 tcltk_constraint_based_check_with_timeout(OpName,invariant,ErrorDesc).
1965 % InvOrAssertion is invariant or assertions: check whether OpName can violate the invariant or the dynamic assertions
1966 tcltk_constraint_based_check_with_timeout(OpName,InvOrAssertion,ErrorDesc) :-
1967 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
1968 valid_operation_or_init(OpName,IOpName),
1969 (time_out_with_enum_warning_one_solution(tcltk_constraint_based_check_op(IOpName,InvOrAssertion,ErrorDesc),DebugTimeOut,TimeOutRes)
1970 -> (is_time_out_result(TimeOutRes)
1971 -> print_message('TIME OUT: '), print_message(OpName), print_message(DebugTimeOut),
1972 ErrorDesc = time_out % callers (e.g., tcltk_constraint_based_check/2 and probcli) test for time_out
1973 ; true
1974 )).
1975 valid_operation_or_init(OpName,R) :- OpName=='@INITIALISATION',!,R='$initialise_machine'.
1976 valid_operation_or_init(OpName,OpName) :- b_get_machine_operation(OpName,_,_,_).
1977 valid_operation_or_init('INITIALISATION','$initialise_machine'). % used e.g. in test 1821: -cbc INITIALISATION
1978
1979 tcltk_constraint_based_check_op(OpName,ErrorDesc) :-
1980 tcltk_constraint_based_check_op(OpName,invariant,ErrorDesc).
1981
1982 tcltk_constraint_based_check_op(TclOpName,InvOrAssertion,ErrorDesc) :-
1983 adapt_tcl_operation_name(TclOpName,OpName),
1984 tcltk_constraint_based_check_op2(OpName,InvOrAssertion,ErrorDesc).
1985
1986 % code below because names with $ cause problems in Tcl with eval
1987 adapt_tcl_operation_name(X,R) :- var(X),!,R=X.
1988 adapt_tcl_operation_name('@PROPERTIES','$setup_constants') :- !.
1989 adapt_tcl_operation_name('@INITIALISATION','$initialise_machine') :- !.
1990 adapt_tcl_operation_name(X,X).
1991
1992 % a version that allows either invariant or assertions check after an Operation OpName
1993 tcltk_constraint_based_check_op2(OpName,InvOrAssertion,ErrorDesc) :-
1994 call_cbc_command(state_model_check(OpName,InvOrAssertion,State,Operation,NewState)),!,
1995 tcltk_add_cbc_state(State,'$JUMP'(constraint_based_check),PriorID), % will also set history
1996 translate_event(Operation,Action),
1997 tcltk_add_new_transition_transid(PriorID,Operation,NewID,NewState,[],TransId2),
1998 set_current_state_id(NewID),
1999 add_to_op_trace_ids(TransId2),
2000 add_id_to_history(PriorID),
2001 ajoin([InvOrAssertion,'_violated_after(',Action,')'],ErrorDesc).
2002 tcltk_constraint_based_check_op2(_,_,'ok').
2003
2004
2005 % try to find constants, parameters that make a given trace feasible
2006 tcltk_cbc_find_trace(TraceToBeFound,Res) :-
2007 tcltk_cbc_find_trace(TraceToBeFound,'',first_solution,Res).
2008
2009 %:- public tcltk_cbc_find_invariant_violation/2.
2010 %tcltk_cbc_find_invariant_violation(TraceToBeFound,Res) :-
2011 % tcltk_cbc_find_trace(TraceToBeFound,'#not_invariant',first_solution,Res).
2012 % could also call tcltk_constraint_based_check_op('$initialise_machine',invariant,Res)
2013
2014 tcltk_cbc_find_trace(TraceToBeFound,TargetPredString,FindAll,Res) :-
2015 b_parse_optional_machine_predicate(TargetPredString,TargetPred),
2016 formatsilent('Looking for solution for trace ~w~n',[TraceToBeFound]),
2017 split_atom(TraceToBeFound,[',',';',' '],TraceAsList),
2018 (maplist(check_valid_operation,TraceAsList)
2019 -> start_ms_timer(Timer),
2020 tcltk_cbc_find_trace_aux(Timer,TraceAsList,TargetPred,FindAll,Res)
2021 ; Res = error).
2022 % findall mode: find all paths; time_out_with_enum_warning_one_solution would cut after the first solution
2023 tcltk_cbc_find_trace_aux(Timer,TraceAsList,TargetPred,findall,Res) :- !,
2024 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
2025 reset_nr_cbc_sols,
2026 retractall(cbc_find_all_time_out_occurred),
2027 (time_out_with_enum_warning_for_findall(
2028 cbc_path_solver:create_testcase_path_nondet(init,TraceAsList,TargetPred,Transitions),DebugTimeOut,TimeOutRes),
2029 (is_time_out_result(TimeOutRes)
2030 -> print_message('*** TIME OUT: '), print_message(DebugTimeOut),
2031 assertz(cbc_find_all_time_out_occurred)
2032 ; inc_nr_cbc_sols,
2033 print('% *** FOUND PATH: '), maplist(print_trans,Transitions),nl
2034 ),
2035 fail % backtrack to find further solutions; we do not cut so that the error scope is exited properly
2036 ; true),
2037 stop_ms_timer(Timer),
2038 (retract(cbc_find_all_time_out_occurred)
2039 -> Res = time_out
2040 ; nr_cbc_sols(N), Res=nr_cbc_sols(N),
2041 print_message('*** ALL SOLUTIONS FOUND ')
2042 ).
2043 tcltk_cbc_find_trace_aux(Timer,TraceAsList,TargetPred,_,Res) :-
2044 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
2045 reset_nr_cbc_sols,
2046 time_out_with_enum_warning_one_solution(
2047 cbc_path_solver:create_testcase_path_nondet(init,TraceAsList,TargetPred,Transitions),DebugTimeOut,TimeOutRes),
2048 stop_ms_timer(Timer),
2049 (is_time_out_result(TimeOutRes)
2050 -> !,
2051 print_message('*** TIME OUT: '), print_message(DebugTimeOut), Res = time_out
2052 ; !,Res = ok,
2053 print('% *** FOUND PATH: '), maplist(print_trans,Transitions),nl,
2054 maplist(extract_trans_id,Transitions,TransIds),
2055 set_trace_by_transition_ids(TransIds)
2056 ).
2057 tcltk_cbc_find_trace_aux(Timer,_TraceToBeFound,_TargetPred,_FindAll,no_solution_found) :-
2058 stop_ms_timer(Timer),
2059 print_message('*** NO SOLUTION FOUND'),nl.
2060
2061 :- dynamic cbc_find_all_time_out_occurred/0.
2062 :- dynamic nr_cbc_sols/1.
2063 nr_cbc_sols(0).
2064 reset_nr_cbc_sols :- retractall(nr_cbc_sols(_)), assertz(nr_cbc_sols(0)).
2065 inc_nr_cbc_sols :-
2066 retract(nr_cbc_sols(N)), N1 is N+1, assertz(nr_cbc_sols(N1)).
2067 extract_trans_id( (TransId,_,_,_), TransId).
2068 print_trans( (_,Event,_,_)) :- translate_event(Event,S), print(S), print(' ').
2069
2070 :- use_module(probsrc(tools_matching), [get_possible_top_level_event_matches_msg/2]).
2071 check_valid_operation(Op) :-
2072 (get_possible_language_specific_top_level_event(Op,_,_) -> true
2073 ; (get_possible_top_level_event_matches_msg(Op,FMsg)
2074 -> ajoin(['Unknown operation/event (did you mean ',FMsg,' ?):'],Msg)
2075 ; Msg='Unknown operation/event:'
2076 ),
2077 add_error(cbc_find_sequence,Msg,Op),
2078 fail
2079 ).
2080
2081 tk_get_possible_language_specific_top_level_event(OpName,list(ResultNames),list(ParameterNames)) :-
2082 get_possible_language_specific_top_level_event(OpName,ResultNames,ParameterNames).
2083
2084
2085 % ------------
2086
2087 :- use_module(bsyntaxtree).
2088 tcltk_constraint_find_valid_state_with_pred(ParameterBindList,RestPreCond,UseConstantsFromStateID) :-
2089 parse_tclk_parameter_values_and_pred('$initialise_machine',ParameterBindList,RestPreCond,CustomPredicate),
2090 UseInvariant=true,
2091 call_cbc_command(
2092 b_state_model_check:b_set_up_valid_state_with_pred(State,CustomPredicate,
2093 UseInvariant,UseConstantsFromStateID)),
2094 tcltk_add_cbc_state(State,find_valid_state).
2095 tcltk_constraint_find_valid_state :-
2096 call_cbc_command(b_set_up_valid_state(State)),
2097 tcltk_add_cbc_state(State,find_valid_state).
2098
2099 :- use_module(extrasrc(optimizing_solver),[b_set_up_maximally_valid_state/2]).
2100 tcltk_constraint_find_maximal_valid_state :-
2101 current_state_id(ID),
2102 call_cbc_command(b_set_up_maximally_valid_state(ID,State)),
2103 tcltk_add_cbc_state(State,find_maximal_valid_state).
2104
2105
2106 tcltk_constraint_find_dynamic_assertion_violation :-
2107 call_cbc_command(b_find_dynamic_assertion_violation(State)),
2108 tcltk_add_cbc_state(State,cbc_dynamic_assertions_check).
2109
2110 :- use_module(clpfd_interface,[catch_clpfd_overflow_call1/1]).
2111 :- use_module(error_manager,[call_in_fresh_error_scope_for_one_solution/1]).
2112 % catch CLPFD overflows and catch other errors
2113 call_cbc_command(Command) :-
2114 call_in_fresh_error_scope_for_one_solution(
2115 (catch_clpfd_overflow_call1(Command) -> true
2116 ; translate_events_in_current_scope_to_warnings(cbc,'Warning: '),fail
2117 % Maybe we should raise error when Command fails and enumeration warnings are there ?
2118 )).
2119
2120
2121 tcltk_constraint_find_deadlock_state(Res) :-
2122 check_we_are_in_b_mode(cbc_deadlock_freedom_check),
2123 create_texpr(truth,pred,[],True),
2124 call_cbc_deadlock_check(True,0,Res).
2125
2126 % if Filter=1 we remove guards which are inconsitent with goal
2127 tcltk_constraint_find_deadlock_state_with_goal(Filter,Res) :-
2128 check_we_are_in_b_mode(cbc_deadlock_freedom_check),
2129 (b_get_machine_goal(Goal) -> true ; create_texpr(truth,pred,[],Goal)),
2130 call_cbc_deadlock_check(Goal,Filter,Res).
2131
2132 % fails if no deadlock was found
2133 call_cbc_deadlock_check(Goal,Filter,Res) :-
2134 call_cbc_command((cbc_deadlock_freedom_check(Result,Goal,Filter),
2135 translate_events_if_no_deadlock(Result))),
2136 process_cbc_deadlock_result(Result,Res).
2137
2138 % as call_cbc_command does when a command fails: keep events such as enumeration warnings as warnings
2139 translate_events_if_no_deadlock(no_deadlock(_)) :- !,
2140 translate_events_in_current_scope_to_warnings(cbc,'Warning: ').
2141 translate_events_if_no_deadlock(_).
2142
2143 :- use_module(b_state_model_check,[add_cbc_deadlock_imprecise_warning/1]).
2144 process_cbc_deadlock_result(time_out,time_out).
2145 process_cbc_deadlock_result(deadlock(State),deadlock) :- tcltk_add_cbc_state(State,cbc_deadlock).
2146 process_cbc_deadlock_result(no_deadlock(ImpreciseOps),_) :-
2147 add_cbc_deadlock_imprecise_warning(ImpreciseOps), % outside of the error scope of call_cbc_command
2148 fail.
2149
2150 check_we_are_in_b_mode(_) :- b_or_z_mode,!.
2151 check_we_are_in_b_mode(Cmd) :- add_error(check_we_are_in_b_mode,'This command can only be performed in B,Z or TLA+ mode: ',Cmd),fail.
2152
2153 tcltk_constraint_find_deadlock_state_with_goal(true,_Filter,Res) :-
2154 !,tcltk_constraint_find_deadlock_state(Res).
2155 tcltk_constraint_find_deadlock_state_with_goal(GoalPred,Filter,Res) :-
2156 bmachine:b_set_machine_goal(GoalPred),
2157 tcltk_constraint_find_deadlock_state_with_goal(Filter,Res).
2158
2159 :- use_module(cbcsrc(enabling_analysis),[check_if_feasible_operation/5]).
2160 tcltk_check_if_feasible_operation(OpName,UseInvariant,TimeOutFactor,Result) :- % UseInvariant currently always 1 from Tcl
2161 check_if_feasible_operation(OpName,UseInvariant,TimeOutFactor,Result,ResultState),
2162 tcltk_add_cbc_state(ResultState,feasibility_check(OpName)).
2163
2164 % add a state found by constraint-based verification or other method that tries to jump to a state without all intermediate steps
2165 % it will add a separate concrete_constants state if necessary
2166 tcltk_add_cbc_state(State,OpName) :-
2167 tcltk_add_cbc_state(State,'$JUMP'(OpName),_ToID).
2168
2169 tcltk_add_cbc_state('$UNKNOWN_STATE',_,To) :- !,To=none.
2170 tcltk_add_cbc_state(State,OpNameTerm,NewID) :-
2171 seperate_state_into_const_and_vars(State,Constants,Variables),
2172 !,
2173 % store the constants separately: important for memory consumption when continuing animation/model checking
2174 (Variables=[] -> Op='$initialise_machine' ; Op = OpNameTerm),
2175 % if Variables are [] we simply create an initialisation transition
2176 (Constants = [] % no need to create SETUP_CONSTANTS transition
2177 -> (Variables = [] % probably prior state for INITIALISATION cbc check
2178 -> NewID=root, set_cbc_state(root,[],[])
2179 ; FullState = Variables,
2180 tcltk_add_new_transition_transid(root,Op,NewID,FullState,[],TransId2),
2181 set_cbc_state(NewID,[TransId2],[root])
2182 )
2183 ; Variables = [], b_machine_has_variables
2184 -> % only constant values, e.g., counterexample for static assertions: we cannot construct an initialised state
2185 tcltk_add_new_transition_transid(root,'$setup_constants',NewID,concrete_constants(Constants),[],TransId1),
2186 set_cbc_state(NewID,[TransId1],[root])
2187 ; tcltk_add_new_transition_transid(root,'$setup_constants',CstID,concrete_constants(Constants),[],TransId1),
2188 FullState = const_and_vars(CstID,Variables),
2189 tcltk_add_new_transition_transid(CstID,Op,NewID,FullState,[],TransId2),
2190 set_cbc_state(NewID,[TransId1,TransId2],[CstID,root])
2191 ).
2192 tcltk_add_cbc_state(State,OpNameTerm,NewID) :-
2193 tcltk_add_new_transition_transid(root,OpNameTerm,NewID,State,[],TransId),
2194 set_cbc_state(NewID,[TransId],[root]).
2195
2196
2197 set_cbc_state(NewID,TransIds,His) :-
2198 set_current_state_id(NewID),
2199 reset_op_trace_ids,
2200 maplist(add_to_op_trace_ids,TransIds),
2201 retractall(history(_)),
2202 retractall(forward_history(_)),
2203 assertz(history(His)). %, print(State),nl.
2204
2205 is_constant_binding(SortedCsts,bind(ID,_)) :-
2206 ord_member(ID,SortedCsts).
2207
2208 :- use_module(bsyntaxtree, [get_texpr_ids/2]).
2209 seperate_state_into_const_and_vars(concrete_constants(C),Constants,Variables) :- !,
2210 Constants=C, Variables=[].
2211 seperate_state_into_const_and_vars(State,Constants,Variables) :-
2212 b_get_machine_constants(TCs), get_texpr_ids(TCs,Cs),
2213 sort(Cs,SortedCsts),
2214 include(is_constant_binding(SortedCsts),State,Constants),
2215 Constants \= [],
2216 exclude(is_constant_binding(SortedCsts),State,Variables).
2217
2218
2219
2220 tcltk_constraint_find_static_assertion_violation(TclResult) :-
2221 cbc_constraint_find_static_assertion_violation(Result,[]),
2222 functor(Result,TclResult,_).
2223 cbc_constraint_find_static_assertion_violation(Result,Options) :-
2224 call_cbc_command(cbc_static_assertions_check(State,Options)),
2225 ( State = counterexample_found(CE) ->
2226 Result = counterexample_found,
2227 tcltk_add_cbc_state(CE,static_assertion_check)
2228 ;
2229 Result = State).
2230
2231 /* --------------------------------------------------- */
2232
2233
2234 :- use_module(error_manager,[extract_all_line_col/5]).
2235 :- use_module(probcspsrc(haskell_csp),[extract_span_from_event/4,extract_span_info/2]).
2236
2237 get_source_text_positions(Event,Line,Col,EndLine,EndCol) :-
2238 extract_span_from_action(Event,SPAN),
2239 extract_all_line_col(SPAN,Line,Col,EndLine,EndCol).
2240
2241 extract_span_from_action(Event,Span) :- csp_mode,
2242 extract_span_from_event(Event,Span,_,_).
2243 extract_span_from_action(Event,Pos) :- b_or_z_mode,
2244 get_operation_name(Event,ID),
2245 % TODO: prob_source_profiling_on SOURCE_PROFILING_INFO, add_source_location_hits
2246 b_get_machine_operation(ID,_Res,_TParas,_Body,_OType,Pos).
2247
2248
2249 /* -------------------------------------------------------------------- */
2250
2251 get_current_option_eventtrace(OptionNum,TraceInfo) :-
2252 % the option number starts with 0 (coming from a TK listbox)
2253 current_options(ActionsAndIDs),
2254 nth0(OptionNum,ActionsAndIDs,(Id,_,_,_)),
2255 transition_info(Id,TraceInfo),
2256 transition_info_can_be_shown(TraceInfo),!.
2257
2258 transition_info_can_be_shown(eventtrace(_)).
2259 transition_info_can_be_shown(path(_)).
2260
2261
2262 tcltk_has_eventtrace(OptionNum) :-
2263 get_current_option_eventtrace(OptionNum,_Trace).
2264
2265 tcltk_show_eventtrace(OptionNum,Desc) :-
2266 get_current_option_eventtrace(OptionNum,Trace),
2267 explain_transition_info(Trace,Desc).
2268
2269
2270
2271 /* --------------------------------------------------- */
2272
2273 :- use_module(prob2_interface,[execute_model/5]).
2274
2275 tcltk_execute_model(MaxNrSteps,ExecutedSteps,Result) :-
2276 current_state_id(CurID),
2277 execute_model(CurID,MaxNrSteps,_TransitionInfo,ExecutedSteps,Result).
2278
2279
2280 tcltk_find_shortest_trace_to_current_node(list(StringList)) :-
2281 find_trace_to_current_node(OpL),
2282 translate_events(OpL,StringList).
2283
2284
2285 tcltk_execute_trace_to_current_node :-
2286 current_state_id(CurID),
2287 tcltk_execute_trace_to_node(CurID).
2288
2289 tcltk_execute_trace_to_node(ToID) :- /* can be useful for TestCase Generation */
2290 set_target_id(ToID),
2291 tcltk_execute_trace_from_to_found_predicate(root,_,_).
2292
2293 % execcute longest loop-free trace (no repeated state)
2294 tcltk_execute_longest_trace_from(From) :-
2295 set_longest_trace_target,
2296 tcltk_execute_trace_from_to_found_predicate(From,_,_).
2297
2298 % OpL is list of operation ids, IDList is list of state ids
2299 tcltk_execute_trace_from_to_found_predicate(From,OpL,IDList) :-
2300 debug_println(19,finding_trace_from_to(From)), flush_output(user),
2301 find_shortest_path_from_to_found_predicate(From,OpL,IDList,ToID), !,
2302 (current_state_id(From) -> true ; state_space_reset),
2303 debug_println(9,executing_trace(From,OpL,ToID)), flush_output(user),
2304 execute_id_trace_from_current(ToID,OpL,IDList).
2305
2306
2307 find_trace_to_current_node(Trace) :-
2308 current_state_id(CurID),
2309 find_shortest_path_from_to(root,CurID,L,_),
2310 extract_term_trace_from_transition_ids(L,Trace).
2311
2312 :- use_module(state_space_dijkstra).
2313
2314 find_shortest_trace_to_node(FromID,ToID,OpIDListe,StateIDList) :-
2315 find_shortest_path_from_to(FromID,ToID,OpIDListe,StateIDList).
2316
2317
2318 /* --------------------------------------------------- */
2319
2320
2321
2322 tcltk_goto_a_non_deterministic_node(Msg) :- /* same transition leads to different resulting state */
2323 visited_expression_id(ID),
2324 external_functions:non_det_transition(ID,_OpName,TID1,TID2),
2325 tcltk_execute_trace_to_node(ID),
2326 transition(ID,Op1,TID1,ID1),
2327 transition(ID,_Op2,TID2,ID2),
2328 translate_event_with_src_and_target_id(Op1,ID,ID1,OpStr),
2329 ajoin(['Operation leads to at least two different states (ids ', ID1,', ',ID2,
2330 ') for same arguments: ', OpStr], Msg).
2331
2332 tcltk_goto_a_non_deterministic_output_node(Msg) :- /* same transition leads to different outputs */
2333 visited_expression_id(ID),
2334 external_functions:non_det_output_transition(ID,_OpName,TID1,TID2),
2335 tcltk_execute_trace_to_node(ID),
2336 transition(ID,Op1,TID1,ID1),
2337 transition(ID,Op2,TID2,ID2),
2338 translate_event_with_src_and_target_id(Op1,ID,ID1,OpStr1),
2339 translate_event_with_src_and_target_id(Op2,ID,ID2,OpStr2),
2340 ajoin(['Operation has at least two different results for same arguments: ', OpStr1,
2341 '\n and ',OpStr2], Msg).
2342
2343 dif_ID(ID1,ID2) :- (number(ID1),number(ID2) -> ID2>ID1 ; ID1 \= ID2).
2344
2345 tcltk_goto_a_branching_node :- /* two different events/operations enabled */
2346 transition(ID,X,ID2), get_operation_name(X,NX),
2347 transition(ID,Y,ID3), dif_ID(ID2,ID3), get_operation_name(Y,NY), NX\=NY,
2348 print_message(found_branching_op(ID,NX,NY)),
2349 %tcltk_goto_state(find_branching_node,ID),
2350 tcltk_execute_trace_to_node(ID).
2351
2352 tcltk_goto_a_non_resetable_node :-
2353 find_resetable_nodes,
2354 visited_expression_id(ID),
2355 ID \== root, % root has no incoming transitions and is thus never marked as resetable
2356 \+(resetable_node(ID)),
2357 \+(not_all_transitions_added(ID)), !,
2358 %tcltk_goto_state(find_non_resetable_node,ID).
2359 tcltk_execute_trace_to_node(ID).
2360
2361 :- use_module(bmachine,[b_get_machine_operation_for_animation/4]).
2362 operation_name_covered(OpName) :- operation_name_covered(OpName,_).
2363 operation_name_covered(OpName,Template) :-
2364 b_get_machine_operation_for_animation(OpName,Results,Par,_),
2365 \+ operation_not_yet_covered(OpName),
2366 length(Par,Arity),
2367 functor(Op,OpName,Arity),
2368 (Results\=[] -> Template = '-->'(Op,_) ; Template = Op).
2369
2370 tcltk_goto_event_list_property_violation(Property,EventSelection,list(OperationList)) :-
2371 % first translate Tk EventSelection Number list into Events
2372 sap:get_selected_events(EventSelection,_AllEvents,OperationList),
2373 include(operation_name_covered,OperationList,_,EnabledOpList), % only keep operations that can be enabled anyway
2374 maplist(operation_name_covered,EnabledOpList,TemplateList), % replace by template
2375 debug_println(9,find_property_violation_for_template(Property,TemplateList)),
2376 visited_expression(ID,S), ID \= root, S\= concrete_constants(_),
2377 \+(not_all_transitions_added(ID)),
2378 \+( check_event_list_property(Property,ID,TemplateList) ),
2379 debug_println(9,found_event_list_property_violation(Property,ID)),
2380 tcltk_execute_trace_to_node(ID).
2381
2382 check_event_list_property(relative_deadlock_freedom,ID,TemplateList) :-
2383 relative_deadlock_freedom(ID,TemplateList).
2384 check_event_list_property(valid_controller,ID,TemplateList) :-
2385 is_valid_controller_state(ID,TemplateList).
2386 check_event_list_property(det_controller,ID,TemplateList) :-
2387 is_det_controller_state(ID,TemplateList).
2388
2389 relative_deadlock_freedom(ID,TemplateList) :- member(Template,TemplateList),
2390 transition(ID,Template,_).
2391 is_valid_controller_state(ID,TemplateList) :- % check that exactly one event from TemplateList is enabled
2392 append(_,[LiveEvent|RestTemplate],TemplateList),
2393 transition(ID,LiveEvent,_),!, % we found one enabled event
2394 \+ relative_deadlock_freedom(ID,RestTemplate). % all other events from list must be disabled
2395 is_det_controller_state(ID,TemplateList) :- % check that *at most* one event from TemplateList is enabled
2396 append(_,[LiveEvent|RestTemplate],TemplateList),
2397 transition(ID,LiveEvent,_),!, % we found one enabled event from list
2398 \+ relative_deadlock_freedom(ID,RestTemplate). % all other events from list must be disabled
2399 is_det_controller_state(_,_) :- true. % no event enabled is also ok
2400
2401
2402 tcltk_goto_state_enabling_operation(TclOpName,FromCurrent) :-
2403 adapt_tcl_operation_name(TclOpName,OpName),
2404 operation_name_covered(OpName,Template), % does cater for Event-B any vars
2405 set_found_predicate(ID, transition(ID,Template,_)),
2406 print_message('Computing trace to node'),
2407 (FromCurrent=1
2408 -> current_state_id(FromID) % inefficient: better to do one dijkstra from FromID !
2409 ; FromID = root
2410 ),
2411 tcltk_execute_trace_from_to_found_predicate(FromID,_,_).
2412 % tcltk_goto_state(find_enabled(OpName),ID).
2413
2414
2415 :- use_module(tools_lists,[count_occurences/2]).
2416 % quickly compute which operations have already been covered and which ones not
2417 tcltk_operations_covered_info(list([list(['Operation','Covered'])|OpCov]),list(Occurences),Precise) :-
2418 findall(list([OpName,Cov]),
2419 (specfile:get_possible_event(OpName),
2420 (operation_name_not_yet_covered(OpName)
2421 -> not_yet_covered_info(Precise,OpName,Cov)
2422 ; Cov = 'yes')),OpCov),
2423 (maplist(get_cov,OpCov,Cov2),
2424 count_occurences(Cov2,Occ2),
2425 maplist(construct_list,Occ2,Occurences) -> true ; Occurences=[]).
2426
2427 get_cov(list([_,Cov|_]),Cov).
2428 construct_list(Kind-Nr,list([Kind,Nr])).
2429
2430 :- use_module(cbcsrc(enabling_analysis),[feasible_operation/2]).
2431 not_yet_covered_info(precise,OpName,Cov) :-
2432 feasible_operation(OpName,Res),!, Res=Cov.
2433 not_yet_covered_info(precise,_,R) :- !, R='unknown'.
2434 not_yet_covered_info(_,_,'uncovered').
2435
2436 :- dynamic resetable_node/1.
2437
2438 resetable_node(a).
2439
2440 :- public find_resetable_nodes/0.
2441 :- dynamic find_flag/2.
2442 find_resetable_nodes :-
2443 retractall(find_flag(_,_)),
2444 retractall(resetable_node(_)),
2445 any_transition(root,_,ID), /* add nodes reachable from root */
2446 assertz(find_flag(ID,0)),
2447 fail.
2448 find_resetable_nodes :-
2449 visited_expression(CID,concrete_constants(_C)),
2450 any_transition(CID,_,ID), /* add nodes reachable after a setup_constants */
2451 assertz(find_flag(ID,0)),
2452 fail.
2453 find_resetable_nodes :- find_resetable_nodes_loop,
2454 debug_println(9,'Not resetable:'),
2455 visited_expression_id(ID),
2456 \+(resetable_node(ID)),
2457 debug_println(9,ID),
2458 fail.
2459 find_resetable_nodes :-
2460 debug_println(9,'Done').
2461
2462
2463 find_resetable_nodes_loop :-
2464 retract(find_flag(ID,N)), !, find_resetable_nodes_loop(ID,N).
2465 find_resetable_nodes_loop.
2466
2467 find_resetable_nodes_loop(ID,N) :- N1 is N+1,
2468 assertz(resetable_node(ID)),
2469 any_transition(NewID,_,ID),
2470 \+(resetable_node(NewID)),
2471 \+(find_flag(NewID,_)),
2472 assertz(find_flag(NewID,N1)),
2473 fail.
2474 find_resetable_nodes_loop(_,_) :- find_resetable_nodes_loop.
2475
2476
2477 :- use_module(specfile, [get_current_state_for_b_formula/2]).
2478
2479 tcltk_show_expression_as_dot(VorE,File) :-
2480 parse_machine_expression(VorE,TypedExpr),
2481 tcltk_show_typed_expression_as_dot_graph(TypedExpr,File).
2482 tcltk_show_expression_as_dot(_VorE,File) :-
2483 add_error(tcltk_show_expression_as_dot,'Computing Value Dot Representation Failed for: ',File),
2484 fail.
2485
2486 :- use_module(dotsrc(state_as_dot_graph),[print_cstate_graph/2]).
2487 :- use_module(dotsrc(state_custom_dot_graph),[tcltk_generate_state_custom_dot_graph_for_expr/2, is_valid_custom_dot_graph_record/1]).
2488
2489 tcltk_show_typed_expression_as_dot_graph(TypedExpr,File) :-
2490 is_valid_custom_dot_graph_record(TypedExpr),
2491 !, % use the more powerful custom_dot_graph mechanism
2492 tcltk_generate_state_custom_dot_graph_for_expr(TypedExpr,File).
2493 tcltk_show_typed_expression_as_dot_graph(TypedExpr,File) :-
2494 get_current_state_for_b_formula(TypedExpr,BState),
2495 extend_state_with_probids_and_lets(BState,BState1),
2496 decompose_expression_for_dot(TypedExpr,ExprList,[]), % decompose pairs so that user can provide multiple values/graphs
2497 compute_for_dot(ExprList,BState1,GraphState), % compute value for each sub-component
2498 format('Writing value to DOT file: ~w~n',[File]),
2499 print_cstate_graph(GraphState,File),
2500 format('Finished writing value to DOT file: ~w~n',[File]).
2501
2502
2503 :- use_module(eval_let_store,[extend_typing_scope_for_stored_lets/2]).
2504 :- use_module(bmachine, [b_parse_machine_expression_from_codes_with_prob_ids/2, type_with_errors/4]).
2505 parse_machine_expression(RawAST,TypedExpr) :- compound(RawAST),!, % allow to pass raw AST as well
2506 extend_typing_scope_for_stored_lets([prob_ids(visible),variables,external_library(safe_available_libraries)],Scope),
2507 type_with_errors(RawAST,Scope,Type,TypedExpr),
2508 % TODO: get_stored_let_typing_scope and add values to state returned by get_current_state_for_b_formula
2509 ((Type=pred ; Type=subst)
2510 -> add_error(parse_machine_expression,'Expected expression formula but obtained: ',Type),fail
2511 ; true ).
2512 parse_machine_expression(VorE,TypedExpr) :-
2513 atom_codes(VorE,VorECodes),
2514 b_parse_machine_expression_from_codes_with_prob_ids(VorECodes,TypedExpr).
2515
2516 compute_for_dot([],_,[]).
2517 compute_for_dot([String,TypedExpr|Tail],BState,[bind(Str,Value)|TS]) :-
2518 % allow user to specify labels for graphs ("lbl1", e1, "lbl2", e2, ...)
2519 get_texpr_expr(String,string(Str)),!,
2520 translate:translate_bexpression_with_limit(TypedExpr,100,EStr),
2521 format('Computing value for expression: ~w~n',[EStr]),
2522 b_compute_expression_with_prob_ids(TypedExpr,BState,Value),
2523 compute_for_dot(Tail,BState,TS).
2524 compute_for_dot([TypedExpr|Tail],BState,[bind(Str,Value)|TS]) :-
2525 translate:translate_bexpression_with_limit(TypedExpr,100,Str),
2526 format('Computing value for expression: ~w~n',[Str]),
2527 b_compute_expression_with_prob_ids(TypedExpr,BState,Value),
2528 compute_for_dot(Tail,BState,TS).
2529
2530 :- use_module(bsyntaxtree, [replace_ids_by_exprs/4]).
2531
2532 % decompose_expression_for_dot ensures that
2533 % ("label1",graph1,"lbl2",graph2) or rec(label:graph) is decomposed and we can associate labels with multiple graphs
2534 decompose_expression_for_dot(b(couple(A,B),_,_)) --> !,
2535 decompose_expression_for_dot(A), decompose_expression_for_dot(B).
2536 decompose_expression_for_dot(b(rec(Fields),_,_)) --> !,decompose_fields_for_dot(Fields).
2537 decompose_expression_for_dot(b(let_expression(Ids,Exprs,Body),couple(_,_),_)) --> !,
2538 % this can happen when OPTIMIZE_AST is set to FALSE and the Jupyter kernel adds LETs; lift string out of let
2539 % :dot expr_as_graph ("h",h,"hh",(h;h))
2540 {replace_ids_by_exprs(Body,Ids,Exprs,Body2)},
2541 decompose_expression_for_dot(Body2).
2542 decompose_expression_for_dot(X) --> [X].
2543
2544
2545 decompose_fields_for_dot([]) --> [].
2546 decompose_fields_for_dot([field(Name,Val)|T]) --> [b(string(Name),string,[]),Val], decompose_fields_for_dot(T).
2547
2548 /* ------------------------------------------------------------------ */
2549
2550 % aka Execute by Predicate
2551 tcltk_add_user_executed_operation(TclOpName,CustomPredicate) :-
2552 tcltk_add_user_executed_operation(TclOpName,[],CustomPredicate).
2553
2554 tcltk_add_user_executed_operation(TclOpName,ParameterBindList,RestPreCond) :-
2555 adapt_tcl_operation_name(TclOpName,OpName),
2556 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate),
2557 current_state_id(CurID),
2558 get_computed_preference(debug_time_out,DTO),
2559 time_out_with_enum_warning_one_solution(b_trans_one_solution_with_pred(OpName,CustomPredicate,CurID,_,_,_),
2560 DTO,TimeOutRes),
2561 (is_time_out_result(TimeOutRes)
2562 -> add_warning(execute_by_predicate,'Timeout occured trying to execute operation with predicate: ',TclOpName),fail
2563 ; true).
2564
2565 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate) :-
2566 GenParseErrors=true,
2567 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate,GenParseErrors).
2568 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate,GenParseErrors) :-
2569 ExtraScope=[],
2570 b_parse_machine_operation_pre_post_predicate(RestPreCond,ExtraScope,RestTypedPred,OpName,GenParseErrors),
2571 (ParameterBindList=[] -> CustomPredicate = RestTypedPred
2572 ; get_animation_operation_parameters(OpName,Parameters),
2573 % print(tcltk_add_user_executed_operation(OpName,ParameterBindList,Parameters)),nl,
2574 parse_parameter_values(ParameterBindList,OpName,Parameters,List),
2575 conjunct_predicates([RestTypedPred|List],CustomPredicate)
2576 ).
2577
2578 :- use_module(bmachine,[b_get_machine_operation_for_animation/7]).
2579 get_animation_operation_parameters('$setup_constants',Parameters) :- !,
2580 b_get_machine_operation_typed_parameters('$setup_constants',Parameters).
2581 get_animation_operation_parameters(OpName,FullParameters) :- xtl_mode,!,
2582 xtl_transition_parameters(OpName,ParaNames),
2583 maplist(make_string_id,ParaNames,FullParameters).
2584 get_animation_operation_parameters(OpName,FullParameters) :-
2585 TopLevel=true, % otherwise ANY parameters not added when show_eventb_any_arguments is true
2586 b_get_machine_operation_for_animation(OpName,_Results,Parameters,_Body,_OType,TopLevel,_OpPos),
2587 b_get_operation_non_det_modifies(OpName,NonDetVars), % also allow setting non-deterministically assigned vars
2588 b_get_machine_variables(Vars),
2589 include(non_det_modified(NonDetVars),Vars,ParaVars),
2590 append(ParaVars,Parameters,FullParameters).
2591
2592 make_string_id(ID,b(identifier(ID),string,[])).
2593 non_det_modified(NonDetVars,TID) :- get_texpr_id(TID,ID), ord_member(ID,NonDetVars).
2594
2595 % parse a list of variable names and expressions and turn into equal predicates
2596 % Motivation: this can also deal with Z-style identifiers like in?, ... which cannot be parsed
2597 :- use_module(btypechecker, [unify_types_strict/2, coerce_type/4]).
2598 :- use_module(extrasrc(before_after_predicates),[prime_dollar0_bexpr_for_ids/3]).
2599 :- use_module(probsrc(b_read_write_info), [b_get_read_write/3]).
2600
2601 parse_parameter_values([],_,_,Res) :- !,Res=[].
2602 parse_parameter_values(['='(ParameterID,ExpressionStr)|T],OpName,Parameters,[Pred|PT]) :-
2603 atom_codes(ExpressionStr,Codes),
2604 debug_format(9,'Parsing for parameter ~w : ~w~n',[ParameterID,ExpressionStr]),
2605 !,
2606 b_parse_machine_expression_from_codes_with_prob_ids(Codes,TypedExpr),
2607 get_texpr_type(TypedExpr,Type),
2608 TID = b(identifier(ParameterID),ExpectedType,[]),
2609 % if we reference a modified variable in the expression, we replace id by id$0 :
2610 (b_or_z_mode -> b_get_read_write(OpName,_,Written) ; Written=[]),
2611 prime_dollar0_bexpr_for_ids(TypedExpr,Written,PrimedTypedExpr0),
2612 (xtl_mode
2613 -> (Type=string -> PrimedTypedExpr1=PrimedTypedExpr0
2614 ; coerce_type(Type,string,PrimedTypedExpr0,PrimedTypedExpr1)),
2615 PrimedTypedExpr=b(external_function_call('STRING_TO_TERM',[PrimedTypedExpr1]),string,[]),
2616 Type2=string
2617 ; PrimedTypedExpr=PrimedTypedExpr0, Type2=Type),
2618 (member(b(identifier(ParameterID),ExpectedType,_),Parameters)
2619 -> (unify_types_strict(Type2,ExpectedType)
2620 -> safe_create_texpr(equal(TID,PrimedTypedExpr),pred,Pred),
2621 parse_parameter_values(T,OpName,Parameters,PT)
2622 ; coerce_type(Type2,ExpectedType,PrimedTypedExpr,NewTypedExpr)
2623 -> safe_create_texpr(equal(TID,NewTypedExpr),pred,Pred),
2624 add_message(parse_parameter_values,'Coercion of provided parameter value: ',NewTypedExpr),
2625 parse_parameter_values(T,OpName,Parameters,PT)
2626 ;
2627 pretty_type(Type2,String1), pretty_type(ExpectedType,String2),
2628 ajoin(['Value for parameter ',ParameterID,' has unexpected type ',String1,', expected: '],Msg),
2629 add_error(parse_parameter_values,Msg,String2),
2630 fail
2631 )
2632 ; add_error(parse_parameter_values,'Unknown operation parameter: ',ParameterID),
2633 fail).
2634 parse_parameter_values(PB,OpName,P,_) :-
2635 add_internal_error('Illegal parameter binding: ',parse_parameter_values(PB,OpName,P,_)),fail.
2636
2637
2638 % just as above but with typed predicate
2639 tcltk_add_user_executed_operation_typed(OpName,Operation,TypedCustomPredicate,NewID) :-
2640 current_state_id(CurID),
2641 tcltk_add_user_executed_operation_typed(OpName,CurID,Operation,TypedCustomPredicate,_,NewID).
2642 tcltk_add_user_executed_operation_typed(OpName,CurID,Operation,TypedCustomPredicate,TransID,NewID) :-
2643 b_trans_one_solution_with_pred(OpName,TypedCustomPredicate,CurID,Operation,TransID,NewID).
2644
2645 % allows the user to arbitrarily change variable values
2646 % Attention: this can of course violate the invariant
2647 tcltk_add_user_modify_variable_transition(VarID,ValueStr) :-
2648 current_state_id(CurID),
2649 tcltk_add_user_modify_variable_transition(CurID,VarID,ValueStr,_).
2650 tcltk_add_user_modify_variable_transition(CurID,VarID,ValueStr,NewID) :-
2651 get_id_type(VarID,Kind,Type),!,
2652 format('Trying to update ~w ~w to new value: ~w~n',[Kind,VarID,ValueStr]),
2653 eval_string_in_cur_state(ValueStr,ValTyped,Value),
2654 get_texpr_type(ValTyped,ValType),
2655 check_types(Kind,VarID,Type,ValType),
2656 visited_expression(CurID,CurState),
2657 update_variable(CurState,VarID,Value,NewState),
2658 Residue=[], TransInfo=[],
2659 (CurState = concrete_constants(_)
2660 -> add_error(tcltk_add_user_modify_variable_transition,'Initialise machine first before modifying values')
2661 ; Operation = '$modify'(string(VarID),string(ValueStr)),
2662 add_trans_id_with_infos(CurID,[],Operation,NewState,Residue,NewID,TransInfo,_),
2663 tcltk_goto_state(Operation,NewID)
2664 ).
2665
2666 check_types(_,_,Type,ValType) :-
2667 unify_types_strict(Type,ValType),!.
2668 check_types(Kind,VarID,Type,ValType) :-
2669 pretty_type(ValType,VTS), pretty_type(Type,TS),
2670 ajoin(['Unexpected type of value (', VTS, ' instead of ',TS,') for ',Kind,' :'],Msg),
2671 add_error(check_types,Msg,VarID),
2672 fail.
2673
2674 :- use_module(bmachine,[b_is_variable/2, b_is_constant/2]).
2675 get_id_type(ID,variable,Type) :- b_is_variable(ID,Type).
2676 get_id_type(ID,constant,Type) :- b_is_constant(ID,Type).
2677 % update variable value or constant value in concrete_constants state
2678 update_variable([],VarID,_,[]) :- add_error(update_variable,'Identifier does not exist in state:',VarID),fail.
2679 update_variable([bind(VarID,_)|T],VarID,NewVal,Res) :- !, Res = [bind(VarID,NewVal)|T].
2680 update_variable([H|T],VarID,NewVal,[H|UT]) :- !, update_variable(T,VarID,NewVal,UT).
2681 update_variable(const_and_vars(ConstID,Old),VarID,NewVal,const_and_vars(NewConstID,Old)) :-
2682 b_is_constant(VarID,_),!,
2683 visited_expression(ConstID,ConstState),
2684 update_variable(ConstState,VarID,NewVal,NewConstState),
2685 add_new_constants_state_after_update(NewConstState,NewConstID).
2686 update_variable(const_and_vars(ConstID,Old),VarID,NewVal,const_and_vars(ConstID,New)) :- !,
2687 update_variable(Old,VarID,NewVal,New). % TODO: allow updating constants
2688 update_variable(concrete_constants(Old),VarID,NewVal,concrete_constants(New)) :- !,
2689 update_variable(Old,VarID,NewVal,New). % here we allow updating constants
2690
2691 add_new_constants_state_after_update(NewConstState,NewConstID) :-
2692 get_id_of_node_and_add_if_required(NewConstState,NewConstID,Exists,root,'$setup_constants',[]),
2693 % Note: we add the (potentially new) constants state node; but there could be no direct connection
2694 % in the state space from this constants state to the update state const_and_vars(NewConstID,Old)
2695 (Exists=exists -> true
2696 ; tcltk_add_new_transition_transid(root,'$partial_setup_constants',NewConstID,NewConstState,[],_TransId1)).
2697
2698 % execute operation by predicate finding just one solution
2699 b_trans_one_solution_with_pred(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID) :-
2700 catch(
2701 (
2702 call_cleanup(b_trans_one_solution_with_pred2(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID),
2703 bmachine:reset_temp_predicate)
2704 ),
2705 enumeration_warning(Cause,_,_,_,_),
2706 (
2707 add_warning(b_trans_one_solution_with_pred,
2708 'Enumeration warning prevented finding solution for operation: ',Cause),
2709 fail
2710 )
2711 ).
2712
2713 % find one solution from current state using OpName and respecting temp_predicate
2714 % Note: the predicate is evaluated in post-state, use $0 to access values in current state
2715 b_trans_one_solution_with_pred2(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID) :-
2716 (b_or_z_mode -> b_top_level_operation(OpName) ; true),
2717 !,
2718 visited_expression(CurID,InState),
2719 set_error_context(operation(OpName,CurID)),
2720 set_context_state(CurID,b_trans_one_solution_with_pred),
2721 debug_format(19,'Executing ~w in state ~w by predicate~n',[OpName,CurID]),
2722 call_cleanup(execute_operation_by_predicate_in_state(InState,OpName,TypedCustomPredicate,Operation,NewState,TransInfo),
2723 (clear_context_state,clear_error_context)),
2724 !,
2725 debug_format(19,'Executed by predicate: ~w~n',[OpName]),
2726 add_trans_id_infos(CurID,Operation,NewState,NewID,TransId,TransInfo),
2727 tcltk_goto_state(Operation,NewID).
2728 b_trans_one_solution_with_pred2(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID) :-
2729 assert_temp_predicate_with_prob_def_set_elements(TypedCustomPredicate),
2730 visited_expression(CurID,InState),
2731 set_error_context(operation(OpName,CurID)),
2732 set_context_state(CurID,b_trans_one_solution_with_pred),
2733 temporary_set_preference(maxNrOfEnablingsPerOperation,1,Max),
2734 temporary_set_preference(maxNrOfInitialisations,1,MaxI),
2735 start_ms_timer(Timer),
2736 call_cleanup((specfile:b_trans(InState,OpName,Operation,NewState,TransInfo) -> true),
2737 (stop_ms_timer(Timer),
2738 reset_temporary_preference(maxNrOfEnablingsPerOperation,Max),
2739 reset_temporary_preference(maxNrOfInitialisations,MaxI),
2740 clear_context_state,clear_error_context)
2741 ),
2742 debug_println(9,found_solution(NewState)),nl,
2743 % now add a transition to the state space:
2744 Residue=[],
2745 add_trans_id_with_infos(CurID,[],Operation,NewState,Residue,NewID,TransInfo,TransId),
2746 tcltk_goto_state(Operation,NewID).
2747
2748 :- use_module(b_global_sets,[inline_prob_deferred_set_elements_into_bexpr/2]).
2749 assert_temp_predicate_with_prob_def_set_elements(CustomPredicate) :-
2750 inline_prob_deferred_set_elements_into_bexpr(CustomPredicate,CompiledPred),
2751 bmachine:assert_temp_typed_predicate(CompiledPred).
2752
2753
2754 % allow user to execute any statement
2755 % TO DO: catch operation_calls and route them differently
2756 % translate operation_call arguments into predicate and call tcltk_add_user_executed_operation_typed(OpName,Operation,TypedCustomPredicate,NewID)
2757 tcltk_add_user_executed_statement(Statement,Updates,NewID) :-
2758 current_expression(CurID,InState),
2759 state_corresponds_to_initialised_b_machine(InState,BState),
2760 set_context_state(CurID,tcltk_add_user_executed_statement),
2761 %start_ms_timer(Timer),
2762 call_cleanup((tcltk_interface:b_full_execute_top_level_statement_with_probids(Statement,BState,Updates,NewState)->true),
2763 clear_context_state),
2764 % TO DO: do we need to catch enumeration warnings ?
2765 %stop_ms_timer(Timer),
2766 Residue=[], TransInfo = [],
2767 debug_println(4,executed(Updates,NewState)),
2768 compute_all_transitions_if_necessary(CurID), % first ensure we have already computed outgoing transitions as usual, so that we can detect if a new state is added
2769 (get_id_of_node_and_add_if_required(NewState,NewID,Exists,CurID,'$unknown_operation',[]),
2770 Exists=exists,
2771 transition(CurID,Action,TransId,NewID)
2772 -> debug_println(4,transition_exists_already(Action,TransId))
2773 ; translate:translate_substitution(Statement,OpLabel),
2774 Action = '$USER'(OpLabel),
2775 add_trans_id_with_infos(CurID,[],Action,NewState,Residue,NewID,TransInfo,_),
2776 format('Added new user-initiated transition to ~w via: ~w~n',[NewID,OpLabel])
2777 ),
2778 tcltk_goto_state(Action,NewID). % use the action of the transition, so that it is added to the history
2779
2780 :- use_module(eval_let_store,[extend_state_with_probids_and_lets/2]).
2781 :- use_module(kernel_waitflags,[init_wait_flags_with_call_stack/2, ground_wait_flags/1]).
2782 %% allows one to execute any statement (not just operations).
2783 b_full_execute_top_level_statement_with_probids(Body,InState,Updates,NewState) :-
2784 extend_state_with_probids_and_lets(InState,InState1),
2785 init_wait_flags_with_call_stack(WF,[prob_command_context(user_executed_statement,unknown)]),
2786 b_execute_top_level_statement(Body,[],InState1,Updates,WF,_Path1,output_not_required),
2787 ground_wait_flags(WF),
2788 store:store_updates_and_normalise(Updates,InState,NewState).
2789
2790 % --------------------------------------------------------------------------------------
2791
2792
2793 :- use_module(bmachine).
2794 :- use_module(specfile).
2795 :- use_module(tools).
2796 :- use_module(library(lists)).
2797 :- use_module(store).
2798 :- use_module(self_check).
2799 :- use_module(b_global_sets).
2800 :- use_module(translate).
2801
2802
2803 /* --------------------------------------------------------- */
2804 /* --------------------------------------------------------- */
2805
2806
2807 /* ----------------------------------*/
2808 /* b_analyse_conjunction */
2809 /* ----------------------------------*/
2810
2811
2812 /* provide list of possible options for analysis */
2813 tcltk_analyse_option(invariant,'INVARIANT') :- b_or_z_mode.
2814 tcltk_analyse_option(properties,S) :- b_or_z_mode,
2815 get_specification_description(properties,S).
2816 tcltk_analyse_option(assertions,S) :- (b_or_z_mode ; csp_mode),
2817 get_specification_description(assertions,S).
2818 tcltk_analyse_option(deadlock,'DEADLOCKED') :- b_or_z_mode.
2819
2820
2821 :- use_module(predicate_evaluator).
2822 /* perform the various analysis */
2823 tcltk_analyse(Mode,Type,ListWithResults,Total,False,Unknown) :-
2824 (Mode == unicode
2825 -> set_unicode_mode,
2826 call_cleanup(tcltk_analyse2(Type,ListWithResults,Summary),unset_unicode_mode)
2827 ; tcltk_analyse2(Type,ListWithResults,Summary)),
2828 (member(total/Total,Summary) -> true ; Total=0),
2829 (member(false/False,Summary) -> true ; False=0),
2830 (member(unknown/Unknown,Summary) -> true ; Unknown=0).
2831 tcltk_analyse2(invariant,L,Summary) :- !,tcltk_analyse_invariant(L,Summary).
2832 tcltk_analyse2(properties,L,Summary) :- !,tcltk_analyse_properties(L,Summary).
2833 tcltk_analyse2(assertions,L,Summary) :- !,tcltk_analyse_assertions(L,Summary).
2834 tcltk_analyse2(deadlock,L,Summary) :- !,tcltk_analyse_deadlock(L,Summary).
2835 tcltk_analyse2(X,L,Summary) :- add_error(tcltk_analyse, 'Unknown type of formula: ', X),
2836 L=[], Summary=[].
2837
2838
2839 /* --------------------------------- */
2840
2841 tcltk_show_current_state(TransBState) :-
2842 current_b_expression(B),
2843 translate_bstate(B,TransBState).
2844
2845
2846 tcltk_show_typing_of_variables_and_constants(list([Header|List])) :-
2847 Header = list(['ID','Type','card','Usage','Info']),
2848 b_get_machine_variables(TypedVarList),
2849 convert_typed_varlist(TypedVarList,VarList,Types),
2850 generate_typing_list(VarList,Types,VList,VarCard),
2851 length(VarList,NrVars),
2852 VarHeader = list(['VARIABLES',NrVars,VarCard,'-','-']),
2853 b_get_machine_all_constants(TypedCstList),
2854 convert_typed_varlist(TypedCstList,CVarList,CTypes),
2855 find_non_det_constants,
2856 generate_typing_list(CVarList,CTypes,CList,CCard),
2857 ( CList = []
2858 -> List = [VarHeader|VList]
2859 ; length(CVarList,NrCsts),
2860 CstHeader = list(['CONSTANTS',NrCsts,CCard,'-','-']),
2861 append([CstHeader|CList],[VarHeader|VList],List)
2862 ),!.
2863 tcltk_show_typing_of_variables_and_constants(list(['TYPE ERROR in MACHINE'])).
2864
2865
2866 %%% Used to get the constant values for the currently loaded B machine in form of a B predicate.
2867 %%% In case that the constants in the model has not been set up then all possible constants'
2868 %%% evaluations will be provided in form of a predicate in Disjunctive Normal Form.
2869 %%% Predicate used for setting up constants when model checking with TLC. (TLA)
2870
2871 tcltk_get_constants_predicate(Pred) :-
2872 tcltk_get_constants_predicate(root,Pred,_PredComplete).
2873 tcltk_get_constants_predicate(CurID,Pred,PredComplete) :-
2874 (CurID=root
2875 -> get_constants_as_disjoint_predicate(Pred),
2876 (max_reached_or_timeout_for_node(root) -> PredComplete = incomplete ; PredComplete = complete)
2877 ; PredComplete=complete,
2878 prob2_interface:get_state(CurID,EState),
2879 filter_constants_bindings(EState,X), % this will only get current constants values
2880 translate_bstate_to_pred(X,Pred)
2881 ).
2882
2883 get_constants_as_disjoint_predicate(Pred) :-
2884 findall(R,get_set_up_constants_solution(R),PredList),
2885 add_or_between_constant_predicates(PredList,Pred).
2886
2887 %get_a_part_of_the_found_solutions(L,N,Part,PredComplete) :-
2888 % length(L,Length),
2889 % (N>=Length
2890 % -> Part=L, PredComplete=complete
2891 % ; sublist(L,Part,_B,N,_A), PredComplete=incomplete
2892 % ).
2893
2894 :- assert_must_succeed((findall(int(I),between:between(1,100000,I),L), custom_explicit_sets:convert_to_avl(L,AVL),
2895 preferences:get_preference(expand_avl_upto,V0),
2896 timeout:time_out(tcltk_interface:translate_bstate_to_pred([bind(x,AVL)],_),5,_), % fully expanding AVL times out
2897 preferences:get_preference(expand_avl_upto,V1), V0==V1)). % preference restored also after a time-out
2898 translate_bstate_to_pred(State,P) :-
2899 temporary_set_preference(expand_avl_upto,-1,CHNG2),
2900 % call_cleanup: also restore the preference upon failure, time-out or other exceptions
2901 call_cleanup(once(translate: translate_bstate(State,P)),
2902 reset_temporary_preference(expand_avl_upto,CHNG2)).
2903
2904 get_set_up_constants_solution(R) :-
2905 compute_transitions_if_necessary(root),
2906 %\+ max_reached_or_timeout_for_node(root),!, % then lookup constants rather than computing them
2907 transition(root,_,Dst),
2908 visited_expression(Dst,concrete_constants(X)),
2909 translate_bstate_to_pred(X,R).
2910 %get_set_up_constants_solution(R) :-
2911 % b_interpreter: b_set_up_concrete_constants(X,_),
2912 % translate:translate_bstate(X,R).
2913
2914 add_or_between_constant_predicates([],'1=1').
2915 add_or_between_constant_predicates(L,Res) :-
2916 tools: ajoin_with_sep(L,' or ',Res).
2917
2918 filter_constants_bindings(EState,R) :-
2919 b_get_machine_all_constants(C),
2920 convert_typed_varlist(C,CVarList,_CTypes),
2921 filter_constants_bindings1(EState,CVarList,R).
2922
2923 filter_constants_bindings1([],_,[]).
2924 filter_constants_bindings1([bind(Ident,Val)|T],CVarList,Res) :-
2925 (member(Ident,CVarList) -> Res = [bind(Ident,Val)|Rest]; Res = Rest),
2926 filter_constants_bindings1(T,CVarList,Rest).
2927
2928 convert_typed_varlist([],[],[]).
2929 convert_typed_varlist([b(identifier(ID),Type,_)|T],[ID|IT],[Type|TT]) :-
2930 %print(ID), print(' : '), print(Type),nl,
2931 % db : set(couple(global(Name),global(Code))) a : set(integer) boolean
2932 convert_typed_varlist(T,IT,TT).
2933 %--------------------------------------
2934
2935
2936 :- use_module(symsrc(symmetry_marker),[type_allows_for_precise_marker/1]).
2937 :- use_module(bmachine,[b_is_unused_constant/1]).
2938 :- use_module(library(codesio),[format_to_codes/3]).
2939 :- use_module(kernel_card_arithmetic,[safe_mul/3]).
2940 generate_typing_list([],[],[],1).
2941 generate_typing_list([Var|VT],[BasicType|TT],[Translation|Rest],TotCard) :-
2942 pretty_type(BasicType,PrettyType),
2943 (kernel_objects:max_cardinality(BasicType,Card) -> true ; Card='??'),
2944 (b_get_constant_represented_inside_global_set(Var,BasicType)
2945 -> Imp='(treated as enumerated) '
2946 ; (preference(symmetry_mode,hash),
2947 \+type_allows_for_precise_marker(BasicType))
2948 -> Imp = '(IMPRECISE for HASH) '
2949 ; Imp = ''
2950 ),
2951 (non_det_constant(Var)
2952 -> atom_concat(Imp,'[multiple solutions in SETUP_CONSTANTS]',Info)
2953 ; Info = Imp),
2954 (b_is_unused_constant(Var) -> Unused='unused' ; Unused=''),
2955 % translate:translate_bexpression(b(member(identifier(Var),BasicType),pred,[]),Translation),
2956 Translation = list([Var,PrettyType,Card,Unused,Info]),
2957 generate_typing_list(VT,TT,Rest,RestCard),
2958 safe_mul(RestCard,Card,TotCard).
2959
2960 :- use_module(symsrc(symmetry_marker),[hash_model_checking_imprecise/2]).
2961 :- use_module(translate,[pretty_type/2]).
2962
2963 tcltk_hash_model_checking_imprecise :-
2964 get_preference(symmetry_mode,hash),
2965 hash_model_checking_imprecise(ID,BasicType),!,
2966 print(' * Note: Hashing may be imprecise for: '),
2967 print(ID), print(' : '),translate:pretty_type(BasicType,S),print(S), print(' !'),nl.
2968
2969
2970 /* find constants which are assigned multiple values */
2971 :- dynamic non_det_constant/1.
2972 find_non_det_constants :-
2973 retractall(non_det_constant(_)),
2974 findall(Csts,visited_expression(_,concrete_constants(Csts),_),CL),
2975 (CL=[Valuation1|O],O=[_|_] -> find_non_det_constants1(Valuation1,O)
2976 ; true /* 0 or 1 valuation only */
2977 ).
2978
2979 find_non_det_constants1([],_).
2980 find_non_det_constants1([bind(C,Value)|T],Other) :- check_cst(Other, C, Value, PeeledOther),
2981 find_non_det_constants1(T,PeeledOther).
2982
2983 check_cst([],_,_,[]).
2984 check_cst([ [bind(C,OtherVal)|T1] | TT], C, Value, [ T1 | PTT]) :-
2985 (Value=OtherVal -> check_cst(TT,C,Value,PTT)
2986 ; assertz(non_det_constant(C)), peel2(TT,PTT)).
2987 peel2([],[]).
2988 peel2([ [_|T1] | TT], [ T1 | PTT]) :- peel2(TT,PTT).
2989
2990
2991 /* --------------------------------- */
2992
2993
2994 /* --------------------------------- */
2995
2996 %%
2997 % Visualize Invariant...
2998 %
2999 % Siehe bvisual.pl
3000
3001 :- use_module(dotsrc(bvisual),[get_tree_from_expr/4, write_dot_graph_to_file/2]).
3002
3003
3004 generate_dot_from_invariant(FileName):-
3005 bmachine:b_get_invariant_from_machine(BExpr),
3006 write_dot_file_for_pred_expr(BExpr,FileName).
3007
3008
3009 :- use_module(b_operation_guards,[get_quantified_operation_enabling_condition/5]).
3010 generate_dot_from_operation(TclOpName,FileName) :-
3011 adapt_tcl_operation_name(TclOpName,OpName),
3012 Simplify=false,
3013 get_quantified_operation_enabling_condition(OpName, BExpr, _BecomesSuchVars, _Precise, Simplify),
3014 write_dot_file_for_pred_expr(BExpr,FileName).
3015 %generate_tree_from_boolean_expression(BExpr, Tree,BecomesSuchVars),
3016 %write_dot_graph_to_file(Tree,FileName).
3017
3018 % a version with additional parameters and additional pre condition / guard predicate
3019 generate_dot_from_operation_with_params(TclOpName,ParameterBindList,RestPreCond, FileName) :-
3020 adapt_tcl_operation_name(TclOpName,OpName),
3021 Simplify=false,
3022 get_quantified_operation_enabling_condition(OpName, BExpr, BecomesSuchVars,_Precise,Simplify),
3023 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate),
3024 insert_custom_predicate_into_guard(BExpr,CustomPredicate,FullPred),
3025 %translate:nested_print_bexpr(FullPred),nl,
3026 % TODO: probably allow all variables to be primed in CustomPredicate:
3027 b_ast_cleanup:annotate_becomes_such_vars(BecomesSuchVars,CustomPredicate,BSV2),
3028 write_dot_file_for_pred_expr(FullPred,FileName,BSV2).
3029
3030 insert_custom_predicate_into_guard(b(exists(Para,Body),pred,Info),Pred,Res) :- !,
3031 Res = b(exists(Para,BodyRes),pred,Info), % TODO: update wd infos
3032 insert_custom_predicate_into_guard(Body,Pred,BodyRes).
3033 insert_custom_predicate_into_guard(Guard,CustomPred,FullPred) :-
3034 % put CustomPred first so that bvisual prioritises solutions coming from user values/predicate
3035 % TODO: we could try and force equalities in CustomPred before calling bvisual
3036 conjunct_predicates([CustomPred,Guard],FullPred).
3037
3038 :- use_module(bmachine, [
3039 b_get_properties_from_machine/1,
3040 b_get_machine_constants/1,
3041 b_machine_has_constants_or_properties/0 ]).
3042 :- use_module(bsyntaxtree,[create_or_merge_exists/3]).
3043 get_properties(BExpr,CreateExists):-
3044 b_get_properties_from_machine(Condition),
3045 ( (CreateExists=true,b_machine_has_constants_or_properties) ->
3046 b_get_machine_constants(IDs),
3047 create_or_merge_exists(IDs, Condition, BExpr)
3048 ;
3049 BExpr = Condition
3050 ).
3051
3052 generate_dot_from_properties(FileName) :-
3053 (current_state_corresponds_to_fully_setup_b_machine -> CreateExists=false; CreateExists=true),
3054 get_properties(BExpr,CreateExists),
3055 write_dot_file_for_pred_expr(BExpr,FileName).
3056
3057 :- use_module(bsyntaxtree,[conjunct_predicates/2]).
3058
3059 generate_dot_from_assertions(FileName) :-
3060 (current_state_corresponds_to_setup_constants_b_machine,
3061 bmachine:b_get_dynamic_assertions_from_machine(BExpr), BExpr \=[]
3062 -> true
3063 ; bmachine:b_get_static_assertions_from_machine(BExpr)
3064 ),
3065 conjunct_predicates(BExpr,BE),
3066 write_dot_file_for_pred_expr(BE,FileName).
3067
3068 generate_dot_from_goal(FileName) :-
3069 b_get_machine_goal(BExpr),!,
3070 write_dot_file_for_pred_expr(BExpr,FileName,all_primed_vars).
3071 generate_dot_from_goal(FileName) :-
3072 write_dot_file_for_pred_expr_and_state(b(string('No GOAL DEFINITION available'),string,[]),[],[],FileName).
3073
3074 generate_dot_from_deadlock_po(FileName) :-
3075 b_state_model_check:get_unsorted_all_guards_false_pred(BExpr),
3076 %print('% CHECKING: '),translate_bexpression(BExpr,PT), print(PT),nl,
3077 write_dot_file_for_pred_expr(BExpr,FileName). % we do not check it is a predicate anymore
3078
3079
3080 generate_dot_from_formula(Pred,FileName) :-
3081 debug_format(19,'Parsing formula ~w~n',[Pred]),
3082 parse_machine_formula(Pred,TypedExpr),
3083 debug_format(19,'Writing dot formula ~w~n',[Pred]),
3084 write_dot_file_for_pred_expr(TypedExpr,FileName,all_primed_vars).
3085
3086
3087 :- use_module(bmachine, [b_parse_machine_formula/3, type_with_errors/4, get_primed_machine_variables/1]).
3088 parse_machine_formula(RawAST,TypedPred) :- compound(RawAST),!, % allow to pass raw AST as well
3089 get_primed_machine_variables(PV),
3090 type_with_errors(RawAST,[prob_ids(visible),identifier(PV),variables],_Type,TypedPred).
3091 parse_machine_formula(PredStr,TypedExpr) :-
3092 get_primed_machine_variables(PV),
3093 b_parse_machine_formula(PredStr,[prob_ids(visible),identifier(PV),variables],TypedExpr).
3094
3095
3096 write_dot_file_for_pred_expr(BExpr,FileName) :-
3097 write_dot_file_for_pred_expr(BExpr,FileName,[]).
3098 write_dot_file_for_pred_expr(BExpr,FileName,BecomesSuchVars) :-
3099 generate_tree_in_cur_state(BExpr, Tree,BecomesSuchVars),
3100 printsilent('% Writing to: '), printsilent(FileName),nls,
3101 write_dot_graph_to_file(Tree,FileName).
3102 write_dot_file_for_pred_expr_and_state(BExpr, LocalState, State,FileName) :-
3103 get_tree_from_expr(Tree, BExpr, LocalState, State),
3104 printsilent('% Writing to: '), printsilent(FileName),nls,
3105 write_dot_graph_to_file(Tree,FileName).
3106
3107 :- use_module(probsrc(state_space),[get_current_predecessor_state_id/1]).
3108 :- use_module(probsrc(specfile),[extract_variables_from_state_as_primed/2]).
3109
3110 generate_tree_in_cur_state(BExpr,Tree,all_primed_vars) :-
3111 (get_current_predecessor_state_id(PredID),
3112 visited_expression(PredID,SrcState),
3113 extract_variables_from_state_as_primed(SrcState,PrimedVarBindings)
3114 -> true
3115 ; PrimedVarBindings=[]
3116 ),
3117 get_current_state_for_b_formula(BExpr,CurState0),
3118 extend_state_with_probids_and_lets(CurState0,CurState1),
3119 append(PrimedVarBindings,CurState1,CurState),
3120 get_tree_from_expr(Tree, BExpr, [], CurState).
3121 generate_tree_in_cur_state(BExpr,Tree,BecomesSuchVars) :-
3122 get_current_state_for_b_formula(BExpr,CurState0),
3123 extend_state_with_probids_and_lets(CurState0,CurState1),
3124 % print(cur(CurState1)),nl,
3125 insert_before_substitution_variables(BecomesSuchVars,[],CurState1,CurState1,CurState),
3126 !,
3127 get_tree_from_expr(Tree, BExpr, [], CurState).
3128
3129 % generate a dot tree representation for a value; mostly useful for symbolic values
3130 write_dot_file_for_value_as_tree(Value,FileName) :-
3131 transform_value_to_expr(Value,BExpr),
3132 temporary_set_preference(formula_tree_minimal_timeout,5,Prev1),
3133 temporary_set_preference(formula_tree_maximal_timeout,30,Prev2),
3134 call_cleanup(generate_tree_in_cur_state(BExpr, Tree,[]),
3135 (reset_temporary_preference(formula_tree_minimal_timeout,Prev1),
3136 reset_temporary_preference(formula_tree_maximal_timeout,Prev2))),
3137 printsilent('% Writing to: '), printsilent(FileName),nls,
3138 write_dot_graph_to_file(Tree,FileName).
3139
3140 :- use_module(probsrc(bsyntaxtree),[create_typed_ids/3]).
3141 :- use_module(library(lists),[maplist/4]).
3142 transform_value_to_expr(closure(P,T,B),E) :-
3143 create_typed_ids(P,T,Parameters),!,
3144 E=b(comprehension_set(Parameters,B),set(any),[]). % TO DO: we could create typing
3145 transform_value_to_expr(Val,b(value(Val),any,[])).
3146
3147 :- use_module(tools,[maplist5/5]).
3148 tcltk_bv_get_tops(Tops) :-
3149 bv_get_top_level(Tops).
3150 tcltk_bv_get_structure(Id,Label,list(Subs)) :-
3151 bv_expand_formula(Id,Label,Subs).
3152 tcltk_bv_is_leaf(Id,Label) :-
3153 bv_expand_formula(Id,Label,[]).
3154 tcltk_bv_get_values(Ids,list(RTexts),list(Tags)) :-
3155 current_state_id(StateId),
3156 bv_get_values(Ids,StateId,Values),
3157 maplist5(tcltk_interface:retrieve_tag_adapted_text_for_id,Ids,Values,Tags,RTexts).
3158 tcltk_bv_get_value(Id,RText,Tag) :-
3159 tcltk_bv_get_values([Id],list([RText]),list([Tag])).
3160 tcltk_bv_show_formula_as_dot_tree(Id,File) :-
3161 bv_get_stored_formula_expr(Id,TExpr),
3162 write_dot_file_for_pred_expr(TExpr,File).
3163 tcltk_bv_get_pp_formula_string(Id,PPFormula) :-
3164 bv_get_stored_formula_expr(Id,TExpr),
3165 translate:translate_bexpression(TExpr,PPFormula).
3166
3167 tcltk_bv_show_formula_as_dot_graph(Id,File) :-
3168 bv_get_stored_formula_expr(Id,TExpr),
3169 get_texpr_type(TExpr,Type),
3170 Type \= pred, Type \= subst,
3171 % tcltk_show_typed_expression_as_dot_graph decomposes expressions and shows value as graph: could be useful for pre-configured DEFINITIONS
3172 tcltk_show_typed_expression_as_dot_graph(TExpr,File).
3173
3174 tcltk_bv_show_value_as_dot_tree(Id,File) :- % useful for symbolic values
3175 current_state_id(StateId),
3176 bv_get_btvalue(Id,StateId,_E,Value),
3177 write_dot_file_for_value_as_tree(Value,File).
3178
3179 % a variation of tcltk_bv_show_value_as_dot_tree without dependence on bvisual2
3180 tcltk_show_identifier_value_as_dot_tree(RawId,File) :- % this also works if bvisual2 is not set up and entry active
3181 get_identifier(RawId,Id),
3182 current_expression(_ID,CurState),
3183 expand_const_and_vars_to_full_store(CurState,EState),
3184 (EState=[] -> add_error(tcltk_show_identifier_value_as_dot_tree,'Initialise machine first, cannot retrieve value for identifier:',Id)
3185 ; lookup_value_for_existing_id(Id,EState,Value)
3186 -> write_dot_file_for_value_as_tree(Value,File)
3187 ; add_error(tcltk_show_identifier_value_as_dot_tree,'Cannot retrieve value for identifier:',Id)).
3188
3189 get_identifier(AtomicID,Res) :- atom(AtomicID), valid_id(AtomicID), !,Res=AtomicID.
3190 get_identifier(identifier(_,ID),Res) :- valid_id(ID),!, Res=ID. % raw ID from prob2_interface
3191 get_identifier(RawFormula,_) :-
3192 add_error(tcltk_show_identifier_value_as_dot_tree,'Please provide valid identifier of constant or variable:',RawFormula),
3193 fail.
3194 valid_id(ID) :- b_is_variable(ID).
3195 valid_id(ID) :- b_is_constant(ID).
3196
3197 retrieve_tag_adapted_text_for_id(Id,Value,Tag,RText) :-
3198 retrieve_tag_text_for_id(Id,Value,Tag,Text),
3199 (Text = '[]' -> RText = '[ ]' ; RText=Text). % for some reason the empty sequence translation [] gets transformed into '' by the tcltk library
3200
3201 retrieve_tag_text_for_id(Id,Value,FullTag,Text) :-
3202 retrieve_tag_text(Value,Tag,Text),
3203 (bv_is_explanation_node(Id) -> convert_explain_tag(Tag,FullTag) ; FullTag=Tag).
3204 retrieve_tag_text(i, inac, '').
3205 retrieve_tag_text(e(Text), error, Text).
3206 retrieve_tag_text(v(Text), value, Text).
3207 retrieve_tag_text(p(true), ptrue, true).
3208 retrieve_tag_text(p(false),pfalse, false).
3209 retrieve_tag_text(bv_info(Text), inac, Text).
3210
3211
3212 tcltk_bv_get_unlimited_value(Id,Text,Tag) :-
3213 current_state_id(StateId),
3214 bv_get_value_unlimited(Id,StateId,Value),
3215 retrieve_tag_text_for_id(Id,Value,Tag,Text1),
3216 atom_codes(Text1,Text). % TODO: In the end, the result was converted from codes to atom and back
3217
3218 % a version which returns just the value as an atom:
3219 tcltk_bv_get_unlimited_value_atom(Id,AtomText) :-
3220 current_state_id(StateId),
3221 bv_get_value_unlimited(Id,StateId,Value),
3222 retrieve_tag_text_for_id(Id,Value,_Tag,AtomText).
3223
3224 convert_explain_tag(ptrue,explaintrue).
3225 convert_explain_tag(pfalse,explainfalse).
3226 convert_explain_tag(X,X).
3227
3228 % -----------------------------------------
3229
3230 % STILL TO DO: refactor eval from here and probcli into separate module
3231
3232 :- dynamic eval_elapsed_time/1.
3233 tcltk_time_call(Call) :-
3234 cputime(T1),Call,cputime(T2),ElapsedTime is T2-T1,
3235 retractall(eval_elapsed_time(_)),assertz(eval_elapsed_time(ElapsedTime)).
3236
3237 :- use_module(eval_strings).
3238
3239
3240 tcltk_eval(String,StringResult,EnumWarning,Solution) :-
3241 get_computed_preference(debug_time_out,DTO),
3242 %print(debug_time_out(DTO)),nl,
3243 time_out_with_enum_warning_one_solution(eval_string(String,StringResult,EnumWarning,LocalState),DTO,TimeOutRes),
3244 (LocalState=[] -> Solution='' ; translate_bstate(LocalState,Solution)),
3245 (is_time_out_result(TimeOutRes) ->
3246 StringResult = '**** TIME-OUT ****', print(StringResult), print(' ('),print(DTO), print('ms)'),nl,
3247 EnumWarning = no
3248 ; print_last_info).
3249
3250 :- public tcltk_eval_string_in_cur_state/2.
3251 tcltk_eval_string_in_cur_state(String,TclValue) :-
3252 eval_string_in_cur_state(String,_,Value),
3253 convert_value_to_tcl(Value,TclValue).
3254 convert_value_to_tcl(int(X),R) :- !, R=X.
3255 convert_value_to_tcl(pred_true,R) :- !, R=1.
3256 convert_value_to_tcl(pred_false,R) :- !, R=0.
3257 convert_value_to_tcl(string(X),R) :- !, R=X.
3258 % TO DO: add sets,...
3259 convert_value_to_tcl(R,R) :- print(cannot_convert_to_tcl(R,R)),nl.
3260
3261 eval_string_in_cur_state(String,Typed,Value) :-
3262 %format('Parsing : "~w"~n',[String]),
3263 bmachine:parse_expression_raw_or_atom_with_prob_ids(String,Typed),
3264 current_state_id(CurID), prob2_interface:get_state(CurID,EState),
3265 %print(evaluating_in_state(CurID)),nl,
3266 b_compute_expression_with_prob_ids(Typed,EState,Value).
3267
3268 % code to translate an expression into a list of lists that can be displayed as a table in Tk
3269 % TO DO: make more robust and add more fancy translations
3270 :- use_module(extrasrc(table_tools),[expand_and_translate_to_table_for_expr/5]).
3271 tcltk_eval_as_table(String,Res) :-
3272 eval_string_in_cur_state(String,Typed,Value),
3273 Res = list([list(Header)|Table]),
3274 expand_and_translate_to_table_for_expr(Typed,Value,Header,Table,['no-row-numbers']).
3275
3276 :- use_module(user_interrupts,[interruptable_call/1]).
3277 interruptable_tcltk_eval(String,StringResult,EnumWarning,Solution) :-
3278 if(interruptable_call(tcltk_eval(String,StringResult,EnumWarning,Solution)),true,
3279 (StringResult = 'Error or User-Interrupt', EnumWarning=unknown, Solution='')).
3280
3281 % -----------------------------------------
3282
3283 % Options can be a singleton list with: prefix, exact, suffix, fuzzy
3284 tcltk_find_value_as_table(String,Options,list([Header|Matches])) :-
3285 eval_string_in_cur_state(String,Typed,GoalValue),
3286 Header = list(['ID','Kind','MatchPath']),
3287 get_texpr_type(Typed,Type),
3288 findall(list([ID,Kind,MatchMsg]),
3289 (find_value_in_cur_state(GoalValue,Type,Options,match(Kind,ID,PathObj)),
3290 translate_bvalue_with_limit(PathObj,1000,PathS),
3291 atom_codes(PathS,MatchMsgC),
3292 debug_format(9,'* match inside ~w ~w @ path: ~w~n',[Kind,ID,PathS]),
3293 atom_codes(MatchMsg,MatchMsgC)),Matches).
3294
3295 % show the matches as a graph with the searched value in the middle and one node per variable/constant
3296 tcltk_find_value_as_graph(String,Options,File) :-
3297 eval_string_in_cur_state(String,Typed,GoalValue),
3298 get_texpr_type(Typed,Type),
3299 findall(Kind-ID-PathObj,find_value_in_cur_state(GoalValue,Type,Options,match(Kind,ID,PathObj)), Matches),
3300 group_find_value_matches(Matches,Groups), % Groups = list of match_group(Kind,ID,Paths)
3301 translate_bvalue_with_limit(GoalValue,60,GoalS),
3302 (get_preference(dot_print_graph_title,true)
3303 -> length(Matches,NrM), length(Groups,NrG),
3304 ajoin(['Occurrences of ',GoalS,': ',NrM,' in ',NrG,' identifier(s)'],Title),
3305 get_preference(dot_title_font_size,TFS), TitleAttrs = [label/Title, labelloc/t, fontsize/TFS]
3306 ; TitleAttrs = []),
3307 (Groups = [_,_,_|_] -> Layout = twopi ; Layout = dot),
3308 gen_dot_graph(File,[graph_name/find_value, no_page_size, layout/Layout, rankdir/'LR', ranksep/1.2,
3309 overlap/scale, fontname/'Helvetica',
3310 node_defaults/[fontname/'Helvetica', fontsize/11, shape/box, style/'rounded,filled'],
3311 edge_defaults/[color/gray55, arrowhead/none, fontname/'Helvetica', fontsize/9]
3312 | TitleAttrs],
3313 use_new_dot_attr_pred(tcltk_interface:find_value_dot_node(GoalS,Groups)),
3314 use_new_dot_attr_pred(tcltk_interface:find_value_dot_edge(Groups)),
3315 dot_no_same_rank,dot_no_subgraph).
3316
3317 group_find_value_matches(Matches,Groups) :-
3318 findall(Kind-ID,member(Kind-ID-_,Matches),KIDs), remove_dups(KIDs,SKIDs),
3319 findall(match_group(Kind,ID,Paths),
3320 (member(Kind-ID,SKIDs), findall(P,member(Kind-ID-P,Matches),Paths)),
3321 Groups).
3322
3323 :- public find_value_dot_node/5, find_value_dot_edge/4.
3324 find_value_dot_node(GoalS,Groups,goal_value,none,
3325 [label/htmllabel(Label), tooltip/Tooltip, shape/ellipse, penwidth/2,
3326 fillcolor/'#FCE4EC', color/'#AD1457']) :-
3327 html_escape(GoalS,EGoal),
3328 (Groups=[] -> Extra='<br/><font point-size="9" color="#707070">not found in any variable or constant</font>'
3329 ; Extra=''),
3330 ajoin(['<<font point-size="9" color="#707070">searched value</font><br/><b>',EGoal,'</b>',Extra,'>'],Label),
3331 ajoin(['Searched value: ',GoalS],Tooltip).
3332 find_value_dot_node(_,Groups,Kind:ID,none,
3333 [label/htmllabel(Label), tooltip/Tooltip, fillcolor/Fill, color/Col | Legend]) :-
3334 member(match_group(Kind,ID,Paths),Groups),
3335 find_value_kind(Kind,Keyw,Col,Fill,LegendText,Order),
3336 (get_preference(dot_print_legend,true) -> Legend=[legend/LegendText, legend_order/Order] ; Legend=[]),
3337 length(Paths,NrPaths),
3338 MaxPaths = 6,
3339 (NrPaths > MaxPaths+1 -> length(Shown,MaxPaths), append(Shown,_,Paths),
3340 More is NrPaths-MaxPaths,
3341 ajoin(['<br/><font color="#707070">… (',More,' more)</font>'],MoreTxt)
3342 ; Shown=Paths, MoreTxt=''),
3343 maplist(find_value_path_html,Shown,PathHtmls),
3344 ajoin_with_sep(PathHtmls,'<br/>',PathsHtml),
3345 html_escape(ID,EID),
3346 ajoin(['<<table border="0" cellborder="0" cellspacing="0" cellpadding="1">',
3347 '<tr><td><font point-size="8" color="#707070">',Keyw,'</font></td></tr>',
3348 '<tr><td><b>',EID,'</b></td></tr>',
3349 '<tr><td balign="left"><font point-size="10">',PathsHtml,MoreTxt,'</font></td></tr></table>>'],Label),
3350 (NrPaths=1 -> ajoin([Keyw,' ',ID,': 1 occurrence'],Tooltip)
3351 ; ajoin([Keyw,' ',ID,': ',NrPaths,' occurrences'],Tooltip)).
3352
3353 find_value_kind(variable,'VARIABLE','#1F5F99','#E3EDF7','variable',10).
3354 find_value_kind(constant,'CONSTANT','#8A6D1E','#F6EFD9','constant',20).
3355
3356 find_value_dot_edge(Groups,goal_value,Kind:ID,Attrs) :-
3357 member(match_group(Kind,ID,Paths),Groups),
3358 length(Paths,Nr),
3359 (Nr>1 -> PW is min(4,1+Nr/4), Attrs=[label/Nr, penwidth/PW] ; Attrs=[]).
3360
3361 % render a path to a match, highlighting the position(s) of the match
3362 find_value_path_html(PathObj,Html) :-
3363 mark_find_value_match(PathObj,MarkedPath),
3364 translate_bvalue_with_limit(MarkedPath,60,PathS),
3365 atom_codes(PathS,Codes),
3366 find_value_marker(Marker), atom_codes(Marker,MC),
3367 split_codes_at_marker(Codes,MC,Parts),
3368 maplist(codes_html_escape,Parts,EParts),
3369 ajoin_with_sep(EParts,'<font color="#AD1457"><b>★</b></font>',Html).
3370
3371 find_value_marker('"@MATCH@"').
3372 mark_find_value_match(term('$MATCH'),R) :- !, R=string('@MATCH@').
3373 mark_find_value_match(T,R) :- compound(T), !, T=..[F|Args], maplist(mark_find_value_match,Args,RArgs), R=..[F|RArgs].
3374 mark_find_value_match(T,T).
3375
3376 split_codes_at_marker(Codes,Marker,[Before|Rest]) :-
3377 append(Before,After,Codes), append(Marker,AfterMarker,After), !,
3378 split_codes_at_marker(AfterMarker,Marker,Rest).
3379 split_codes_at_marker(Codes,_,[Codes]).
3380
3381 codes_html_escape(Codes,E) :- atom_codes(A,Codes), html_escape(A,E).
3382
3383 % find a given value somewhere in a constant or variable value
3384 find_value_in_cur_state(GoalValue,Type,Options,match(Kind,ID,PathObj)) :-
3385 translate:translate_bvalue(GoalValue,VS),
3386 get_current_state_for_b_formula(requires_variables,State), % produce full state
3387 member(bind(ID,Value),State),
3388 ( bmachine:b_is_variable(ID,IDType), Kind=variable
3389 ; bmachine:b_is_constant(ID,IDType), Kind=constant),
3390 debug_format(19,'Searching id ~w for ~w~n',[ID,VS]),
3391 % TODO check if Type occurs in type of ID
3392 find_value(Value,IDType,GoalValue,Type,Options,PathObj).
3393
3394
3395 :- use_module(probsrc(kernel_freetypes),[registered_freetype/2]).
3396 :- use_module(bsyntaxtree,[is_set_type/2]).
3397 :- use_module(kernel_strings,[to_b_string/2]).
3398 find_value(Val,Type,GoalVal,Type,Options,Path) :- !, % target and goal type match; to do: unify_types
3399 (kernel_objects:equal_object(Val,GoalVal) -> Path = term('$MATCH')
3400 ; fuzzy_find_value(Val,Type,GoalVal,Type,Options,Path)).
3401 find_value((A,B),couple(TA,TB),GoalVal,Type,Options,Path) :- !,
3402 ( find_value(A,TA,GoalVal,Type,Options,PA),
3403 Path=','(PA,B)
3404 ; find_value(B,TB,GoalVal,Type,Options,PB),
3405 Path=','(A,PB)).
3406 find_value(rec(Fields),record(FieldTypes),GoalVal,Type,Options,rec([field(Field,Path)])) :- !,
3407 member(field(Field,Val),Fields),
3408 member(field(Field,TVal),FieldTypes),
3409 find_value(Val,TVal,GoalVal,Type,Options,Path).
3410 find_value(avl_set(AVL),AType,GoalVal,Type,Options,[Path]) :- !,
3411 is_set_type(AType,TA),
3412 custom_explicit_sets:avl_member_opt(Value,AVL), % TODO: provide a more proper interface predicate
3413 find_value(Value,TA,GoalVal,Type,Options,Path).
3414 find_value([H|T],set(TA),GoalVal,Type,Options,[Path]) :- !,
3415 member(Value,[H|T]),
3416 find_value(Value,TA,GoalVal,Type,Options,Path).
3417 find_value(freeval(ID,Case,Val),freetype(ID),GoalVal,Type,Options,freeval(Case,Path)) :- !,
3418 (registered_freetype(ID,Cases),
3419 member(case(Case,TVal),Cases) -> true
3420 ; add_error(find_value,'Illegal freeval:',freeval(ID,Case,Val)),fail
3421 ),
3422 find_value(Val,TVal,GoalVal,Type,Options,Path).
3423 find_value(Val,TypeVal,GoalVal,Type,Options,Path) :-
3424 fuzzy_find_value(Val,TypeVal,GoalVal,Type,Options,Path).
3425
3426 fuzzy_find_value(Val,_Type,string(GoalAtom),string,[Option|_],term('$FUZZYMATCH'(TargetAtom))) :-
3427 GoalAtom \= '',
3428 simple_value_to_match(Val),
3429 to_b_string(Val,string(TargetAtom)),
3430 find_match_string(Option,TargetAtom,GoalAtom).
3431
3432 simple_value_to_match(fd(_,_)).
3433 simple_value_to_match(string(_)).
3434 simple_value_to_match(int(_)).
3435 simple_value_to_match(term(_)).
3436 simple_value_to_match(freeval(_,_Case,Val)) :- ground(Val), Val=term(_).
3437
3438 :- use_module(tools_matching,[fuzzy_match_codes_lower_case/2]).
3439
3440 % check whether TargetAtom matches GoalAtom given match option
3441 find_match_string(exact,GoalAtom,GoalAtom).
3442 find_match_string(prefix,TargetAtom,GoalAtom) :-
3443 atom_concat(GoalAtom,_,TargetAtom). % use sub_atom ?
3444 find_match_string(suffix,TargetAtom,GoalAtom) :-
3445 atom_concat(_,GoalAtom,TargetAtom).
3446 find_match_string(infix,TargetAtom,GoalAtom) :-
3447 sub_atom(TargetAtom,_Before,Length,_After,GoalAtom), Length>0.
3448 find_match_string(fuzzy,TargetAtom,GoalAtom) :-
3449 atom_codes(TargetAtom,TC),
3450 atom_codes(GoalAtom,GC),
3451 fuzzy_match_codes_lower_case(TC,GC).
3452 % TODO: regex
3453
3454
3455 :- use_module(prob2_interface, [get_possible_completions/3]).
3456 % ID can be col$, svg$, ... (TODO: maybe pass category names directly ? svg_colors_only, ...)
3457 tcltk_get_possible_completions(ID,list(Completions)) :-
3458 get_possible_completions(ID,[],L),
3459 findall(C,member(completion(C,_Category),L),CL),
3460 sort(CL,Completions).
3461
3462 % -----------------------------------------
3463 % B Simplifier
3464 :- use_module(probporsrc(b_simplifier),[tcltk_simplify_b_predicate/2]).
3465 tcltk_simplify_predicate(String,StringResult) :-
3466 tcltk_simplify_b_predicate(String,StringResult).
3467
3468
3469 % -----------------------------------------
3470 % CBC Check
3471
3472 get_cbc_data_base_id_checks(IDs) :-
3473 findall(ID,b_state_model_check: cbc_check(ID,_Text,_Call,_Res,_Ok),IDs).
3474 get_cbc_data_base_text_checks(Strings) :-
3475 findall(Text1,(b_state_model_check: cbc_check(_ID,Text,_Call,_Res,_Ok),tools: string_concatenate(Text,';',Text1)),Strings).
3476
3477
3478 % -----------------------------------------
3479
3480 % CSP Refinement Search
3481
3482 %:- dynamic tcltk_cspm_mode/0.
3483 %set_tcltk_cspm_mode :- assertz(tcltk_cspm_mode).
3484 %unset_tcltk_cspm_mode :- retractall(tcltk_cspm_mode).
3485
3486
3487 %get_new_csp_process_id(E,File,ID) :-
3488 % ( parse_single_csp_expression_file(E,File,Proc) ->
3489 % haskell_csp: check_compiled_term(Proc), add_csp_process_id1(Proc,ID,haskell_csp:animatable_process)
3490 % ; add_error(parse_single_csp_expression_file,'Invalid process expression: ',E),fail
3491 % ).
3492
3493 %parse_and_analyze_process_expression(ProcExp,File,Proc) :-
3494 % ( parse_single_csp_expression_file(ProcExp,File,Proc) -> true
3495 % ; add_error(parse_single_csp_expression_file,'Invalid process expression: ',ProcExp),fail
3496 % ).
3497
3498 get_csp_process_id(Process,ID) :- get_start_transition_term(Process,Trans),
3499 transition(root,Trans,ID).
3500
3501 :- use_module(probcspsrc(haskell_csp),[animatable_process_without_arguments/1,animatable_process_cli/1]).
3502 add_csp_process_id(Process,NewID) :-
3503 add_csp_process_id1(Process,NewID,animatable_process_cli).
3504
3505 add_csp_process_id1(Process,NewID,Pred) :-
3506 (call(Pred,Process)
3507 -> get_start_transition_term(Process,Trans),
3508 (transition(root,Trans,_,DestID) -> NewID=DestID % process already set up
3509 ; xtl_interface:get_start_expr(Process,NewState),
3510 add_trans_id(root,Trans,NewState,NewID,_)
3511 )
3512 ; add_error_fail(add_csp_process_id,'Not an animatable CSP Process: ',Process)).
3513
3514 get_start_transition_term('MAIN',R) :- !, R= start_cspm_MAIN.
3515 get_start_transition_term(agent_call(_Src,'MAIN',[]),R) :- !, R= start_cspm_MAIN.
3516 get_start_transition_term(P,start_cspm(P)).
3517
3518 add_csp_general_process_id(val_of(Process,_),ID) :- !,
3519 ( animatable_process_without_arguments(Process) % in case the called processes is one without arguments, then we don't have to parse the expression
3520 -> add_csp_process_id(Process,ID)
3521 % code below not covered; loaded_main_file only defined for probcli entry point !
3522 %; animation_mode(cspm),
3523 % loaded_main_file(CSPFile),
3524 % parse_and_analyze_process_expression(Process,CSPFile,Proc),
3525 % (transition(root,start_cspm(Proc),_TransID,ID) -> true
3526 % ; otherwise -> add_trans_id(root,start_cspm(Proc),Proc,ID,_)
3527 % )
3528 ).
3529 add_csp_general_process_id(GenProcExpr,ID) :-
3530 % stripping out the source-loc info
3531 haskell_csp_analyzer: clear_span(GenProcExpr,GenProcExpr1),
3532 get_start_transition_term(GenProcExpr1,Trans),
3533 (transition(root,Trans,_TransID,ID)
3534 -> true
3535 ; add_trans_id(root,Trans,GenProcExpr1,ID,_)
3536 ).
3537
3538 :- public tcltk_csp_in_situ_refinement/4.
3539 tcltk_csp_in_situ_refinement(ImplProcess,AbsProcess,ResTrace,Style) :-
3540 debug_format(9,'Checking ~w ~w ~w~n',[AbsProcess,Style,ImplProcess]),
3541 tcltk_csp_in_situ_refinement(ImplProcess,AbsProcess,ResTrace,Style,10000000).
3542 csp_ref_style('[T=',trace). % Trace Refinement
3543 csp_ref_style('T',trace). % Trace Refinement
3544 csp_ref_style('[SF=',singleton_failures). % Singleton Failures Refinement
3545 csp_ref_style('[F=',failures). % Failures Refinement
3546 csp_ref_style('[R=',refusals). % Refusals Refinement
3547 csp_ref_style('[RD=',refusals_div). % Refusals-Divergence Refinement
3548 csp_ref_style('F',failures). % Failures Refinement
3549 csp_ref_style('[FD=',X) :- csp_ref_style('FailureDivergence',X).
3550 csp_ref_style('FD',X) :- csp_ref_style('FailureDivergence',X).
3551 csp_ref_style('Trace',trace).
3552 csp_ref_style('Failure',failures).
3553 csp_ref_style('FailureDivergence',failure_divergences).
3554 csp_ref_style('RefusalTesting',refusals).
3555 csp_ref_style('RefusalTestingDiv',refusals_div).
3556 csp_ref_style('RevivalTesting',revival). % not yet supported; the refinement checker raises an error
3557 csp_ref_style('RevivalTestingDiv',revival_div). % ditto
3558
3559 translate_csp_ref_style(Style,RefStyle) :- (csp_ref_style(Style,RefStyle) -> true ;
3560 add_error_fail(csp,'Unknown refinement style: ',Style)).
3561
3562 :- use_module(extrasrc(refinement_checker),[in_situ_ref_search/5]).
3563
3564 % tcltk_csp_in_situ_refinement('P','Q',R,0,1000). tcltk_csp_in_situ_refinement('Q','P',R,1000).
3565 tcltk_csp_in_situ_refinement(ImplProcess,AbsProcess,ResTrace,Style,MaxNrOfNewNodes) :-
3566 add_csp_process_id(ImplProcess,ImplNodeID),
3567 add_csp_process_id(AbsProcess,SpecNodeID),
3568 translate_csp_ref_style(Style,RefStyle),
3569 in_situ_ref_search(ImplNodeID,SpecNodeID,ResTrace,RefStyle,MaxNrOfNewNodes).
3570
3571 :- use_module(probcspsrc(haskell_csp),[get_csp_assertions/1,translate_csp_assertion/2]).
3572
3573 tcltk_check_csp_assertions(List,Summary) :- get_csp_assertions(Assertions),
3574 treat_csp_ass(Assertions,List,0,0,0,Summary). % TO DO: display _List
3575
3576 treat_csp_ass([],[],T,F,U,[total/Tot, true/T, false/F, unknown/U]) :- Tot is T+F+U.
3577 treat_csp_ass([Assertion|T],['='(PP,Ok)|TPP],True,False,U,Summary) :- !,
3578 (checkAssertion(Assertion,PP,_,Ok,_)
3579 -> ( Ok=true -> T1 is True+1, F1=False, U1=U
3580 ; Ok=false -> T1=True, F1 is False+1, U1=U
3581 ; T1=True, F1=False, U1 is U+1)
3582 ; U1 is U+1, T1=True, PP = '??',
3583 F1=False,Ok=unknown
3584 ),
3585 treat_csp_ass(T,TPP,T1,F1,U1,Summary).
3586 treat_csp_ass([H|T],TP,T1,F1,U,Summary) :-
3587 add_error(treat_csp_ass,'Unknown CSP assertion: ',H),
3588 U1 is U+1, treat_csp_ass(T,TP,T1,F1,U1,Summary).
3589
3590 % assertModelCheckExt(False,val_of(P3,src_span(25,8,25,10,562,2)),DeadlockFree,F)
3591
3592 :- use_module(extrasrc(refinement_checker),[in_situ_model_check/5, reset_refinement_checker/0]).
3593
3594 run_assertion_check(assertModelCheckExt(Negated,Spec,Type,ModelStyle),Negated,ResTrace) :-
3595 haskell_csp_analyzer: compile_body(Spec,'assertModelCheck',[],[],CSpec),
3596 debug_println(9,assertModelCheckExt(Negated,CSpec,Type,ModelStyle)),
3597 add_csp_general_process_id(CSpec,SpecNodeID),
3598 translate_csp_ref_style(ModelStyle,RefStyle),
3599 in_situ_model_check(SpecNodeID,ResTrace,Type,RefStyle,10000000),
3600 formatsilent('Result trace for assertModelCheck: ~w~n',[ResTrace]).
3601 run_assertion_check(assertModelCheck(Negated,Spec,Style),Negated,ResTrace) :-
3602 run_assertion_check(assertModelCheckExt(Negated,Spec,Style,'FailureDivergence'),Negated,ResTrace).
3603 run_assertion_check(assertRef(Negated,Spec,Style,Impl,Span),Negated,ResTrace) :-
3604 haskell_csp_analyzer: compile_body(Spec,'assertRef',[],[],CSpec),
3605 haskell_csp_analyzer: compile_body(Impl,'assertRef',[],[],CImpl),
3606 debug_println(9,assertRef(Negated,CSpec,Style,CImpl,Span)),
3607 add_csp_general_process_id(CSpec,SpecNodeID),
3608 add_csp_general_process_id(CImpl,ImplNodeID),
3609 translate_csp_ref_style(Style,RefStyle),
3610 refinement_checker:in_situ_ref_search(ImplNodeID,SpecNodeID,ResTrace,RefStyle,10000000).
3611 run_assertion_check(assertLtl(Negated,Spec,FormulaAsAtom,_Span),Negated,ResTrace) :-
3612 add_csp_process_id_normalized(Spec,'assertLtl',CSpec,CSpecNodeID),
3613 %% print(add_csp_general_process_id(Spec,CSpec,SpecNodeID)),nl,
3614 reset_animation_history, % do not use tcltk_reset: it would discard errors found so far
3615 ltl_model_check_with_ce1(CSpec,FormulaAsAtom,-1,specific_node(CSpecNodeID),Result),
3616 translate_ltl_result(Result,ResTrace),
3617 debug_println(9,ltl_result(Negated,CSpec,CSpecNodeID,FormulaAsAtom,Result)).
3618 run_assertion_check(assertCtl(Negated,Spec,FormulaAsAtom,_Span),Negated,ResTrace) :-
3619 add_csp_process_id_normalized(Spec,'assertCtl',CSpec,CSpecNodeID),
3620 reset_animation_history, % do not use tcltk_reset: it would discard errors found so far
3621 ctl_model_check_with_ce(CSpec,FormulaAsAtom,-1,specific_node(CSpecNodeID),Result,Trace),
3622 debug_println(9,ctl_result(Negated,CSpec,CSpecNodeID,FormulaAsAtom,Result)),
3623 translate_ctl_result(Result,Trace,ResTrace).
3624
3625 checkAssertion(Assertion,PP,Negated,Ok,ResTrace) :-
3626 translate_csp_assertion(Assertion,PP),
3627 formatsilent('CHECKING ~w~n',[PP]),
3628 debug_println(9,checkAssertion(Assertion)),
3629 reset_refinement_checker,
3630 (run_assertion_check(Assertion,Negated,ResTrace)
3631 -> debug_println(9,result(ResTrace)),
3632 (ResTrace=no_counter_example
3633 -> (Negated = 'False' -> Ok=true ; Ok=false)
3634 ; ResTrace=no_counter_example_found
3635 -> Ok=interrupted
3636 ; ResTrace=not_checked % e.g., unsupported refinement model; an error has been raised
3637 -> Ok=interrupted
3638 ; ResTrace=[interrupted|_]
3639 -> Ok=interrupted, print('*** Execution interrupted by user ***'),nl
3640 ; ResTrace=[incomplete]
3641 -> Ok=interrupted, print('*** Not all states were explored ***'),nl
3642 ; ResTrace=[nostart]
3643 -> Ok=interrupted, print('*** No initial state found ***'),nl
3644 ; Negated = 'False' -> Ok=false
3645 ; Ok=true
3646 ),
3647 (Ok=true -> printsilent('OK'),nls
3648 ; Ok=interrupted -> print('*** UNKNOWN ***'),nl
3649 ; print('*** FALSE ***'),nl
3650 )
3651 ; add_error_fail(checkAssertion,'Internal Error, Assertion Checking Failed for: ',PP)
3652 ).
3653
3654 add_csp_process_id_normalized(Spec,Functor,CSpec,CSpecNodeID) :-
3655 % stripping out the src_span info
3656 haskell_csp_analyzer: clear_span(Spec,SpecNoSpan),
3657 haskell_csp_analyzer: compile_body(SpecNoSpan,Functor,[],[],CSpec),
3658 add_csp_general_process_id(CSpec,CSpecNodeID).
3659
3660 translate_ltl_result(ok,Res) :- !,
3661 Res = no_counter_example.
3662 translate_ltl_result(no,Res) :- !,
3663 Res = no.
3664 translate_ltl_result(ce(Atom),Res) :-
3665 !, % we have a counter-example for the LTL formula
3666 Res=Atom.
3667 translate_ltl_result(interrupted,Res) :-
3668 !,
3669 Res=[interrupted].
3670 translate_ltl_result(incomplete,Res) :- % not all states explored
3671 !,
3672 Res=[incomplete].
3673 translate_ltl_result(nostart,Res) :- % no initial state found
3674 !,
3675 Res=[nostart].
3676 translate_ltl_result(syntax_error,_Res) :- % the error has already been reported by the LTL parser
3677 !,
3678 fail.
3679 translate_ltl_result(Status,_Res) :-
3680 add_error_fail(ltl_assertions_result, 'Internal Error: unknown LTL assertion result ', Status).
3681
3682 translate_ctl_result(true,_Trace,ResTrace) :- !,
3683 ResTrace = no_counter_example.
3684 translate_ctl_result(false,ce(Atom),ResTrace) :- !,
3685 ResTrace = Atom.
3686 translate_ctl_result(interrupted,_TRace,ResTrace) :-
3687 !,
3688 ResTrace=[interrupted].
3689 translate_ctl_result(Status,_Trace,_ResTrace) :-
3690 add_error_fail(ctl_assertions_result, 'Internal Error: unknown CTL assertion result ', Status).
3691
3692
3693 tcltk_check_csp_assertion(Assertion,CSPFile,Negated,Result) :-
3694 tcltk_check_csp_assertion(Assertion,CSPFile,Negated,_PlTerm,Result).
3695
3696 tcltk_check_csp_assertion(Assertion,CSPFile,Negated,PlTerm,Result) :-
3697 parse_single_csp_declaration(Assertion,CSPFile,PlTerm),
3698 checkAssertion(PlTerm,_PP,Negated,_Ok,Result).
3699
3700 :- public tcltk_play_ltl_ctl_counterexample_trace/4.
3701 tcltk_play_ltl_ctl_counterexample_trace(Assertion,CSPFile,Type,FairnessChecked) :-
3702 announce_event(play_counterexample),
3703 ( Type == ltl -> Functor = assertLtl
3704 ; Type == ctl -> Functor = assertCtl
3705 ; add_error_fail(ltl_ctl_counterexample, 'Internal Error: Model checker type unknown: ',Type)),
3706 % constructing the prolog declaration term
3707 PlDeclTerm =.. [Functor,_Negated,Spec,FormulaAsAtom,_Span],
3708 parse_single_csp_declaration(Assertion,CSPFile,PlDeclTerm),
3709 haskell_csp_analyzer: clear_span(Spec,SpecNoSpan),
3710 haskell_csp_analyzer: compile_body(SpecNoSpan,'assertLtl',[],[],CSpec),
3711 % parsing and preprocessing the LTL/CTL formula
3712 parse_and_preprocess_formula(FormulaAsAtom,Type,PF),
3713 (is_fairness_implication(PF) -> FairnessChecked='yes'; FairnessChecked='no'),
3714 % need to reset history and current state before loading the counter-example
3715 reset_animation_history,
3716 tcltk_play_counterexample(Type,CSpec,PF).
3717
3718 tcltk_play_counterexample(ltl,Spec,Formula) :- !,
3719 tcltk_play_ltl_counterexample(Spec,Formula).
3720 tcltk_play_counterexample(ctl,Spec,Formula) :- !,
3721 tcltk_play_ctl_counterexample(Spec,Formula).
3722 tcltk_play_counterexample(Type,Spec,Formula) :-
3723 add_error_fail(ltl_ctl_counterexample, 'Internal Error: Unknown domain type: ', (Type,Spec,Formula)).
3724
3725 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3726
3727
3728 %%%% Parse and get LTL formulas from LTL File %%%%
3729 get_ltl_formulas_from_file(Filename,Text) :-
3730 parse_ltlfile(Filename, Formulas), debug_println(9,Formulas),
3731 translate_ltl_formulas(Formulas,Text).
3732
3733 translate_ltl_formulas(Formulas,Text) :-
3734 maplist(translate_ltl_formula,Formulas,Strings),
3735 haskell_csp: concatenate_string_list(Strings,Text).
3736
3737 translate_ltl_formula(formula(_Name,Formula),Text) :- !,
3738 pp_ltl_formula(Formula,T),
3739 string_concatenate(T,'$',Text).
3740 translate_ltl_formula(F,'') :- add_error(get_ltl_formulas_from_file,'Illegal formula: ',F).
3741
3742
3743 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3744
3745
3746 tcltk_explore_csp_process(ProcString,SpecNodeID) :-
3747 haskell_csp: parse_single_csp_expression(ltl,ProcString,Res),
3748 haskell_csp_analyzer: clear_span(Res,ResNoSpan),
3749 haskell_csp_analyzer: compile_body(ResNoSpan,'assertLtl',[],[],CRes),
3750 add_csp_general_process_id(CRes,SpecNodeID),
3751 refinement_checker:dfs_check(SpecNodeID,_ResTrace,false,false).
3752
3753 tcltk_visualize_csp_process(SpecNodeID,F) :-
3754 visualize_graph: tcltk_print_csp_process_states_for_dot(F,SpecNodeID).
3755
3756 :- dynamic nr_csp_process_state/1.
3757 get_csp_process_stats(NrNodes) :-
3758 assertz(nr_csp_process_state(0)),
3759 count_nodes,
3760 nr_csp_process_state(NrNodes),
3761 retractall(nr_csp_process_state(_)).
3762
3763 count_nodes :-
3764 refinement_checker: dvisited(_NodeID),
3765 nr_csp_process_state(NrNodes),
3766 NewNrNodes is NrNodes +1,
3767 retractall(nr_csp_process_state(_)),
3768 assertz(nr_csp_process_state(NewNrNodes)),
3769 fail.
3770 count_nodes.
3771
3772 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3773
3774 tcltk_machine_has_assertions :-
3775 ( b_get_static_assertions_from_machine([_|_]); b_get_dynamic_assertions_from_machine([_|_]) ), !.
3776
3777 tcltk_unique_top_level_operation(Name) :- b_top_level_operation(Name),
3778 \+ (b_top_level_operation(N2), N2 \= Name).
3779
3780 tcltk_top_level_operations(list(Res)) :-
3781 findall(Name,b_top_level_operation(Name),Names),
3782 length(Names,L),
3783 (L>5 -> sort(Names,Res) ; Res=Names).
3784
3785 tcltk_get_vacuous_guards(list(L)) :-
3786 eclipse_interface:get_vacuous_guards(LP), % to do: add source column
3787 (LP=[] -> L = ['No vacuous guards']
3788 ; L = [list(['VACUOUS GUARDS'])|L1],
3789 findall(list([P]), member(P,LP), L1)
3790 ).
3791
3792 tcltk_get_vacuous_invariants(list(L)) :-
3793 eclipse_interface:get_vacuous_invariants(LP),
3794 (LP=[] -> L = ['No vacuous invariants']
3795 ; L = [list(['VACUOUS INVARIANTS'])|L1],
3796 findall(list([TP]), (member(P,LP), translate_bexpression(P,TP)), L1)
3797 ).
3798
3799 tcltk_get_vacuous_invariants_table(list([list(['LHS','Op','RHS','Source'])|L])) :-
3800 eclipse_interface:get_vacuous_invariants(LP),
3801 LP \= [], !,
3802 maplist(get_expr_and_source,LP,L).
3803 tcltk_get_vacuous_invariants_table(list(['No vacuous invariants'])).
3804
3805 :- use_module(translate,[translate_bexpression_with_limit/3]).
3806 :- use_module(error_manager,[get_tk_table_position_info/2]).
3807 get_expr_and_source(P,list([TS1,Op,TS2,Src])) :-
3808 decompose(P,LHS,Op,RHS),
3809 translate_bexpression_with_limit(LHS,150,TS1),
3810 translate_bexpression_with_limit(RHS,60,TS2),
3811 get_tk_table_position_info(P,Src).
3812
3813 decompose(b(implication(LHS,RHS),pred,_),LHS,'=>',RHS) :- !.
3814 decompose(b(disjunction(LHS,RHS),pred,_),LHS,'or',RHS) :- !.
3815 decompose(LHS,LHS,'?',b(truth,pred,[])).
3816
3817
3818 % -------------------
3819
3820
3821 :- use_module(extrasrc(mcts_game_play), [mcts_auto_play/4, mcts_auto_play_available/0]).
3822
3823 tcltk_mcts_auto_play :- tcltk_mcts_auto_play(_).
3824 tcltk_mcts_auto_play(TransID) :-
3825 mcts_auto_play_available,
3826 current_state_id(CurID),
3827 mcts_auto_play(CurID,ActionAsTerm,TransID,State2),
3828 (tcltk_perform_action(CurID,ActionAsTerm,TransID,State2)
3829 -> true
3830 ; add_error(tcltk_mcts_auto_play,'Cannot perform chosen action:',ActionAsTerm),fail).
3831
3832
3833 % -----------------------
3834
3835
3836 :- dynamic current_simb_state/1, simb_history/5.
3837
3838 :- use_module(extrasrc(simb_parser)).
3839 :- use_module(extrasrc(simb_simulator)).
3840
3841 tcltk_start_simulation :-
3842 retractall(current_simb_state(_)),
3843 retractall(simb_history(_,_,_,_,_)),
3844 simb_file_loaded(_),!,
3845 reset_animation_history, % do not reset errors
3846 simb_initial_state(Init),
3847 assert(current_simb_state(Init)).
3848 tcltk_start_simulation :- add_error(simb,'Cannot start simulation, no SimB file loaded'),fail.
3849
3850 % Options: visible, stop_if_time_progresses, stop_if_time_exceeds(T)
3851 tcltk_peform_simulation_steps(Nr,ResElapsedTime,StopReason,Opts) :- \+ current_simb_state(_),!,
3852 (tcltk_start_simulation
3853 -> tcltk_peform_simulation_steps2(1,0,Nr,ResElapsedTime,StopReason,Opts)
3854 ; ResElapsedTime=0, StopReason=error % error already reported
3855 ).
3856 tcltk_peform_simulation_steps(Nr,ResElapsedTime,StopReason,Opts) :-
3857 tcltk_peform_simulation_steps2(1,0,Nr,ResElapsedTime,StopReason,Opts).
3858
3859 tcltk_peform_simulation_steps2(CurStepNr,ElapsedTime,MaxNr,ResElapsedTime,StopReason,Opts) :-
3860 stop_simulation(CurStepNr,ElapsedTime,MaxNr,StopReason,Opts), !,
3861 (debug_mode(off) -> true
3862 ; format('Stop simulation at step ~w after ~w ms~n',[CurStepNr,ElapsedTime]),
3863 current_simb_state(State), portray_simb_state(State)),
3864 ResElapsedTime = ElapsedTime.
3865 tcltk_peform_simulation_steps2(CurStepNr,ElapsedTime,MaxNr,ResElapsedTime,StopReason,Opts) :-
3866 (tcltk_peform_simulation_step(Delta,Opts,StepRes) -> true ; StepRes=deadlock),
3867 (StepRes = ok
3868 -> N1 is MaxNr-1,
3869 C1 is CurStepNr+1, E1 is ElapsedTime+Delta,
3870 tcltk_peform_simulation_steps2(C1,E1,N1,ResElapsedTime,StopReason,Opts)
3871 ; StepRes = deadlock
3872 -> ResElapsedTime = ElapsedTime,
3873 StopReason = deadlock,
3874 add_warning(simb,'Simulation is deadlocked at step nr: ',CurStepNr)
3875 %,current_simb_state(State), portray_simb_state(State)
3876 ; ResElapsedTime = ElapsedTime, % the animator could not perform the transition; error already reported
3877 StopReason = error
3878 ).
3879
3880 stop_simulation(_,_,Nr,max_steps_reached,_Opts) :- Nr =< 0.
3881 stop_simulation(CurStepNr,_,_Nr,time_progresses,Opts) :- CurStepNr>1,
3882 member(stop_if_time_progresses,Opts),
3883 current_simb_state(State),
3884 get_simb_delay_until_next_step(State,Delta),
3885 Delta > 0.
3886 stop_simulation(_,ElapsedTime,_Nr,max_time_exceeded,Opts) :-
3887 member(stop_if_time_exceeds(MaxTime),Opts),
3888 ElapsedTime > MaxTime.
3889
3890 % StepRes is ok, deadlock or error (animator could not perform the transition chosen by the simulator)
3891 tcltk_peform_simulation_step(Delta,Opts,StepRes) :-
3892 current_state_id(CurID), % todo: assert/retract in tcltk_peform_simulation_steps
3893 retract(current_simb_state(State)),!,
3894 simb_update_current_state_id(State,CurID,State2),
3895 (simb_perform_step(Opts,State2, TransID, Delta, Probability,NewSimBState)
3896 -> (simb_perform_animator_transition(CurID,TransID)
3897 -> % only update the simulator once the animator has performed the transition, so that both stay synchronised
3898 assert(current_simb_state(NewSimBState)),
3899 save_last_simulation_step(State2,TransID,Delta,Probability),
3900 StepRes = ok
3901 ; assert(current_simb_state(State2)),
3902 StepRes = error
3903 )
3904 ; assert(current_simb_state(State2)),
3905 StepRes = deadlock
3906 ).
3907
3908 simb_perform_animator_transition(_,none) :- !.
3909 simb_perform_animator_transition(CurID,TransID) :-
3910 (tcltk_perform_action(CurID,_,TransID,_)
3911 -> true % TODO: add time and maybe activation id store_transition_infos(TransInfo,TransID)
3912 ; add_error(simb,'Cannot perform chosen transition:',TransID),fail).
3913
3914 % save last simulation state and the transition that was performed from it
3915 save_last_simulation_step(LastSimBState,TransID,Delta,Probability) :-
3916 tcltk_get_simb_history_length(Len), L1 is Len+1,
3917 asserta(simb_history(L1,TransID,Delta,Probability,LastSimBState)).
3918
3919 tcltk_get_simb_history_length(Len) :- simb_history(Len,_,_,_,_),!.
3920 tcltk_get_simb_history_length(0).
3921
3922 % try and go back one simulation step
3923 tcltk_backtrack_simulation_step :-
3924 simb_history(Step,TransID,_Delta,_Prob,LastSimBState),!,
3925 get_simb_current_state_id(LastSimBState,LastCurID),
3926 (TransID = none -> true
3927 ; tcltk_can_backtrack_to_state_id(LastCurID) -> tcltk_backtrack
3928 ; add_warning(simb,'Animator and simulator not synchronised, cannot step back in animator to state, : ',LastCurID)
3929 ),
3930 % only remove the history entry once the animator has stepped back
3931 retract(simb_history(Step,_,_,_,_)),
3932 retractall(current_simb_state(_)), % TODO: add to forward history
3933 assert(current_simb_state(LastSimBState)).
3934
3935 tcltk_can_backtrack_simulation_step :-
3936 simb_history(_,TransID,_Delta,_Prob,LastSimBState),
3937 (TransID=none -> true
3938 ; get_simb_current_state_id(LastSimBState,LastCurID),
3939 tcltk_can_backtrack_to_state_id(LastCurID)).
3940
3941 tk_get_simb_history_entry([Step,Time,Delta,ProbS,ActID,ActionString]) :-
3942 simb_history(Step,TransID,Delta,Prob,LastSimBState),
3943 (Prob=none -> ProbS = 'det' ; ProbS = Prob),
3944 get_simb_current_state_id(LastSimBState,CurID),
3945 translate_event_from_src_and_target_id(CurID,TransID,ActionString),
3946 get_simb_time(LastSimBState,Time),
3947 get_simb_next_activation_term(LastSimBState,ActID,_Params). % TODO: extract number of activations, ...
3948
3949 translate_event_from_src_and_target_id(_,none,ActionString) :- !, ActionString='-'.
3950 translate_event_from_src_and_target_id(CurID,TransID,ActionString) :-
3951 transition(CurID,ActionAsTerm,TransID,NewID),
3952 translate_event_with_src_and_target_id(ActionAsTerm,CurID,NewID,40,ActionString).
3953
3954 tk_get_simb_history_table(list([list(['Step','Time','Delta','Probability','ActivationID','VisibleEvent'])|RList])) :-
3955 findall(list(EntryList),tk_get_simb_history_entry(EntryList),List),
3956 reverse(List,RList).
3957
3958 simb_perform_step(Opts,State, TransID, Delta, Probability, NewSimBState) :- member(visible,Opts),!,
3959 simb_perform_visible_step(State, TransID, Delta, Probability, NewSimBState).
3960 simb_perform_step(_,State, TransID, Delta, Probability, NewSimBState) :-
3961 simb_perform_step(State, TransID, Delta, Probability, NewSimBState).
3962
3963 tcltk_delay_until_next_step(Time) :-
3964 current_simb_state(State), !, get_simb_delay_until_next_step(State,Time).
3965 tcltk_delay_until_next_step(0).
3966
3967 tcltk_simulation_time(Time) :-
3968 current_simb_state(State), !, get_simb_time(State,Time).
3969 tcltk_simulation_time('-').
3970
3971 tk_get_simb_scheduling_table_stats(Info) :-
3972 current_simb_state(State), !, get_simb_scheduling_table_info(State,Info).
3973 tk_get_simb_scheduling_table_stats('-').
3974
3975
3976 tk_get_simb_scheduling_table(list([list(['Time(ms)','Prio','ActivationID','Params'])|List])) :-
3977 current_simb_state(State),!, %simb_simulator:portray_simb_state(State),nl,
3978 findall(list([Time,Prio,ID,ParamStr]),(get_simb_scheduling_entry(State,Time,Prio,ID,Params),
3979 get_simb_params(Params,ParamStr)),List).
3980 tk_get_simb_scheduling_table(list(['Simulation Not Started'])).
3981
3982 get_simb_params([],Res) :- !, Res='-'.
3983 get_simb_params(List,ParamString) :-
3984 get_param_tokens(List,Tokens), ajoin(Tokens,ParamString).
3985
3986 % note we could use translate_bstate_limited; but it inserts spaces/newlines
3987 :- use_module(probsrc(translate), [translate_bvalue_with_limit/3]).
3988 get_param_tokens([],[]).
3989 get_param_tokens([bind(Name,Val)],[Name,'=',ValS]) :- !,
3990 translate_bvalue_with_limit(Val,20,ValS).
3991 get_param_tokens([bind(Name,Val)|T],[Name,'=',ValS,','|TT]) :-
3992 translate_bvalue_with_limit(Val,20,ValS),
3993 get_param_tokens(T,TT).
3994
3995 tk_get_simb_activations(list([list(['ActivationID','Prio','Kind','After','TransSelection','Guard','Execute'])|List])) :-
3996 simb_file_loaded(_),!,
3997 findall(list([ID,PrioS,ActKind,AftS,TransSelection,Gs,ExList]),
3998 (simb_activation(ID,Prio,ActKind),
3999 simb_activation_effect(ID,Execute,AddGuard,TransSelection,After,_ActivationList),
4000 get_simb_number_as_str(After,20,AftS),
4001 get_simb_number_as_str(Prio,20,PrioS),
4002 ajoin_with_sep(Execute,',',ExList),
4003 translate_bexpression_with_limit(AddGuard,20,Gs)),List).
4004 tk_get_simb_activations(list(['Simulation Not Loaded'])).
4005
4006 get_simb_number_as_str(After,Lim,AftS) :-
4007 (number(After) -> AftS = After ; translate_bexpression_with_limit(After,Lim,AftS)).
4008
4009 % for reacting to clicks in tk_get_simb_activations
4010 tk_get_simb_activation_details(Nr,ID,list([list(['Attribute','Value'])|Details])) :-
4011 findall(ID, simb_activation(ID,_Prio,_ActKind), List),
4012 nth1(Nr,List,ID),
4013 findall(list([Attr,Val]),describe_activation(ID,Attr,Val),Details).
4014
4015 :- use_module(probsrc(bsyntaxtree), [def_get_texpr_id/2]).
4016
4017 describe_activation(ID,id,ID).
4018 describe_activation(ID,param,Para) :-
4019 simb_activation_params(ID,TParams),
4020 member(TID,TParams), def_get_texpr_id(TID,ParaID),
4021 get_texpr_type(TID,Type), pretty_type(Type,String),
4022 ajoin([ParaID,' : ',String],Para).
4023 describe_activation(ID,priority,PrioS) :-
4024 simb_activation(ID,Prio,_ActKind),get_simb_number_as_str(Prio,150,PrioS).
4025 describe_activation(ID,activationKind,ActKind) :- simb_activation(ID,_Prio,ActKind).
4026 describe_activation(ID,additionalGuard,Gs) :-
4027 simb_activation_effect(ID,_,AddGuard,_,_After,_),translate_bexpression_with_limit(AddGuard,150,Gs).
4028 describe_activation(ID,after,AfterS) :-
4029 simb_activation_effect(ID,_,_,_,After,_),get_simb_number_as_str(After,150,AfterS).
4030 describe_activation(ID,execute,OpName) :-
4031 simb_activation_effect(ID,Execute,_,_TransSelect,_After,_), member(OpName,Execute).
4032 describe_activation(ID,transitionSelection,TransSelect) :-
4033 simb_activation_effect(ID,_,_,TransSelect,_After,_).
4034 describe_activation(ID,activating,Activating) :-
4035 simb_activation_effect(ID,_,_,_TransSelect,_After,ActivatingList),
4036 member(A,ActivatingList),
4037 (atomic(A) -> Activating=A
4038 ; A=triggerActivation(A2,_Params,_Prob) -> Activating=A2 % TODO: show params
4039 ; member(chooseActivation(A2,Prob),A), get_simb_number_as_str(Prob,30,P2), ajoin([A2,':',P2],Activating)).
4040 describe_activation(ID,Option,true) :-
4041 simb_activation_options(ID,Options), member(Option,Options).
4042 % TODO: extend for all other infos
4043
4044 % ---------------------
4045
4046 :- use_module(probsrc(tools),[wrap_and_truncate_atom/4,string_escape/2]).
4047 :- use_module(probsrc(preferences),[temporary_set_preference/3, reset_temporary_preference/2]).
4048
4049 tcltk_print_simb_activation_graph(File) :-
4050 (current_simb_state(State) -> true ; State=none),
4051 temporary_set_preference(dot_print_self_loops,true,Chng),
4052 (get_preference(dot_print_graph_title,true)
4053 -> get_preference(dot_title_font_size,TFS), TitleAttrs = [label/'SimB activation diagram', labelloc/t, fontsize/TFS] ; TitleAttrs=[]),
4054 call_cleanup(gen_dot_graph(File,[graph_name/simb_activations, no_page_size, fontname/'Helvetica',
4055 nodesep/0.35, ranksep/0.55,
4056 node_defaults/[fontname/'Helvetica', fontsize/11, shape/box,
4057 style/'rounded,filled', margin/'0.12,0.06'],
4058 edge_defaults/[fontname/'Helvetica', fontsize/9, arrowsize/0.8]
4059 | TitleAttrs],
4060 use_new_dot_attr_pred(tcltk_interface:dot_activation_node(State)),
4061 use_new_dot_attr_pred(tcltk_interface:dot_activation_trans(State)),
4062 dot_no_same_rank,dot_no_subgraph),
4063 reset_temporary_preference(dot_print_self_loops,Chng)).
4064
4065 :- public dot_activation_node/4, dot_activation_trans/4.
4066 % one node per SimB activation, showing its parameters, timing, priority, executed event and guard
4067 dot_activation_node(State,ID,none,[label/htmllabel(Label), tooltip/Tooltip, fillcolor/Fill, color/Col | Attrs]) :-
4068 simb_activation(ID,Prio,ActKind),
4069 simb_activation_effect(ID,Execute,AddGuard,_TransSelection,After,_ActivationList),
4070 (get_simb_scheduling_entry(State,Time,_Prio,ID,_)
4071 -> Class=scheduled, ajoin(['scheduled at ',Time,' ms'],SchedTxt), Rows0=[SchedTxt]
4072 ; (sub_atom(ID,0,1,_,'$') -> Class=internal ; Class=normal), Rows0=[]),
4073 simb_activation_class_colours(Class,Fill,Col,LegendText,Order),
4074 (simb_activation_params(ID,TParams), TParams = [_|_], get_texpr_ids(TParams,Params)
4075 -> ajoin_with_sep(Params,', ',ParamsS), ajoin(['params: ',ParamsS],ParamsRow), Rows1=[ParamsRow|Rows0]
4076 ; Rows1=Rows0),
4077 (Prio=1 -> Rows2=Rows1
4078 ; get_simb_number_as_str(Prio,30,PrioS), ajoin(['priority: ',PrioS],PrioRow), append(Rows1,[PrioRow],Rows2)),
4079 (After=0 -> Rows3=Rows2
4080 ; get_simb_number_as_str(After,30,AftS), ajoin(['after: ',AftS],AftRow), append(Rows2,[AftRow],Rows3)),
4081 (Execute=[] -> Rows4=Rows3
4082 ; Execute=[Ex], atom(Ex) -> (Ex=ID -> Rows4=Rows3 ; ajoin(['execute: ',Ex],ExRow), append(Rows3,[ExRow],Rows4))
4083 ; length(Execute,Len) -> ajoin(['execute list of ',Len,' events'],ExRow), append(Rows3,[ExRow],Rows4)
4084 ; append(Rows3,['execute: ??'],Rows4)),
4085 (AddGuard=b(truth,_,_) -> Rows=Rows4
4086 ; translate_bexpression_with_limit(AddGuard,40,Gs), ajoin(['guard: ',Gs],GRow), append(Rows4,[GRow],Rows)),
4087 html_escape(ID,EID),
4088 maplist(html_escape,Rows,ERows),
4089 ajoin_with_sep(ERows,'<br/>',RowsHtml),
4090 (ERows=[] -> RowsPart='' ; ajoin(['<br/><font point-size="9" color="#505050">',RowsHtml,'</font>'],RowsPart)),
4091 ajoin(['<<font point-size="8" color="#707070">',ActKind,'</font><br/><b>',EID,'</b>',RowsPart,'>'],Label),
4092 ajoin_with_sep([ID|Rows],'\n',Tooltip),
4093 (Class=scheduled -> Attrs=[penwidth/2|LAttrs] ; Attrs=LAttrs),
4094 (get_preference(dot_print_legend,true) -> LAttrs=[legend/LegendText, legend_order/Order] ; LAttrs=[]).
4095
4096 simb_activation_class_colours(normal,'#E3EDF7','#1F5F99','activation',10).
4097 simb_activation_class_colours(scheduled,'#F3E5F5','#6A1B9A','currently scheduled activation',20).
4098 simb_activation_class_colours(internal,'#F5F5F5','#757575','setup/initialisation activation',30).
4099
4100 dot_activation_trans(_State,NodeID,SuccNodeID,[color/Col, fontcolor/Col, style/Style | Attrs]) :-
4101 simb_activation(NodeID,_,_ActKind),
4102 simb_activation_effect(NodeID,_Execute,_AddGuard,_TransSelection,_After,ActivationList),
4103 (member(SuccNodeID,ActivationList), simb_activation_id(SuccNodeID), Kind=activates, Attrs0=[]
4104 ; member(triggerActivation(SuccNodeID,_Params,Prob),ActivationList), % TODO: show params
4105 (Prob=none -> Kind=activates, Attrs0=[]
4106 ; get_simb_number_as_str(Prob,30,Label), Kind=probabilistic, Attrs0=[label/Label])
4107 ; member(List,ActivationList),member(chooseActivation(SuccNodeID,Prob),List),
4108 get_simb_number_as_str(Prob,30,Label), Kind=choice, Attrs0=[label/Label]
4109 ),
4110 simb_activation_edge_style(Kind,Col,Style,LegendText,Order),
4111 (get_preference(dot_print_legend,true) -> Attrs=[legend/LegendText, legend_order/Order|Attrs0] ; Attrs=Attrs0).
4112
4113 simb_activation_edge_style(activates,'#1F5F99',solid,'activates',50).
4114 simb_activation_edge_style(probabilistic,'#C77700',dashed,'activates with probability',60).
4115 simb_activation_edge_style(choice,'#6A1B9A',dashed,'chooses one activation with probability',70).
4116