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,
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
1526 bindings_to_state([], []).
1527 bindings_to_state([Binding|T], [Bind|NT]) :-
1528 (Binding = binding(Id,Val,_); Binding = bind(Id,Val)),
1529 Bind = bind(Id,Val),
1530 bindings_to_state(T, NT).
1531
1532 /* --------------------------------------------------------------------- */
1533
1534 tcltk_exists_an_open_node :-
1535 not_all_transitions_added(_) ; not_interesting(_).
1536 tcltk_goto_an_open_node :-
1537 (not_all_transitions_added(ID) ; not_interesting(ID)),!,
1538 tcltk_goto_state(find_open_node,ID).
1539 tcltk_goto_max_reached_node :-
1540 (max_reached_for_node(ID) ; time_out_for_node(ID)),!,
1541 tcltk_execute_trace_to_node(ID).
1542 tcltk_goto_timeout_node :-
1543 time_out_for_node(ID),!,
1544 tcltk_execute_trace_to_node(ID).
1545 % tcltk_goto_state(find_max_reached_node,ID).
1546
1547 tcltk_goto_an_invariant_violation :-
1548 invariant_violated(ID),!,
1549 tcltk_goto_state(find_inv_violation,ID).
1550
1551
1552 tcltk_goto_node_with_id(ToID) :-
1553 current_state_id(ToID),!.
1554 tcltk_goto_node_with_id(ID) :-
1555 visited_expression_id(ID),
1556 tcltk_execute_trace_to_node(ID).
1557
1558 tcltk_try_goto_node_with_id(ID) :-
1559 (tcltk_goto_node_with_id(ID) -> true
1560 ; add_internal_error('Call failed:',tcltk_goto_node_with_id(ID))).
1561
1562 /* --------------------------------------------------------------------- */
1563
1564 % TO DO: clean up and move into model_checker module
1565
1566 ?tcltk_state_space_only_has_root_node :- transition(root,_,ID),
1567 \+ not_all_transitions_added(ID),!,fail.
1568 tcltk_state_space_only_has_root_node.
1569
1570 tcltk_search_among_existing_nodes(TclTkRes,FindDeadlocks,FindInvViolations,
1571 FindGoal,FindAssViolations,FindStateErrors) :-
1572 search_among_existing_nodes(Res,FindDeadlocks,FindInvViolations,
1573 FindGoal,FindAssViolations,FindStateErrors),
1574 translate_error_for_tclk(Res,TclTkRes).
1575
1576 % 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
1577 % TODO: process mc_continue_after_error preference
1578 search_among_existing_nodes(invariant_violation,_FindDeadlocks,FindInvViolations,
1579 _FindGoal,_FindAssViolations,_FindStateErrors) :-
1580 (get_state_space_stats(_,_,PrN), PrN>100
1581 -> print_message('Search Among Processed Nodes'), print_message(number_of_nodes(PrN)) ; true),
1582 FindInvViolations=1,
1583 (invariant_violated(ResID) -> true
1584 ; find_invariant_violation_among_not_checked_nodes(ResID)),
1585 tcltk_execute_trace_to_node(ResID).
1586 search_among_existing_nodes(Error,_FindDeadlocks,FindInvViolations,
1587 _FindGoal,_FindAssViolations,_FindStateErrors) :-
1588 FindInvViolations=1,
1589 find_xtl_csp_invariant_violation_among_all_existing_nodes(ResID,Error), % could be xtl_error
1590 tcltk_execute_trace_to_node(ResID).
1591 search_among_existing_nodes(DEADLOCK,FindDeadlocks,_,_,_,_) :-
1592 FindDeadlocks=1,
1593 ? visited_expression_id(ResID),
1594 transitions_computed_for_node(ResID),
1595 is_deadlocked(ResID),
1596 (time_out_for_node(ResID)
1597 -> DEADLOCK = possible_deadlock_timeout
1598 ; get_preference(store_only_one_incoming_transition,true) -> DEADLOCK = possible_deadlock
1599 ; DEADLOCK = deadlock),
1600 print_message(deadlock_among_existing_nodes(ResID)),
1601 tcltk_execute_trace_to_node(ResID).
1602 search_among_existing_nodes(goal_found,_,_,FindGoal,_,_) :-
1603 FindGoal=1,
1604 %visited_expression(ResID,_CurState),
1605 %\+(not_all_transitions_added(ResID)), % if commented out: will also look at open nodes
1606 node_satisfies_goal(ResID),
1607 tcltk_execute_trace_to_node(ResID).
1608 search_among_existing_nodes(assertion_violation,_,_,_,FindAssViolations,_) :-
1609 FindAssViolations=1,
1610 b_machine_has_assertions,
1611 ? visited_expression(ResID,CurState),
1612 transitions_computed_for_node(ResID),
1613 state_violates_assertions(ResID,CurState),
1614 tcltk_execute_trace_to_node(ResID).
1615 search_among_existing_nodes(ERR,_,_,_,_,FindStateErrors) :- FindStateErrors=1,
1616 state_space:state_error(ResID,_,Error), Error \== invariant_violated,
1617 (Error = abort_error(ERR,_,_,_) -> true ; ERR = state_error(Error)),
1618 tcltk_execute_trace_to_node(ResID).
1619 search_among_existing_nodes(all,_,_,_,_,_).
1620
1621
1622 compute_all_transitions_if_necessary :-
1623 current_state_id(CurID),
1624 compute_all_transitions_if_necessary(CurID,false).
1625 :- public compute_all_transitions_if_necessary/1.
1626 compute_all_transitions_if_necessary(CurID) :-
1627 compute_all_transitions_if_necessary(CurID,false).
1628
1629 compute_all_transitions_if_necessary(CurID,CheckInvariant) :-
1630 (retract_open_node(CurID) % will assert not_invariant_checked
1631 -> set_context_state(CurID),
1632 % first check invariant, relevant if we want to use specialized_inv proof information
1633 visited_expression(CurID,State),
1634 % TO DO: this does not expand concrete_constants: the expansion may be done twice below:
1635 % once for compute_invariant (corresponds_to_b...) and once for compute_all_transitions (prepare_state_for_specfile_trans)
1636 prepare_state_for_specfile_trans(State,CurID,PreparedState),
1637 (CheckInvariant==true
1638 -> compute_invariant_if_necessary_and_requested(CurID,PreparedState) ; true),
1639 compute_all_transitions(CurID,PreparedState),
1640 clear_context_state
1641 ; true).
1642 %compute_all_transitions_if_necessary(CurID,CurState) :-
1643 % ((not_all_transitions_added(CurID);not_interesting(CurID))
1644 % -> compute_all_transitions(CurID,CurState) ; true).
1645
1646
1647 compute_invariant_if_necessary_and_requested(ID,State) :-
1648 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
1649 compute_invariant_if_necessary(ID,State),
1650 exit_error_scope(ErrScID,_ErrOcc,compute_invariant_if_necessary_and_requested). % should we do something with error occured result ?
1651
1652 compute_invariant_if_necessary(ID,State) :-
1653 animation_mode(MODE),compute_invariant_if_necessary(ID,State,MODE).
1654 compute_invariant_if_necessary(ID,State,MODE) :-
1655 ( check_invariantKO(MODE,ID,State) -> true ; true).
1656
1657 check_invariantKO(ID,State) :-
1658 animation_mode(MODE),check_invariantKO(MODE,ID,State).
1659 check_invariantKO(b,ID,State) :-
1660 check_invariantKO2(ID,State).
1661 check_invariantKO(csp_and_b,ID,State) :-
1662 check_invariantKO2(ID,State).
1663 % for XTL we do not use not_invariant_checked/1 facts; one should call xtl_invariant_violated/1
1664
1665 % check invariant for B state
1666 check_invariantKO2(ID,_) :- invariant_violated(ID),!.
1667 check_invariantKO2(ID,CurState) :-
1668 set_invariant_checked(ID), % only succeeds if we haven't checked invariant for ID yet
1669 % print(check_inv(ID)),nl,
1670 state_corresponds_to_initialised_b_machine(CurState),
1671 ( preferences:preference(do_invariant_checking,false) -> assertz(not_invariant_checked(ID))
1672 ; force_check_invariantKO(ID,CurState)).
1673
1674
1675 force_check_invariantKO(ID,CurBState) :-
1676 % Note: this checks the invariant without setting up a new error scope
1677 % (Reason: in the model checker it would be relatively expensive to set up an error scope for each state
1678 % the model checker stops anyway when the first error is found and then exits its error scope)
1679 catch_clpfd_overflow_call_for_state(ID, 'checking invariants',
1680 b_state_violates_invariant(ID,CurBState),true) ->
1681 %(b_state_violates_invariant(ID,CurBState) ->
1682 set_invariant_violated(ID).
1683 % TO DO ?: call state_satisfies_negation_of_invariant if double_evaluation_when_analysing is true ?
1684
1685 % try and find an invariant violation among those nodes that have not yet been checked
1686 find_invariant_violation_among_not_checked_nodes(ID) :-
1687 retract(not_invariant_checked(ID)), %print(checking_invariant(ID)),nl,
1688 visited_expression(ID,State),
1689 state_corresponds_to_initialised_b_machine(State),
1690 prepare_state_for_specfile_trans(State,ID,CurBState),
1691 force_check_invariantKO(ID,CurBState).
1692
1693 find_xtl_csp_invariant_violation_among_all_existing_nodes(ID,Error) :-
1694 animation_mode(MODE),
1695 (MODE=xtl ; MODE=csp), % invariant violations not stored, hence we need to re-check every node
1696 visited_expression(ID,State),
1697 find_invariant_error(MODE,ID,State,Error). % csp_error or xtl_error
1698
1699 :- use_module(probporsrc(ample_sets),[compute_ample_set2/3]).
1700 % computing ample sets (model_checker.pl)
1701 compute_ample_set(CurID,CurState,POROptions) :-
1702 catch_clpfd_overflow_call_for_state(CurID,'computing ample sets for POR',
1703 compute_ample_set2(CurID,CurState,POROptions),clear_context_state).
1704
1705
1706 %compute_all_transitions(CurID,CurState) :- get_preference(use_clpfd_solver,false),!,
1707 % compute_all_transitions2(CurID,CurState). % in principle this overflow cannot/should not happen with CLPFD FALSE
1708 % but no performance benefit can be measured by removing the catch
1709 compute_all_transitions(CurID,CurState) :-
1710 catch_clpfd_overflow_call_for_state(CurID,'computing all enabled transitions',
1711 compute_all_transitions2(CurID,CurState),clear_context_state).
1712
1713
1714 %catch_clpfd_overflow_call_for_state(_CurID, Call,_ExtraCleanUpCode) :-
1715 % preferences:preference(use_clpfd_solver,false),!, % Overflow should not occur
1716 % call(Call).
1717 :- use_module(clpfd_interface,[catch_clpfd_overflow_call2/2]).
1718 catch_clpfd_overflow_call_for_state(CurID, Context, Call,ExtraCleanUpCode) :-
1719 catch_clpfd_overflow_call2(Call,
1720 ( store_state_error(CurID,clpfd_overflow_error(Context),_),
1721 call(ExtraCleanUpCode)) ).
1722
1723
1724
1725
1726 :- use_module(probsrc(succeed_max),[reset_max_reached/0,max_reached/0, max_reached/1]).
1727 compute_all_transitions2(CurID,CurState) :- /* compute all outgoing transitions for a given node */
1728 % set_context_state(CurID), % error_context is set for each operation below anyway.
1729 reset_max_reached,
1730 prepare_state_for_specfile_trans(CurState,CurID,PreparedCurState), % will perform unpacking of constants just once, for example
1731 ((time_out_preference_disabled % e.g., when using probcli -disable_time_out
1732 ; use_no_timeout(CurID))
1733 -> add_transitions_fail_loop(CurID,PreparedCurState)
1734 ; preferences:preference(time_out,CurTO),
1735 add_transitions__with_timeout_fail_loop(CurID,PreparedCurState,CurTO)
1736 ),
1737 add_partial_transitions(CurID,PreparedCurState), % also copies unsat component infos
1738 (max_reached -> assert_max_reached_for_node(CurID),MaxReached=true ; MaxReached=false),
1739 % TO DO: use max_reached(OpID)
1740 (CurID==root -> save_constants(MaxReached) ; add_new_transitions_to_cache(CurID))
1741 . %,clear_context_state.
1742
1743 :- use_module(error_manager,[get_virtual_time_out_from_exception/2]). % used by time_out_with_enum_warning_for_findall
1744 % loop to compute successor states without a time_out
1745 add_transitions_fail_loop(CurID,CurState) :-
1746 catch(
1747 add_transitions_fail_loop2(CurID,CurState,TimeOutRes),
1748 Exc,
1749 get_virtual_time_out_from_exception(Exc,TimeOutRes)),
1750 (nonvar(TimeOutRes),
1751 (TimeOutRes=operation_time_out(Op,TimeOutRes2)
1752 -> assert_time_out_for_node(CurID,Op,TimeOutRes2)
1753 ; assert_time_out_for_node(CurID,'unspecified_operation',TimeOutRes))
1754 ; true).
1755
1756 add_transitions_fail_loop2(CurID,CurState,_) :-
1757 possible_trans_name_for_successors(CurState,ActionName),
1758 % we could check pge info here (e.g., store one Predecessor ID and look if ActionName can be enabled after)
1759 set_error_context(operation(ActionName,CurID)),
1760 add_transition(CurID,CurState,ActionName,_NewId), % TO DO: transmit animation_mode value?
1761 fail.
1762 add_transitions_fail_loop2(_,_,OpTimeOutRes) :-
1763 (enumeration_warning_occured_in_error_scope
1764 -> (virtual_time_out_occured_in_error_scope(TimeOutRes)
1765 -> % i.e., critical enumeration warning occurred
1766 (get_error_context(operation(ActionName,_))
1767 -> OpTimeOutRes = operation_time_out(ActionName,TimeOutRes)
1768 ; OpTimeOutRes = operation_time_out('unspecified_operation',TimeOutRes))
1769 ; true),
1770 clear_enumeration_warnings
1771 ; true % no warnings: sunshine case
1772 ),
1773 clear_error_context.
1774
1775 possible_trans_name_for_successors(CurState,ActionName) :-
1776 ? specfile_possible_trans_name_for_successors(CurState,ActionName),
1777 (preference(store_only_one_incoming_transition,true), % SAFETY_MODEL_CHECK
1778 nonvar(ActionName),
1779 b_or_z_mode,
1780 b_operation_cannot_modify_state(ActionName) % we have a skip operation
1781 -> operation_not_yet_covered(ActionName)
1782 % if operation covered: all we could is create a self-loop, which would not be added to the state space anyway
1783 ; true).
1784
1785
1786 :- use_module(library(timeout),[time_out/3]).
1787 my_timeout_test(1000000) :- write('.'), !, my_timeout_test(0).
1788 my_timeout_test(X) :- X1 is X+1, my_timeout_test(X1).
1789 :- public my_timeout_test/0.
1790 my_timeout_test :- time_out(my_timeout_test(0),500,TO), nl,
1791 print(time_out_result(TO)),nl, TO==time_out.
1792 :- assert_must_succeed(tcltk_interface:my_timeout_test).
1793
1794 add_transitions__with_timeout_fail_loop(CurID,CurState,CurTO) :-
1795 enter_new_error_scope(Level,add_transitions__with_timeout_fail_loop),
1796 call_cleanup(add_transitions__with_timeout_fail_loop2(Level,CurID,CurState,CurTO),
1797 exit_error_scope(Level,_,add_transitions__with_timeout_fail_loop)).
1798
1799 % old profiler
1800 :- use_module(runtime_profiler,[profile_failure_driven_loop/2]).
1801
1802 % the loop to compute all successors of state CurID with a time-out
1803 add_transitions__with_timeout_fail_loop2(Level,CurID,CurState,CurTO) :- % statistics(runtime,_),
1804 % TO DO: prepare computing the state: expanding const and vars, unpacking, ...
1805 ? possible_trans_name_for_successors(CurState,ActionName),
1806 profile_failure_driven_loop(ActionName,CurID),
1807 % Note: we enumerate possible transition names so that we can catch the time-out per name !
1808 % statistics(runtime,[T1,DeltaT]), print(delta_time(ActionName,DeltaT)),nl, %%
1809 % first enumerate possible Operations/... to obtain timeout per operation/...
1810 % TO DO: divide CurTO by number of transitions ???
1811 % We could also decide to have one time-out per state, only if that one is triggered move to
1812 % finer-grained timeouts
1813 % 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
1814 % In SICS 4.3.5 the runtime increased from 1.480 to 2.270 seconds = 0.022 ms per timeout call
1815 % In SICS 4.4.1 the runtime increased from 1.494 to 3.033 seconds. = 0.044 ms per timeout call.
1816 %% statistics(runtime,[T1,_]), print(try(ActionName,T1)),nl,%%
1817 set_error_context(operation(ActionName,CurID)),
1818 (nonvar(ActionName),translate_operation_name(ActionName,A2),
1819 get_specific_time_out_for_operation(A2,RealTimeOut) -> true ; RealTimeOut = CurTO),
1820 ? time_out_with_enum_warning_for_findall_in_current_error_scope(Level,
1821 (add_transition(CurID,CurState,ActionName,_NewId),fail), % fail inside meta-call;
1822 % so that time_out is for entire add_transition loop; not just for each single solution
1823 RealTimeOut,TimeOutRes),
1824 %% statistics(runtime,[T2,_]), TDiff is T2-T1, print(added_transition(CurID,ActionName,TDiff,TimeOutRes)),nl, %%
1825 %% add_transition(CurID,CurState,ActionName,_NewId) ,
1826 ((TimeOutRes==time_out ;
1827 nonvar(TimeOutRes),TimeOutRes=virtual_time_out(_), \+ max_reached(ActionName))
1828 % virtual time outs not relevant if we have already stopped earlier anyway;
1829 % TO DO: does not seem to work for INITIALISATION
1830 -> (TimeOutRes=virtual_time_out(_) -> true
1831 ; print_message('TIME OUT: '),print_message(CurID),
1832 print_message(RealTimeOut),print_message(ActionName)
1833 ),
1834 (var(ActionName)
1835 -> assert_time_out_for_node(CurID,'unspecified_operation',TimeOutRes)
1836 ; assert_time_out_for_node(CurID,ActionName,TimeOutRes) % TO DO: assert info per ActionSkeleton ?
1837 )
1838 ; true
1839 ),fail.
1840 add_transitions__with_timeout_fail_loop2(_,_,_,_) :- clear_error_context.
1841 % statistics(runtime,[_,DeltaT]), print(delta_time(end,DeltaT)),nl.
1842
1843 % compute and add transition to next states
1844 add_transition(CurID,CurState,ActionName,NewId) :-
1845 /* ActionName maybe pre-instantiated */
1846 extract_infos_from_prepared_state(CurState,PrecomputedInfos),
1847 ? specfile_trans(CurState,ActionName,Act,NewExpression,TransInfo,Residue),
1848 %% print_bt_message(specfile_trans(CurState,ActionName,Act,NewExpression,TransInfo,Residue)), %%
1849 add_trans_id_with_infos(CurID,PrecomputedInfos,Act,NewExpression,Residue,NewId,TransInfo,_).
1850
1851 :- use_module(kernel_tools,[add_call_residue_error/3]).
1852 % after being computed, add a new transition in the state space; adding the destination state if required
1853 add_trans_id_with_infos(CurID,PrecomputedInfos,Act,NewExpression,Residue,NewID,TransInfo,TransId) :-
1854 (Residue=[] -> true
1855 ; ajoin(['Prolog residue while computing transition ',Act,' in state ',CurID,':'],Msg),
1856 add_call_residue_error(add_trans_id,Msg,Residue)
1857 ),
1858 add_new_transition_transid_with_infos(CurID,PrecomputedInfos,Act,NewID,NewExpression,TransInfo,TransId).
1859
1860
1861
1862 add_trans_id(CurID,Act,NewExpression,NewID,TransId) :-
1863 add_trans_id_with_infos(CurID,[],Act,NewExpression,[],NewID,[],TransId).
1864
1865 add_trans_id_infos(CurID,Act,NewExpression,NewID,TransId,TransInfos) :-
1866 add_trans_id_with_infos(CurID,[],Act,NewExpression,[],NewID,TransInfos,TransId).
1867
1868 add_partial_transitions(root,CurState) :-
1869 % for the moment root is the only state where partial transitions are computed
1870 % note: some regular setup_constants transitions can cover partial_properties and are also partial transitions
1871 % (but which find values for all constants)
1872 ? \+ any_transition(root,_,_),
1873 % No transition was found, we try and extract deterministic values found for constants
1874 % and will add PARTIAL_SETUP_CONSTANTS if all constants valued or if preference allows it
1875 partial_trans(CurState,Act,NewExpression,Residue),
1876 add_trans_id_with_infos(root,[],Act,NewExpression,Residue,_NewID,[],_),fail.
1877 add_partial_transitions(_CurID,_).
1878
1879 /* --------------------------------------------------------------------- */
1880
1881 /* A bit like AO* algorithm: expands open nodes (i.e., states whose transitions
1882 have not yet been computed */
1883
1884 :- use_module(model_checker).
1885
1886 tcltk_model_check(Nr,TclTkRes,FindDeadlocks,FindInvViolations,FindGoal,FindAssViolations,
1887 FindStateErrors,StopFullCoverage,PartialOrderReduction,TIMELIMIT,TotalTime) :-
1888 statistics(walltime,[CurTime,_]), /* get current time in ms */
1889 LimitTime is CurTime+TIMELIMIT,
1890 %debug_println(10,start_tcltk_model_check(Nr,TIMELIMIT)),
1891 InspectExistingNodes = 0,
1892 (do_model_check(Nr,_A,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1893 FindAssViolations,FindStateErrors,StopFullCoverage,
1894 PartialOrderReduction,InspectExistingNodes)
1895 -> translate_error_for_tclk(Res,TclTkRes)
1896 ; add_internal_error('Call failed: ',do_model_check(Nr,_A,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1897 FindAssViolations,FindStateErrors,StopFullCoverage,
1898 PartialOrderReduction,InspectExistingNodes)),
1899 TclTkRes=error),
1900 statistics(walltime,[CurTime2,_]),
1901 TotalTime is CurTime2-CurTime,
1902 debug_println(10,tcltk_model_check(Nr,TotalTime,Res)).
1903
1904 translate_error_for_tclk([timeout,Nr],Res) :- !, Res=[timeout,Nr].
1905 translate_error_for_tclk(state_error(S),String) :- !, translate_state_err_for_tcltk(S,String).
1906 translate_error_for_tclk(S,R) :- atomic(S),!,R=S.
1907 translate_error_for_tclk(S,R) :- nonvar(S), add_error(translate_error_for_tclk,'Unknown Model Check result: ',S), R=unknown.
1908
1909 translate_state_err_for_tcltk(abort_error(TYPE,_,_,_),ERR) :- !, ERR = TYPE.
1910 translate_state_err_for_tcltk(eventerror(Event,Error,_),ERR) :- !,
1911 functor(Error,F,_),
1912 ajoin(['event_error:',Event,':',F],ERR).
1913 translate_state_err_for_tcltk(Error,ERR) :-
1914 functor(Error, StateError, _), atom_concat('state_error:',StateError,ERR).
1915
1916
1917
1918 do_model_check(_Nr,NodesAnalysed,_LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1919 FindAssViolations,FindStateErrors,_StopFullCoverage,
1920 _PartialOrderReduction,ForceInspectExistingNodes) :-
1921 (tcltk_state_space_only_has_root_node -> true % Then also look at the root node
1922 ; ForceInspectExistingNodes == 1),
1923 search_among_existing_nodes(Res,FindDeadlocks,FindInvViolations,FindGoal,
1924 FindAssViolations,FindStateErrors),
1925 Res \=all, NodesAnalysed=0.
1926 do_model_check(LimitNr,NodesAnalysed,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1927 FindAssViolations,FindStateErrors,StopFullCoverage,PartialOrderReduction,_) :-
1928 update_ass(FindAssViolations,FindAssViolations2),
1929 open_search(LimitNr,NodesAnalysed,LimitTime,Res,FindDeadlocks,FindInvViolations,FindGoal,
1930 FindAssViolations2,FindStateErrors,StopFullCoverage,PartialOrderReduction).
1931
1932 update_ass(1,FindAssViol) :- \+ b_machine_has_assertions,!, % no need to check assertions
1933 FindAssViol=0.
1934 update_ass(X,X).
1935
1936 /* --------------------------------------------------- */
1937
1938 /* constraint-based checking of refinements */
1939 :- use_module(symbolic_model_checker(cbc_refinement_checks), [cbc_refinement_check/2]).
1940 tcltk_cbc_refinement_check(list(List),ErrorOccured) :-
1941 cbc_refinement_check(List,ErrorOccured).
1942
1943 /* constraint-based/model search for invariant violations */
1944
1945 :- dynamic cbc_inv_error_found/2.
1946
1947 tcltk_constraint_based_check(L) :- tcltk_constraint_based_check(L,_).
1948 tcltk_constraint_based_check(list(List),ErrorsOrTimeoutWereFound) :-
1949 retractall(cbc_inv_error_found(_,_)),
1950 findall(Res, (tcltk_constraint_based_check_with_timeout(OpName,ErrorDesc),
1951 (ErrorDesc=ok -> true ; assertz(cbc_inv_error_found(OpName,ErrorDesc))),
1952 string_concatenate(' == ',ErrorDesc,Res1),
1953 string_concatenate(OpName,Res1,Res)), List),
1954 %%print(list(List)),nl, %%
1955 (cbc_inv_error_found(_,_) ->
1956 (cbc_inv_error_found(_,X),X\=time_out
1957 -> ErrorsOrTimeoutWereFound=true ; ErrorsOrTimeoutWereFound=time_out
1958 )
1959 ; ErrorsOrTimeoutWereFound = false).
1960
1961 % can also be called with uninstantiated OpName
1962 tcltk_constraint_based_check_with_timeout(OpName,ErrorDesc) :-
1963 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
1964 valid_operation_or_init(OpName,IOpName),
1965 (time_out_with_enum_warning_one_solution(tcltk_constraint_based_check_op(IOpName,ErrorDesc),DebugTimeOut,TimeOutRes)
1966 -> (is_time_out_result(TimeOutRes)
1967 -> print_message('TIME OUT: '), print_message(OpName), print_message(DebugTimeOut),
1968 ErrorDesc = time_out % callers (e.g., tcltk_constraint_based_check/2 and probcli) test for time_out
1969 ; true
1970 )).
1971 valid_operation_or_init(OpName,R) :- OpName=='@INITIALISATION',!,R='$initialise_machine'.
1972 valid_operation_or_init(OpName,OpName) :- b_get_machine_operation(OpName,_,_,_).
1973 valid_operation_or_init('INITIALISATION','$initialise_machine'). % used e.g. in test 1821: -cbc INITIALISATION
1974
1975 tcltk_constraint_based_check_op(OpName,ErrorDesc) :-
1976 tcltk_constraint_based_check_op(OpName,invariant,ErrorDesc).
1977
1978 tcltk_constraint_based_check_op(TclOpName,InvOrAssertion,ErrorDesc) :-
1979 adapt_tcl_operation_name(TclOpName,OpName),
1980 tcltk_constraint_based_check_op2(OpName,InvOrAssertion,ErrorDesc).
1981
1982 % code below because names with $ cause problems in Tcl with eval
1983 adapt_tcl_operation_name(X,R) :- var(X),!,R=X.
1984 adapt_tcl_operation_name('@PROPERTIES','$setup_constants') :- !.
1985 adapt_tcl_operation_name('@INITIALISATION','$initialise_machine') :- !.
1986 adapt_tcl_operation_name(X,X).
1987
1988 % a version that allows either invariant or assertions check after an Operation OpName
1989 tcltk_constraint_based_check_op2(OpName,InvOrAssertion,ErrorDesc) :-
1990 call_cbc_command(state_model_check(OpName,InvOrAssertion,State,Operation,NewState)),!,
1991 tcltk_add_cbc_state(State,'$JUMP'(constraint_based_check),PriorID), % will also set history
1992 translate_event(Operation,Action),
1993 tcltk_add_new_transition_transid(PriorID,Operation,NewID,NewState,[],TransId2),
1994 set_current_state_id(NewID),
1995 add_to_op_trace_ids(TransId2),
1996 add_id_to_history(PriorID),
1997 ajoin([InvOrAssertion,'_violated_after(',Action,')'],ErrorDesc).
1998 tcltk_constraint_based_check_op2(_,_,'ok').
1999
2000
2001 % try to find constants, parameters that make a given trace feasible
2002 tcltk_cbc_find_trace(TraceToBeFound,Res) :-
2003 tcltk_cbc_find_trace(TraceToBeFound,'',first_solution,Res).
2004
2005 %:- public tcltk_cbc_find_invariant_violation/2.
2006 %tcltk_cbc_find_invariant_violation(TraceToBeFound,Res) :-
2007 % tcltk_cbc_find_trace(TraceToBeFound,'#not_invariant',first_solution,Res).
2008 % could also call tcltk_constraint_based_check_op('$initialise_machine',invariant,Res)
2009
2010 tcltk_cbc_find_trace(TraceToBeFound,TargetPredString,FindAll,Res) :-
2011 b_parse_optional_machine_predicate(TargetPredString,TargetPred),
2012 formatsilent('Looking for solution for trace ~w~n',[TraceToBeFound]),
2013 split_atom(TraceToBeFound,[',',';',' '],TraceAsList),
2014 (maplist(check_valid_operation,TraceAsList)
2015 -> start_ms_timer(Timer),
2016 tcltk_cbc_find_trace_aux(Timer,TraceAsList,TargetPred,FindAll,Res)
2017 ; Res = error).
2018 % findall mode: find all paths; time_out_with_enum_warning_one_solution would cut after the first solution
2019 tcltk_cbc_find_trace_aux(Timer,TraceAsList,TargetPred,findall,Res) :- !,
2020 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
2021 reset_nr_cbc_sols,
2022 retractall(cbc_find_all_time_out_occurred),
2023 (time_out_with_enum_warning_for_findall(
2024 cbc_path_solver:create_testcase_path_nondet(init,TraceAsList,TargetPred,Transitions),DebugTimeOut,TimeOutRes),
2025 (is_time_out_result(TimeOutRes)
2026 -> print_message('*** TIME OUT: '), print_message(DebugTimeOut),
2027 assertz(cbc_find_all_time_out_occurred)
2028 ; inc_nr_cbc_sols,
2029 print('% *** FOUND PATH: '), maplist(print_trans,Transitions),nl
2030 ),
2031 fail % backtrack to find further solutions; we do not cut so that the error scope is exited properly
2032 ; true),
2033 stop_ms_timer(Timer),
2034 (retract(cbc_find_all_time_out_occurred)
2035 -> Res = time_out
2036 ; nr_cbc_sols(N), Res=nr_cbc_sols(N),
2037 print_message('*** ALL SOLUTIONS FOUND ')
2038 ).
2039 tcltk_cbc_find_trace_aux(Timer,TraceAsList,TargetPred,_,Res) :-
2040 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
2041 reset_nr_cbc_sols,
2042 time_out_with_enum_warning_one_solution(
2043 cbc_path_solver:create_testcase_path_nondet(init,TraceAsList,TargetPred,Transitions),DebugTimeOut,TimeOutRes),
2044 stop_ms_timer(Timer),
2045 (is_time_out_result(TimeOutRes)
2046 -> !,
2047 print_message('*** TIME OUT: '), print_message(DebugTimeOut), Res = time_out
2048 ; !,Res = ok,
2049 print('% *** FOUND PATH: '), maplist(print_trans,Transitions),nl,
2050 maplist(extract_trans_id,Transitions,TransIds),
2051 set_trace_by_transition_ids(TransIds)
2052 ).
2053 tcltk_cbc_find_trace_aux(Timer,_TraceToBeFound,_TargetPred,_FindAll,no_solution_found) :-
2054 stop_ms_timer(Timer),
2055 print_message('*** NO SOLUTION FOUND'),nl.
2056
2057 :- dynamic cbc_find_all_time_out_occurred/0.
2058 :- dynamic nr_cbc_sols/1.
2059 nr_cbc_sols(0).
2060 reset_nr_cbc_sols :- retractall(nr_cbc_sols(_)), assertz(nr_cbc_sols(0)).
2061 inc_nr_cbc_sols :-
2062 retract(nr_cbc_sols(N)), N1 is N+1, assertz(nr_cbc_sols(N1)).
2063 extract_trans_id( (TransId,_,_,_), TransId).
2064 print_trans( (_,Event,_,_)) :- translate_event(Event,S), print(S), print(' ').
2065
2066 :- use_module(probsrc(tools_matching), [get_possible_top_level_event_matches_msg/2]).
2067 check_valid_operation(Op) :-
2068 (get_possible_language_specific_top_level_event(Op,_,_) -> true
2069 ; (get_possible_top_level_event_matches_msg(Op,FMsg)
2070 -> ajoin(['Unknown operation/event (did you mean ',FMsg,' ?):'],Msg)
2071 ; Msg='Unknown operation/event:'
2072 ),
2073 add_error(cbc_find_sequence,Msg,Op),
2074 fail
2075 ).
2076
2077 tk_get_possible_language_specific_top_level_event(OpName,list(ResultNames),list(ParameterNames)) :-
2078 get_possible_language_specific_top_level_event(OpName,ResultNames,ParameterNames).
2079
2080
2081 % ------------
2082
2083 :- use_module(bsyntaxtree).
2084 tcltk_constraint_find_valid_state_with_pred(ParameterBindList,RestPreCond,UseConstantsFromStateID) :-
2085 parse_tclk_parameter_values_and_pred('$initialise_machine',ParameterBindList,RestPreCond,CustomPredicate),
2086 UseInvariant=true,
2087 call_cbc_command(
2088 b_state_model_check:b_set_up_valid_state_with_pred(State,CustomPredicate,
2089 UseInvariant,UseConstantsFromStateID)),
2090 tcltk_add_cbc_state(State,find_valid_state).
2091 tcltk_constraint_find_valid_state :-
2092 call_cbc_command(b_set_up_valid_state(State)),
2093 tcltk_add_cbc_state(State,find_valid_state).
2094
2095 :- use_module(extrasrc(optimizing_solver),[b_set_up_maximally_valid_state/2]).
2096 tcltk_constraint_find_maximal_valid_state :-
2097 current_state_id(ID),
2098 call_cbc_command(b_set_up_maximally_valid_state(ID,State)),
2099 tcltk_add_cbc_state(State,find_maximal_valid_state).
2100
2101
2102 tcltk_constraint_find_dynamic_assertion_violation :-
2103 call_cbc_command(b_find_dynamic_assertion_violation(State)),
2104 tcltk_add_cbc_state(State,cbc_dynamic_assertions_check).
2105
2106 :- use_module(clpfd_interface,[catch_clpfd_overflow_call1/1]).
2107 :- use_module(error_manager,[call_in_fresh_error_scope_for_one_solution/1]).
2108 % catch CLPFD overflows and catch other errors
2109 call_cbc_command(Command) :-
2110 call_in_fresh_error_scope_for_one_solution(
2111 (catch_clpfd_overflow_call1(Command) -> true
2112 ; translate_events_in_current_scope_to_warnings(cbc,'Warning: '),fail
2113 % Maybe we should raise error when Command fails and enumeration warnings are there ?
2114 )).
2115
2116
2117 tcltk_constraint_find_deadlock_state(Res) :-
2118 check_we_are_in_b_mode(cbc_deadlock_freedom_check),
2119 create_texpr(truth,pred,[],True),
2120 call_cbc_command(cbc_deadlock_freedom_check(State,True,0)),
2121 (State == time_out -> Res = time_out
2122 ; tcltk_add_cbc_state(State,cbc_deadlock), Res=deadlock).
2123
2124 % if Filter=1 we remove guards which are inconsitent with goal
2125 tcltk_constraint_find_deadlock_state_with_goal(Filter,Res) :-
2126 check_we_are_in_b_mode(cbc_deadlock_freedom_check),
2127 (b_get_machine_goal(Goal) -> true ; create_texpr(truth,pred,[],Goal)),
2128 call_cbc_command(cbc_deadlock_freedom_check(State,Goal,Filter)),
2129 (State == time_out -> Res = time_out
2130 ; tcltk_add_cbc_state(State,cbc_deadlock), Res=deadlock).
2131
2132 check_we_are_in_b_mode(_) :- b_or_z_mode,!.
2133 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.
2134
2135 tcltk_constraint_find_deadlock_state_with_goal(true,_Filter,Res) :-
2136 !,tcltk_constraint_find_deadlock_state(Res).
2137 tcltk_constraint_find_deadlock_state_with_goal(GoalPred,Filter,Res) :-
2138 bmachine:b_set_machine_goal(GoalPred),
2139 tcltk_constraint_find_deadlock_state_with_goal(Filter,Res).
2140
2141 :- use_module(cbcsrc(enabling_analysis),[check_if_feasible_operation/5]).
2142 tcltk_check_if_feasible_operation(OpName,UseInvariant,TimeOutFactor,Result) :- % UseInvariant currently always 1 from Tcl
2143 check_if_feasible_operation(OpName,UseInvariant,TimeOutFactor,Result,ResultState),
2144 tcltk_add_cbc_state(ResultState,feasibility_check(OpName)).
2145
2146 % add a state found by constraint-based verification or other method that tries to jump to a state without all intermediate steps
2147 % it will add a separate concrete_constants state if necessary
2148 tcltk_add_cbc_state(State,OpName) :-
2149 tcltk_add_cbc_state(State,'$JUMP'(OpName),_ToID).
2150
2151 tcltk_add_cbc_state('$UNKNOWN_STATE',_,To) :- !,To=none.
2152 tcltk_add_cbc_state(State,OpNameTerm,NewID) :-
2153 seperate_state_into_const_and_vars(State,Constants,Variables),
2154 !,
2155 % store the constants separately: important for memory consumption when continuing animation/model checking
2156 (Variables=[] -> Op='$initialise_machine' ; Op = OpNameTerm),
2157 % if Variables are [] we simply create an initialisation transition
2158 (Constants = [] % no need to create SETUP_CONSTANTS transition
2159 -> (Variables = [] % probably prior state for INITIALISATION cbc check
2160 -> NewID=root, set_cbc_state(root,[],[])
2161 ; FullState = Variables,
2162 tcltk_add_new_transition_transid(root,Op,NewID,FullState,[],TransId2),
2163 set_cbc_state(NewID,[TransId2],[root])
2164 )
2165 ; Variables = [], b_machine_has_variables
2166 -> % only constant values, e.g., counterexample for static assertions: we cannot construct an initialised state
2167 tcltk_add_new_transition_transid(root,'$setup_constants',NewID,concrete_constants(Constants),[],TransId1),
2168 set_cbc_state(NewID,[TransId1],[root])
2169 ; tcltk_add_new_transition_transid(root,'$setup_constants',CstID,concrete_constants(Constants),[],TransId1),
2170 FullState = const_and_vars(CstID,Variables),
2171 tcltk_add_new_transition_transid(CstID,Op,NewID,FullState,[],TransId2),
2172 set_cbc_state(NewID,[TransId1,TransId2],[CstID,root])
2173 ).
2174 tcltk_add_cbc_state(State,OpNameTerm,NewID) :-
2175 tcltk_add_new_transition_transid(root,OpNameTerm,NewID,State,[],TransId),
2176 set_cbc_state(NewID,[TransId],[root]).
2177
2178
2179 set_cbc_state(NewID,TransIds,His) :-
2180 set_current_state_id(NewID),
2181 reset_op_trace_ids,
2182 maplist(add_to_op_trace_ids,TransIds),
2183 retractall(history(_)),
2184 retractall(forward_history(_)),
2185 assertz(history(His)). %, print(State),nl.
2186
2187 is_constant_binding(SortedCsts,bind(ID,_)) :-
2188 ord_member(ID,SortedCsts).
2189
2190 :- use_module(bsyntaxtree, [get_texpr_ids/2]).
2191 seperate_state_into_const_and_vars(concrete_constants(C),Constants,Variables) :- !,
2192 Constants=C, Variables=[].
2193 seperate_state_into_const_and_vars(State,Constants,Variables) :-
2194 b_get_machine_constants(TCs), get_texpr_ids(TCs,Cs),
2195 sort(Cs,SortedCsts),
2196 include(is_constant_binding(SortedCsts),State,Constants),
2197 Constants \= [],
2198 exclude(is_constant_binding(SortedCsts),State,Variables).
2199
2200
2201
2202 tcltk_constraint_find_static_assertion_violation(TclResult) :-
2203 cbc_constraint_find_static_assertion_violation(Result,[]),
2204 functor(Result,TclResult,_).
2205 cbc_constraint_find_static_assertion_violation(Result,Options) :-
2206 call_cbc_command(cbc_static_assertions_check(State,Options)),
2207 ( State = counterexample_found(CE) ->
2208 Result = counterexample_found,
2209 tcltk_add_cbc_state(CE,static_assertion_check)
2210 ;
2211 Result = State).
2212
2213 /* --------------------------------------------------- */
2214
2215
2216 :- use_module(error_manager,[extract_all_line_col/5]).
2217 :- use_module(probcspsrc(haskell_csp),[extract_span_from_event/4,extract_span_info/2]).
2218
2219 get_source_text_positions(Event,Line,Col,EndLine,EndCol) :-
2220 extract_span_from_action(Event,SPAN),
2221 extract_all_line_col(SPAN,Line,Col,EndLine,EndCol).
2222
2223 extract_span_from_action(Event,Span) :- csp_mode,
2224 extract_span_from_event(Event,Span,_,_).
2225 extract_span_from_action(Event,Pos) :- b_or_z_mode,
2226 get_operation_name(Event,ID),
2227 % TODO: prob_source_profiling_on SOURCE_PROFILING_INFO, add_source_location_hits
2228 b_get_machine_operation(ID,_Res,_TParas,_Body,_OType,Pos).
2229
2230
2231 /* -------------------------------------------------------------------- */
2232
2233 get_current_option_eventtrace(OptionNum,TraceInfo) :-
2234 % the option number starts with 0 (coming from a TK listbox)
2235 current_options(ActionsAndIDs),
2236 nth0(OptionNum,ActionsAndIDs,(Id,_,_,_)),
2237 transition_info(Id,TraceInfo),
2238 transition_info_can_be_shown(TraceInfo),!.
2239
2240 transition_info_can_be_shown(eventtrace(_)).
2241 transition_info_can_be_shown(path(_)).
2242
2243
2244 tcltk_has_eventtrace(OptionNum) :-
2245 get_current_option_eventtrace(OptionNum,_Trace).
2246
2247 tcltk_show_eventtrace(OptionNum,Desc) :-
2248 get_current_option_eventtrace(OptionNum,Trace),
2249 explain_transition_info(Trace,Desc).
2250
2251
2252
2253 /* --------------------------------------------------- */
2254
2255 :- use_module(prob2_interface,[execute_model/5]).
2256
2257 tcltk_execute_model(MaxNrSteps,ExecutedSteps,Result) :-
2258 current_state_id(CurID),
2259 execute_model(CurID,MaxNrSteps,_TransitionInfo,ExecutedSteps,Result).
2260
2261
2262 tcltk_find_shortest_trace_to_current_node(list(StringList)) :-
2263 find_trace_to_current_node(OpL),
2264 translate_events(OpL,StringList).
2265
2266
2267 tcltk_execute_trace_to_current_node :-
2268 current_state_id(CurID),
2269 tcltk_execute_trace_to_node(CurID).
2270
2271 tcltk_execute_trace_to_node(ToID) :- /* can be useful for TestCase Generation */
2272 set_target_id(ToID),
2273 tcltk_execute_trace_from_to_found_predicate(root,_,_).
2274
2275 % execcute longest loop-free trace (no repeated state)
2276 tcltk_execute_longest_trace_from(From) :-
2277 set_longest_trace_target,
2278 tcltk_execute_trace_from_to_found_predicate(From,_,_).
2279
2280 % OpL is list of operation ids, IDList is list of state ids
2281 tcltk_execute_trace_from_to_found_predicate(From,OpL,IDList) :-
2282 debug_println(19,finding_trace_from_to(From)), flush_output(user),
2283 find_shortest_path_from_to_found_predicate(From,OpL,IDList,ToID), !,
2284 (current_state_id(From) -> true ; state_space_reset),
2285 debug_println(9,executing_trace(From,OpL,ToID)), flush_output(user),
2286 execute_id_trace_from_current(ToID,OpL,IDList).
2287
2288
2289 find_trace_to_current_node(Trace) :-
2290 current_state_id(CurID),
2291 find_shortest_path_from_to(root,CurID,L,_),
2292 extract_term_trace_from_transition_ids(L,Trace).
2293
2294 :- use_module(state_space_dijkstra).
2295
2296 find_shortest_trace_to_node(FromID,ToID,OpIDListe,StateIDList) :-
2297 find_shortest_path_from_to(FromID,ToID,OpIDListe,StateIDList).
2298
2299
2300 /* --------------------------------------------------- */
2301
2302
2303
2304 tcltk_goto_a_non_deterministic_node(Msg) :- /* same transition leads to different resulting state */
2305 visited_expression_id(ID),
2306 external_functions:non_det_transition(ID,_OpName,TID1,TID2),
2307 tcltk_execute_trace_to_node(ID),
2308 transition(ID,Op1,TID1,ID1),
2309 transition(ID,_Op2,TID2,ID2),
2310 translate_event_with_src_and_target_id(Op1,ID,ID1,OpStr),
2311 ajoin(['Operation leads to at least two different states (ids ', ID1,', ',ID2,
2312 ') for same arguments: ', OpStr], Msg).
2313
2314 tcltk_goto_a_non_deterministic_output_node(Msg) :- /* same transition leads to different outputs */
2315 visited_expression_id(ID),
2316 external_functions:non_det_output_transition(ID,_OpName,TID1,TID2),
2317 tcltk_execute_trace_to_node(ID),
2318 transition(ID,Op1,TID1,ID1),
2319 transition(ID,Op2,TID2,ID2),
2320 translate_event_with_src_and_target_id(Op1,ID,ID1,OpStr1),
2321 translate_event_with_src_and_target_id(Op2,ID,ID2,OpStr2),
2322 ajoin(['Operation has at least two different results for same arguments: ', OpStr1,
2323 '\n and ',OpStr2], Msg).
2324
2325 dif_ID(ID1,ID2) :- (number(ID1),number(ID2) -> ID2>ID1 ; ID1 \= ID2).
2326
2327 tcltk_goto_a_branching_node :- /* two different events/operations enabled */
2328 transition(ID,X,ID2), get_operation_name(X,NX),
2329 transition(ID,Y,ID3), dif_ID(ID2,ID3), get_operation_name(Y,NY), NX\=NY,
2330 print_message(found_branching_op(ID,NX,NY)),
2331 %tcltk_goto_state(find_branching_node,ID),
2332 tcltk_execute_trace_to_node(ID).
2333
2334 tcltk_goto_a_non_resetable_node :-
2335 find_resetable_nodes,
2336 visited_expression_id(ID),
2337 ID \== root, % root has no incoming transitions and is thus never marked as resetable
2338 \+(resetable_node(ID)),
2339 \+(not_all_transitions_added(ID)), !,
2340 %tcltk_goto_state(find_non_resetable_node,ID).
2341 tcltk_execute_trace_to_node(ID).
2342
2343 :- use_module(bmachine,[b_get_machine_operation_for_animation/4]).
2344 operation_name_covered(OpName) :- operation_name_covered(OpName,_).
2345 operation_name_covered(OpName,Template) :-
2346 b_get_machine_operation_for_animation(OpName,Results,Par,_),
2347 \+ operation_not_yet_covered(OpName),
2348 length(Par,Arity),
2349 functor(Op,OpName,Arity),
2350 (Results\=[] -> Template = '-->'(Op,_) ; Template = Op).
2351
2352 tcltk_goto_event_list_property_violation(Property,EventSelection,list(OperationList)) :-
2353 % first translate Tk EventSelection Number list into Events
2354 sap:get_selected_events(EventSelection,_AllEvents,OperationList),
2355 include(operation_name_covered,OperationList,_,EnabledOpList), % only keep operations that can be enabled anyway
2356 maplist(operation_name_covered,EnabledOpList,TemplateList), % replace by template
2357 debug_println(9,find_property_violation_for_template(Property,TemplateList)),
2358 visited_expression(ID,S), ID \= root, S\= concrete_constants(_),
2359 \+(not_all_transitions_added(ID)),
2360 \+( check_event_list_property(Property,ID,TemplateList) ),
2361 debug_println(9,found_event_list_property_violation(Property,ID)),
2362 tcltk_execute_trace_to_node(ID).
2363
2364 check_event_list_property(relative_deadlock_freedom,ID,TemplateList) :-
2365 relative_deadlock_freedom(ID,TemplateList).
2366 check_event_list_property(valid_controller,ID,TemplateList) :-
2367 is_valid_controller_state(ID,TemplateList).
2368 check_event_list_property(det_controller,ID,TemplateList) :-
2369 is_det_controller_state(ID,TemplateList).
2370
2371 relative_deadlock_freedom(ID,TemplateList) :- member(Template,TemplateList),
2372 transition(ID,Template,_).
2373 is_valid_controller_state(ID,TemplateList) :- % check that exactly one event from TemplateList is enabled
2374 append(_,[LiveEvent|RestTemplate],TemplateList),
2375 transition(ID,LiveEvent,_),!, % we found one enabled event
2376 \+ relative_deadlock_freedom(ID,RestTemplate). % all other events from list must be disabled
2377 is_det_controller_state(ID,TemplateList) :- % check that *at most* one event from TemplateList is enabled
2378 append(_,[LiveEvent|RestTemplate],TemplateList),
2379 transition(ID,LiveEvent,_),!, % we found one enabled event from list
2380 \+ relative_deadlock_freedom(ID,RestTemplate). % all other events from list must be disabled
2381 is_det_controller_state(_,_) :- true. % no event enabled is also ok
2382
2383
2384 tcltk_goto_state_enabling_operation(TclOpName,FromCurrent) :-
2385 adapt_tcl_operation_name(TclOpName,OpName),
2386 operation_name_covered(OpName,Template), % does cater for Event-B any vars
2387 set_found_predicate(ID, transition(ID,Template,_)),
2388 print_message('Computing trace to node'),
2389 (FromCurrent=1
2390 -> current_state_id(FromID) % inefficient: better to do one dijkstra from FromID !
2391 ; FromID = root
2392 ),
2393 tcltk_execute_trace_from_to_found_predicate(FromID,_,_).
2394 % tcltk_goto_state(find_enabled(OpName),ID).
2395
2396
2397 :- use_module(tools_lists,[count_occurences/2]).
2398 % quickly compute which operations have already been covered and which ones not
2399 tcltk_operations_covered_info(list([list(['Operation','Covered'])|OpCov]),list(Occurences),Precise) :-
2400 findall(list([OpName,Cov]),
2401 (specfile:get_possible_event(OpName),
2402 (operation_name_not_yet_covered(OpName)
2403 -> not_yet_covered_info(Precise,OpName,Cov)
2404 ; Cov = 'yes')),OpCov),
2405 (maplist(get_cov,OpCov,Cov2),
2406 count_occurences(Cov2,Occ2),
2407 maplist(construct_list,Occ2,Occurences) -> true ; Occurences=[]).
2408
2409 get_cov(list([_,Cov|_]),Cov).
2410 construct_list(Kind-Nr,list([Kind,Nr])).
2411
2412 :- use_module(cbcsrc(enabling_analysis),[feasible_operation/2]).
2413 not_yet_covered_info(precise,OpName,Cov) :-
2414 feasible_operation(OpName,Res),!, Res=Cov.
2415 not_yet_covered_info(precise,_,R) :- !, R='unknown'.
2416 not_yet_covered_info(_,_,'uncovered').
2417
2418 :- dynamic resetable_node/1.
2419
2420 resetable_node(a).
2421
2422 :- public find_resetable_nodes/0.
2423 :- dynamic find_flag/2.
2424 find_resetable_nodes :-
2425 retractall(find_flag(_,_)),
2426 retractall(resetable_node(_)),
2427 any_transition(root,_,ID), /* add nodes reachable from root */
2428 assertz(find_flag(ID,0)),
2429 fail.
2430 find_resetable_nodes :-
2431 visited_expression(CID,concrete_constants(_C)),
2432 any_transition(CID,_,ID), /* add nodes reachable after a setup_constants */
2433 assertz(find_flag(ID,0)),
2434 fail.
2435 find_resetable_nodes :- find_resetable_nodes_loop,
2436 debug_println(9,'Not resetable:'),
2437 visited_expression_id(ID),
2438 \+(resetable_node(ID)),
2439 debug_println(9,ID),
2440 fail.
2441 find_resetable_nodes :-
2442 debug_println(9,'Done').
2443
2444
2445 find_resetable_nodes_loop :-
2446 retract(find_flag(ID,N)), !, find_resetable_nodes_loop(ID,N).
2447 find_resetable_nodes_loop.
2448
2449 find_resetable_nodes_loop(ID,N) :- N1 is N+1,
2450 assertz(resetable_node(ID)),
2451 any_transition(NewID,_,ID),
2452 \+(resetable_node(NewID)),
2453 \+(find_flag(NewID,_)),
2454 assertz(find_flag(NewID,N1)),
2455 fail.
2456 find_resetable_nodes_loop(_,_) :- find_resetable_nodes_loop.
2457
2458
2459 :- use_module(specfile, [get_current_state_for_b_formula/2]).
2460
2461 tcltk_show_expression_as_dot(VorE,File) :-
2462 parse_machine_expression(VorE,TypedExpr),
2463 tcltk_show_typed_expression_as_dot_graph(TypedExpr,File).
2464 tcltk_show_expression_as_dot(_VorE,File) :-
2465 add_error(tcltk_show_expression_as_dot,'Computing Value Dot Representation Failed for: ',File),
2466 fail.
2467
2468 :- use_module(dotsrc(state_as_dot_graph),[print_cstate_graph/2]).
2469 :- use_module(dotsrc(state_custom_dot_graph),[tcltk_generate_state_custom_dot_graph_for_expr/2, is_valid_custom_dot_graph_record/1]).
2470
2471 tcltk_show_typed_expression_as_dot_graph(TypedExpr,File) :-
2472 is_valid_custom_dot_graph_record(TypedExpr),
2473 !, % use the more powerful custom_dot_graph mechanism
2474 tcltk_generate_state_custom_dot_graph_for_expr(TypedExpr,File).
2475 tcltk_show_typed_expression_as_dot_graph(TypedExpr,File) :-
2476 get_current_state_for_b_formula(TypedExpr,BState),
2477 extend_state_with_probids_and_lets(BState,BState1),
2478 decompose_expression_for_dot(TypedExpr,ExprList,[]), % decompose pairs so that user can provide multiple values/graphs
2479 compute_for_dot(ExprList,BState1,GraphState), % compute value for each sub-component
2480 format('Writing value to DOT file: ~w~n',[File]),
2481 print_cstate_graph(GraphState,File),
2482 format('Finished writing value to DOT file: ~w~n',[File]).
2483
2484
2485 :- use_module(eval_let_store,[extend_typing_scope_for_stored_lets/2]).
2486 :- use_module(bmachine, [b_parse_machine_expression_from_codes_with_prob_ids/2, type_with_errors/4]).
2487 parse_machine_expression(RawAST,TypedExpr) :- compound(RawAST),!, % allow to pass raw AST as well
2488 extend_typing_scope_for_stored_lets([prob_ids(visible),variables,external_library(safe_available_libraries)],Scope),
2489 type_with_errors(RawAST,Scope,Type,TypedExpr),
2490 % TODO: get_stored_let_typing_scope and add values to state returned by get_current_state_for_b_formula
2491 ((Type=pred ; Type=subst)
2492 -> add_error(parse_machine_expression,'Expected expression formula but obtained: ',Type),fail
2493 ; true ).
2494 parse_machine_expression(VorE,TypedExpr) :-
2495 atom_codes(VorE,VorECodes),
2496 b_parse_machine_expression_from_codes_with_prob_ids(VorECodes,TypedExpr).
2497
2498 compute_for_dot([],_,[]).
2499 compute_for_dot([String,TypedExpr|Tail],BState,[bind(Str,Value)|TS]) :-
2500 % allow user to specify labels for graphs ("lbl1", e1, "lbl2", e2, ...)
2501 get_texpr_expr(String,string(Str)),!,
2502 translate:translate_bexpression_with_limit(TypedExpr,100,EStr),
2503 format('Computing value for expression: ~w~n',[EStr]),
2504 b_compute_expression_with_prob_ids(TypedExpr,BState,Value),
2505 compute_for_dot(Tail,BState,TS).
2506 compute_for_dot([TypedExpr|Tail],BState,[bind(Str,Value)|TS]) :-
2507 translate:translate_bexpression_with_limit(TypedExpr,100,Str),
2508 format('Computing value for expression: ~w~n',[Str]),
2509 b_compute_expression_with_prob_ids(TypedExpr,BState,Value),
2510 compute_for_dot(Tail,BState,TS).
2511
2512 :- use_module(bsyntaxtree, [replace_ids_by_exprs/4]).
2513
2514 % decompose_expression_for_dot ensures that
2515 % ("label1",graph1,"lbl2",graph2) or rec(label:graph) is decomposed and we can associate labels with multiple graphs
2516 decompose_expression_for_dot(b(couple(A,B),_,_)) --> !,
2517 decompose_expression_for_dot(A), decompose_expression_for_dot(B).
2518 decompose_expression_for_dot(b(rec(Fields),_,_)) --> !,decompose_fields_for_dot(Fields).
2519 decompose_expression_for_dot(b(let_expression(Ids,Exprs,Body),couple(_,_),_)) --> !,
2520 % this can happen when OPTIMIZE_AST is set to FALSE and the Jupyter kernel adds LETs; lift string out of let
2521 % :dot expr_as_graph ("h",h,"hh",(h;h))
2522 {replace_ids_by_exprs(Body,Ids,Exprs,Body2)},
2523 decompose_expression_for_dot(Body2).
2524 decompose_expression_for_dot(X) --> [X].
2525
2526
2527 decompose_fields_for_dot([]) --> [].
2528 decompose_fields_for_dot([field(Name,Val)|T]) --> [b(string(Name),string,[]),Val], decompose_fields_for_dot(T).
2529
2530 /* ------------------------------------------------------------------ */
2531
2532 % aka Execute by Predicate
2533 tcltk_add_user_executed_operation(TclOpName,CustomPredicate) :-
2534 tcltk_add_user_executed_operation(TclOpName,[],CustomPredicate).
2535
2536 tcltk_add_user_executed_operation(TclOpName,ParameterBindList,RestPreCond) :-
2537 adapt_tcl_operation_name(TclOpName,OpName),
2538 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate),
2539 current_state_id(CurID),
2540 get_computed_preference(debug_time_out,DTO),
2541 time_out_with_enum_warning_one_solution(b_trans_one_solution_with_pred(OpName,CustomPredicate,CurID,_,_,_),
2542 DTO,TimeOutRes),
2543 (is_time_out_result(TimeOutRes)
2544 -> add_warning(execute_by_predicate,'Timeout occured trying to execute operation with predicate: ',TclOpName),fail
2545 ; true).
2546
2547 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate) :-
2548 GenParseErrors=true,
2549 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate,GenParseErrors).
2550 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate,GenParseErrors) :-
2551 ExtraScope=[],
2552 b_parse_machine_operation_pre_post_predicate(RestPreCond,ExtraScope,RestTypedPred,OpName,GenParseErrors),
2553 (ParameterBindList=[] -> CustomPredicate = RestTypedPred
2554 ; get_animation_operation_parameters(OpName,Parameters),
2555 % print(tcltk_add_user_executed_operation(OpName,ParameterBindList,Parameters)),nl,
2556 parse_parameter_values(ParameterBindList,OpName,Parameters,List),
2557 conjunct_predicates([RestTypedPred|List],CustomPredicate)
2558 ).
2559
2560 :- use_module(bmachine,[b_get_machine_operation_for_animation/7]).
2561 get_animation_operation_parameters('$setup_constants',Parameters) :- !,
2562 b_get_machine_operation_typed_parameters('$setup_constants',Parameters).
2563 get_animation_operation_parameters(OpName,FullParameters) :- xtl_mode,!,
2564 xtl_transition_parameters(OpName,ParaNames),
2565 maplist(make_string_id,ParaNames,FullParameters).
2566 get_animation_operation_parameters(OpName,FullParameters) :-
2567 TopLevel=true, % otherwise ANY parameters not added when show_eventb_any_arguments is true
2568 b_get_machine_operation_for_animation(OpName,_Results,Parameters,_Body,_OType,TopLevel,_OpPos),
2569 b_get_operation_non_det_modifies(OpName,NonDetVars), % also allow setting non-deterministically assigned vars
2570 b_get_machine_variables(Vars),
2571 include(non_det_modified(NonDetVars),Vars,ParaVars),
2572 append(ParaVars,Parameters,FullParameters).
2573
2574 make_string_id(ID,b(identifier(ID),string,[])).
2575 non_det_modified(NonDetVars,TID) :- get_texpr_id(TID,ID), ord_member(ID,NonDetVars).
2576
2577 % parse a list of variable names and expressions and turn into equal predicates
2578 % Motivation: this can also deal with Z-style identifiers like in?, ... which cannot be parsed
2579 :- use_module(btypechecker, [unify_types_strict/2, coerce_type/4]).
2580 :- use_module(extrasrc(before_after_predicates),[prime_dollar0_bexpr_for_ids/3]).
2581 :- use_module(probsrc(b_read_write_info), [b_get_read_write/3]).
2582
2583 parse_parameter_values([],_,_,Res) :- !,Res=[].
2584 parse_parameter_values(['='(ParameterID,ExpressionStr)|T],OpName,Parameters,[Pred|PT]) :-
2585 atom_codes(ExpressionStr,Codes),
2586 debug_format(9,'Parsing for parameter ~w : ~w~n',[ParameterID,ExpressionStr]),
2587 !,
2588 b_parse_machine_expression_from_codes_with_prob_ids(Codes,TypedExpr),
2589 get_texpr_type(TypedExpr,Type),
2590 TID = b(identifier(ParameterID),ExpectedType,[]),
2591 % if we reference a modified variable in the expression, we replace id by id$0 :
2592 (b_or_z_mode -> b_get_read_write(OpName,_,Written) ; Written=[]),
2593 prime_dollar0_bexpr_for_ids(TypedExpr,Written,PrimedTypedExpr0),
2594 (xtl_mode
2595 -> (Type=string -> PrimedTypedExpr1=PrimedTypedExpr0
2596 ; coerce_type(Type,string,PrimedTypedExpr0,PrimedTypedExpr1)),
2597 PrimedTypedExpr=b(external_function_call('STRING_TO_TERM',[PrimedTypedExpr1]),string,[]),
2598 Type2=string
2599 ; PrimedTypedExpr=PrimedTypedExpr0, Type2=Type),
2600 (member(b(identifier(ParameterID),ExpectedType,_),Parameters)
2601 -> (unify_types_strict(Type2,ExpectedType)
2602 -> safe_create_texpr(equal(TID,PrimedTypedExpr),pred,Pred),
2603 parse_parameter_values(T,OpName,Parameters,PT)
2604 ; coerce_type(Type2,ExpectedType,PrimedTypedExpr,NewTypedExpr)
2605 -> safe_create_texpr(equal(TID,NewTypedExpr),pred,Pred),
2606 add_message(parse_parameter_values,'Coercion of provided parameter value: ',NewTypedExpr),
2607 parse_parameter_values(T,OpName,Parameters,PT)
2608 ;
2609 pretty_type(Type2,String1), pretty_type(ExpectedType,String2),
2610 ajoin(['Value for parameter ',ParameterID,' has unexpected type ',String1,', expected: '],Msg),
2611 add_error(parse_parameter_values,Msg,String2),
2612 fail
2613 )
2614 ; add_error(parse_parameter_values,'Unknown operation parameter: ',ParameterID),
2615 fail).
2616 parse_parameter_values(PB,OpName,P,_) :-
2617 add_internal_error('Illegal parameter binding: ',parse_parameter_values(PB,OpName,P,_)),fail.
2618
2619
2620 % just as above but with typed predicate
2621 tcltk_add_user_executed_operation_typed(OpName,Operation,TypedCustomPredicate,NewID) :-
2622 current_state_id(CurID),
2623 tcltk_add_user_executed_operation_typed(OpName,CurID,Operation,TypedCustomPredicate,_,NewID).
2624 tcltk_add_user_executed_operation_typed(OpName,CurID,Operation,TypedCustomPredicate,TransID,NewID) :-
2625 b_trans_one_solution_with_pred(OpName,TypedCustomPredicate,CurID,Operation,TransID,NewID).
2626
2627 % allows the user to arbitrarily change variable values
2628 % Attention: this can of course violate the invariant
2629 tcltk_add_user_modify_variable_transition(VarID,ValueStr) :-
2630 current_state_id(CurID),
2631 tcltk_add_user_modify_variable_transition(CurID,VarID,ValueStr,_).
2632 tcltk_add_user_modify_variable_transition(CurID,VarID,ValueStr,NewID) :-
2633 get_id_type(VarID,Kind,Type),!,
2634 format('Trying to update ~w ~w to new value: ~w~n',[Kind,VarID,ValueStr]),
2635 eval_string_in_cur_state(ValueStr,ValTyped,Value),
2636 get_texpr_type(ValTyped,ValType),
2637 check_types(Kind,VarID,Type,ValType),
2638 visited_expression(CurID,CurState),
2639 update_variable(CurState,VarID,Value,NewState),
2640 Residue=[], TransInfo=[],
2641 (CurState = concrete_constants(_)
2642 -> add_error(tcltk_add_user_modify_variable_transition,'Initialise machine first before modifying values')
2643 ; Operation = '$modify'(string(VarID),string(ValueStr)),
2644 add_trans_id_with_infos(CurID,[],Operation,NewState,Residue,NewID,TransInfo,_),
2645 tcltk_goto_state(Operation,NewID)
2646 ).
2647
2648 check_types(_,_,Type,ValType) :-
2649 unify_types_strict(Type,ValType),!.
2650 check_types(Kind,VarID,Type,ValType) :-
2651 pretty_type(ValType,VTS), pretty_type(Type,TS),
2652 ajoin(['Unexpected type of value (', VTS, ' instead of ',TS,') for ',Kind,' :'],Msg),
2653 add_error(check_types,Msg,VarID),
2654 fail.
2655
2656 :- use_module(bmachine,[b_is_variable/2, b_is_constant/2]).
2657 get_id_type(ID,variable,Type) :- b_is_variable(ID,Type).
2658 get_id_type(ID,constant,Type) :- b_is_constant(ID,Type).
2659 % update variable value or constant value in concrete_constants state
2660 update_variable([],VarID,_,[]) :- add_error(update_variable,'Identifier does not exist in state:',VarID),fail.
2661 update_variable([bind(VarID,_)|T],VarID,NewVal,Res) :- !, Res = [bind(VarID,NewVal)|T].
2662 update_variable([H|T],VarID,NewVal,[H|UT]) :- !, update_variable(T,VarID,NewVal,UT).
2663 update_variable(const_and_vars(ConstID,Old),VarID,NewVal,const_and_vars(NewConstID,Old)) :-
2664 b_is_constant(VarID,_),!,
2665 visited_expression(ConstID,ConstState),
2666 update_variable(ConstState,VarID,NewVal,NewConstState),
2667 add_new_constants_state_after_update(NewConstState,NewConstID).
2668 update_variable(const_and_vars(ConstID,Old),VarID,NewVal,const_and_vars(ConstID,New)) :- !,
2669 update_variable(Old,VarID,NewVal,New). % TODO: allow updating constants
2670 update_variable(concrete_constants(Old),VarID,NewVal,concrete_constants(New)) :- !,
2671 update_variable(Old,VarID,NewVal,New). % here we allow updating constants
2672
2673 add_new_constants_state_after_update(NewConstState,NewConstID) :-
2674 get_id_of_node_and_add_if_required(NewConstState,NewConstID,Exists,root,'$setup_constants',[]),
2675 % Note: we add the (potentially new) constants state node; but there could be no direct connection
2676 % in the state space from this constants state to the update state const_and_vars(NewConstID,Old)
2677 (Exists=exists -> true
2678 ; tcltk_add_new_transition_transid(root,'$partial_setup_constants',NewConstID,NewConstState,[],_TransId1)).
2679
2680 % execute operation by predicate finding just one solution
2681 b_trans_one_solution_with_pred(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID) :-
2682 catch(
2683 (
2684 call_cleanup(b_trans_one_solution_with_pred2(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID),
2685 bmachine:reset_temp_predicate)
2686 ),
2687 enumeration_warning(Cause,_,_,_,_),
2688 (
2689 add_warning(b_trans_one_solution_with_pred,
2690 'Enumeration warning prevented finding solution for operation: ',Cause),
2691 fail
2692 )
2693 ).
2694
2695 % find one solution from current state using OpName and respecting temp_predicate
2696 % Note: the predicate is evaluated in post-state, use $0 to access values in current state
2697 b_trans_one_solution_with_pred2(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID) :-
2698 (b_or_z_mode -> b_top_level_operation(OpName) ; true),
2699 !,
2700 visited_expression(CurID,InState),
2701 set_error_context(operation(OpName,CurID)),
2702 set_context_state(CurID,b_trans_one_solution_with_pred),
2703 debug_format(19,'Executing ~w in state ~w by predicate~n',[OpName,CurID]),
2704 call_cleanup(execute_operation_by_predicate_in_state(InState,OpName,TypedCustomPredicate,Operation,NewState,TransInfo),
2705 (clear_context_state,clear_error_context)),
2706 !,
2707 debug_format(19,'Executed by predicate: ~w~n',[OpName]),
2708 add_trans_id_infos(CurID,Operation,NewState,NewID,TransId,TransInfo),
2709 tcltk_goto_state(Operation,NewID).
2710 b_trans_one_solution_with_pred2(OpName,TypedCustomPredicate,CurID,Operation,TransId,NewID) :-
2711 assert_temp_predicate_with_prob_def_set_elements(TypedCustomPredicate),
2712 visited_expression(CurID,InState),
2713 set_error_context(operation(OpName,CurID)),
2714 set_context_state(CurID,b_trans_one_solution_with_pred),
2715 temporary_set_preference(maxNrOfEnablingsPerOperation,1,Max),
2716 temporary_set_preference(maxNrOfInitialisations,1,MaxI),
2717 start_ms_timer(Timer),
2718 call_cleanup((specfile:b_trans(InState,OpName,Operation,NewState,TransInfo) -> true),
2719 (stop_ms_timer(Timer),
2720 reset_temporary_preference(maxNrOfEnablingsPerOperation,Max),
2721 reset_temporary_preference(maxNrOfInitialisations,MaxI),
2722 clear_context_state,clear_error_context)
2723 ),
2724 debug_println(9,found_solution(NewState)),nl,
2725 % now add a transition to the state space:
2726 Residue=[],
2727 add_trans_id_with_infos(CurID,[],Operation,NewState,Residue,NewID,TransInfo,TransId),
2728 tcltk_goto_state(Operation,NewID).
2729
2730 :- use_module(b_global_sets,[inline_prob_deferred_set_elements_into_bexpr/2]).
2731 assert_temp_predicate_with_prob_def_set_elements(CustomPredicate) :-
2732 inline_prob_deferred_set_elements_into_bexpr(CustomPredicate,CompiledPred),
2733 bmachine:assert_temp_typed_predicate(CompiledPred).
2734
2735
2736 % allow user to execute any statement
2737 % TO DO: catch operation_calls and route them differently
2738 % translate operation_call arguments into predicate and call tcltk_add_user_executed_operation_typed(OpName,Operation,TypedCustomPredicate,NewID)
2739 tcltk_add_user_executed_statement(Statement,Updates,NewID) :-
2740 current_expression(CurID,InState),
2741 state_corresponds_to_initialised_b_machine(InState,BState),
2742 set_context_state(CurID,tcltk_add_user_executed_statement),
2743 %start_ms_timer(Timer),
2744 call_cleanup((tcltk_interface:b_full_execute_top_level_statement_with_probids(Statement,BState,Updates,NewState)->true),
2745 clear_context_state),
2746 % TO DO: do we need to catch enumeration warnings ?
2747 %stop_ms_timer(Timer),
2748 Residue=[], TransInfo = [],
2749 debug_println(4,executed(Updates,NewState)),
2750 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
2751 (get_id_of_node_and_add_if_required(NewState,NewID,Exists,CurID,'$unknown_operation',[]),
2752 Exists=exists,
2753 transition(CurID,Action,TransId,NewID)
2754 -> debug_println(4,transition_exists_already(Action,TransId))
2755 ; translate:translate_substitution(Statement,OpLabel),
2756 Action = '$USER'(OpLabel),
2757 add_trans_id_with_infos(CurID,[],Action,NewState,Residue,NewID,TransInfo,_),
2758 format('Added new user-initiated transition to ~w via: ~w~n',[NewID,OpLabel])
2759 ),
2760 tcltk_goto_state(Action,NewID). % use the action of the transition, so that it is added to the history
2761
2762 :- use_module(eval_let_store,[extend_state_with_probids_and_lets/2]).
2763 :- use_module(kernel_waitflags,[init_wait_flags_with_call_stack/2, ground_wait_flags/1]).
2764 %% allows one to execute any statement (not just operations).
2765 b_full_execute_top_level_statement_with_probids(Body,InState,Updates,NewState) :-
2766 extend_state_with_probids_and_lets(InState,InState1),
2767 init_wait_flags_with_call_stack(WF,[prob_command_context(user_executed_statement,unknown)]),
2768 b_execute_top_level_statement(Body,[],InState1,Updates,WF,_Path1,output_not_required),
2769 ground_wait_flags(WF),
2770 store:store_updates_and_normalise(Updates,InState,NewState).
2771
2772 % --------------------------------------------------------------------------------------
2773
2774
2775 :- use_module(bmachine).
2776 :- use_module(specfile).
2777 :- use_module(tools).
2778 :- use_module(library(lists)).
2779 :- use_module(store).
2780 :- use_module(self_check).
2781 :- use_module(b_global_sets).
2782 :- use_module(translate).
2783
2784
2785 /* --------------------------------------------------------- */
2786 /* --------------------------------------------------------- */
2787
2788
2789 /* ----------------------------------*/
2790 /* b_analyse_conjunction */
2791 /* ----------------------------------*/
2792
2793
2794 /* provide list of possible options for analysis */
2795 tcltk_analyse_option(invariant,'INVARIANT') :- b_or_z_mode.
2796 tcltk_analyse_option(properties,S) :- b_or_z_mode,
2797 get_specification_description(properties,S).
2798 tcltk_analyse_option(assertions,S) :- (b_or_z_mode ; csp_mode),
2799 get_specification_description(assertions,S).
2800 tcltk_analyse_option(deadlock,'DEADLOCKED') :- b_or_z_mode.
2801
2802
2803 :- use_module(predicate_evaluator).
2804 /* perform the various analysis */
2805 tcltk_analyse(Mode,Type,ListWithResults,Total,False,Unknown) :-
2806 (Mode == unicode
2807 -> set_unicode_mode,
2808 call_cleanup(tcltk_analyse2(Type,ListWithResults,Summary),unset_unicode_mode)
2809 ; tcltk_analyse2(Type,ListWithResults,Summary)),
2810 (member(total/Total,Summary) -> true ; Total=0),
2811 (member(false/False,Summary) -> true ; False=0),
2812 (member(unknown/Unknown,Summary) -> true ; Unknown=0).
2813 tcltk_analyse2(invariant,L,Summary) :- !,tcltk_analyse_invariant(L,Summary).
2814 tcltk_analyse2(properties,L,Summary) :- !,tcltk_analyse_properties(L,Summary).
2815 tcltk_analyse2(assertions,L,Summary) :- !,tcltk_analyse_assertions(L,Summary).
2816 tcltk_analyse2(deadlock,L,Summary) :- !,tcltk_analyse_deadlock(L,Summary).
2817 tcltk_analyse2(X,L,Summary) :- add_error(tcltk_analyse, 'Unknown type of formula: ', X),
2818 L=[], Summary=[].
2819
2820
2821 /* --------------------------------- */
2822
2823 tcltk_show_current_state(TransBState) :-
2824 current_b_expression(B),
2825 translate_bstate(B,TransBState).
2826
2827
2828 tcltk_show_typing_of_variables_and_constants(list([Header|List])) :-
2829 Header = list(['ID','Type','card','Usage','Info']),
2830 b_get_machine_variables(TypedVarList),
2831 convert_typed_varlist(TypedVarList,VarList,Types),
2832 generate_typing_list(VarList,Types,VList,VarCard),
2833 length(VarList,NrVars),
2834 VarHeader = list(['VARIABLES',NrVars,VarCard,'-','-']),
2835 b_get_machine_all_constants(TypedCstList),
2836 convert_typed_varlist(TypedCstList,CVarList,CTypes),
2837 find_non_det_constants,
2838 generate_typing_list(CVarList,CTypes,CList,CCard),
2839 ( CList = []
2840 -> List = [VarHeader|VList]
2841 ; length(CVarList,NrCsts),
2842 CstHeader = list(['CONSTANTS',NrCsts,CCard,'-','-']),
2843 append([CstHeader|CList],[VarHeader|VList],List)
2844 ),!.
2845 tcltk_show_typing_of_variables_and_constants(list(['TYPE ERROR in MACHINE'])).
2846
2847
2848 %%% Used to get the constant values for the currently loaded B machine in form of a B predicate.
2849 %%% In case that the constants in the model has not been set up then all possible constants'
2850 %%% evaluations will be provided in form of a predicate in Disjunctive Normal Form.
2851 %%% Predicate used for setting up constants when model checking with TLC. (TLA)
2852
2853 tcltk_get_constants_predicate(Pred) :-
2854 tcltk_get_constants_predicate(root,Pred,_PredComplete).
2855 tcltk_get_constants_predicate(CurID,Pred,PredComplete) :-
2856 (CurID=root
2857 -> get_constants_as_disjoint_predicate(Pred),
2858 (max_reached_or_timeout_for_node(root) -> PredComplete = incomplete ; PredComplete = complete)
2859 ; PredComplete=complete,
2860 prob2_interface:get_state(CurID,EState),
2861 filter_constants_bindings(EState,X), % this will only get current constants values
2862 translate_bstate_to_pred(X,Pred)
2863 ).
2864
2865 get_constants_as_disjoint_predicate(Pred) :-
2866 findall(R,get_set_up_constants_solution(R),PredList),
2867 add_or_between_constant_predicates(PredList,Pred).
2868
2869 %get_a_part_of_the_found_solutions(L,N,Part,PredComplete) :-
2870 % length(L,Length),
2871 % (N>=Length
2872 % -> Part=L, PredComplete=complete
2873 % ; sublist(L,Part,_B,N,_A), PredComplete=incomplete
2874 % ).
2875
2876 :- assert_must_succeed((findall(int(I),between:between(1,100000,I),L), custom_explicit_sets:convert_to_avl(L,AVL),
2877 preferences:get_preference(expand_avl_upto,V0),
2878 timeout:time_out(tcltk_interface:translate_bstate_to_pred([bind(x,AVL)],_),5,_), % fully expanding AVL times out
2879 preferences:get_preference(expand_avl_upto,V1), V0==V1)). % preference restored also after a time-out
2880 translate_bstate_to_pred(State,P) :-
2881 temporary_set_preference(expand_avl_upto,-1,CHNG2),
2882 % call_cleanup: also restore the preference upon failure, time-out or other exceptions
2883 call_cleanup(once(translate: translate_bstate(State,P)),
2884 reset_temporary_preference(expand_avl_upto,CHNG2)).
2885
2886 get_set_up_constants_solution(R) :-
2887 compute_transitions_if_necessary(root),
2888 %\+ max_reached_or_timeout_for_node(root),!, % then lookup constants rather than computing them
2889 transition(root,_,Dst),
2890 visited_expression(Dst,concrete_constants(X)),
2891 translate_bstate_to_pred(X,R).
2892 %get_set_up_constants_solution(R) :-
2893 % b_interpreter: b_set_up_concrete_constants(X,_),
2894 % translate:translate_bstate(X,R).
2895
2896 add_or_between_constant_predicates([],'1=1').
2897 add_or_between_constant_predicates(L,Res) :-
2898 tools: ajoin_with_sep(L,' or ',Res).
2899
2900 filter_constants_bindings(EState,R) :-
2901 b_get_machine_all_constants(C),
2902 convert_typed_varlist(C,CVarList,_CTypes),
2903 filter_constants_bindings1(EState,CVarList,R).
2904
2905 filter_constants_bindings1([],_,[]).
2906 filter_constants_bindings1([bind(Ident,Val)|T],CVarList,Res) :-
2907 (member(Ident,CVarList) -> Res = [bind(Ident,Val)|Rest]; Res = Rest),
2908 filter_constants_bindings1(T,CVarList,Rest).
2909
2910 convert_typed_varlist([],[],[]).
2911 convert_typed_varlist([b(identifier(ID),Type,_)|T],[ID|IT],[Type|TT]) :-
2912 %print(ID), print(' : '), print(Type),nl,
2913 % db : set(couple(global(Name),global(Code))) a : set(integer) boolean
2914 convert_typed_varlist(T,IT,TT).
2915 %--------------------------------------
2916
2917
2918 :- use_module(symsrc(symmetry_marker),[type_allows_for_precise_marker/1]).
2919 :- use_module(bmachine,[b_is_unused_constant/1]).
2920 :- use_module(library(codesio),[format_to_codes/3]).
2921 :- use_module(kernel_card_arithmetic,[safe_mul/3]).
2922 generate_typing_list([],[],[],1).
2923 generate_typing_list([Var|VT],[BasicType|TT],[Translation|Rest],TotCard) :-
2924 pretty_type(BasicType,PrettyType),
2925 (kernel_objects:max_cardinality(BasicType,Card) -> true ; Card='??'),
2926 (b_get_constant_represented_inside_global_set(Var,BasicType)
2927 -> Imp='(treated as enumerated) '
2928 ; (preference(symmetry_mode,hash),
2929 \+type_allows_for_precise_marker(BasicType))
2930 -> Imp = '(IMPRECISE for HASH) '
2931 ; Imp = ''
2932 ),
2933 (non_det_constant(Var)
2934 -> atom_concat(Imp,'[multiple solutions in SETUP_CONSTANTS]',Info)
2935 ; Info = Imp),
2936 (b_is_unused_constant(Var) -> Unused='unused' ; Unused=''),
2937 % translate:translate_bexpression(b(member(identifier(Var),BasicType),pred,[]),Translation),
2938 Translation = list([Var,PrettyType,Card,Unused,Info]),
2939 generate_typing_list(VT,TT,Rest,RestCard),
2940 safe_mul(RestCard,Card,TotCard).
2941
2942 :- use_module(symsrc(symmetry_marker),[hash_model_checking_imprecise/2]).
2943 :- use_module(translate,[pretty_type/2]).
2944
2945 tcltk_hash_model_checking_imprecise :-
2946 get_preference(symmetry_mode,hash),
2947 hash_model_checking_imprecise(ID,BasicType),!,
2948 print(' * Note: Hashing may be imprecise for: '),
2949 print(ID), print(' : '),translate:pretty_type(BasicType,S),print(S), print(' !'),nl.
2950
2951
2952 /* find constants which are assigned multiple values */
2953 :- dynamic non_det_constant/1.
2954 find_non_det_constants :-
2955 retractall(non_det_constant(_)),
2956 findall(Csts,visited_expression(_,concrete_constants(Csts),_),CL),
2957 (CL=[Valuation1|O],O=[_|_] -> find_non_det_constants1(Valuation1,O)
2958 ; true /* 0 or 1 valuation only */
2959 ).
2960
2961 find_non_det_constants1([],_).
2962 find_non_det_constants1([bind(C,Value)|T],Other) :- check_cst(Other, C, Value, PeeledOther),
2963 find_non_det_constants1(T,PeeledOther).
2964
2965 check_cst([],_,_,[]).
2966 check_cst([ [bind(C,OtherVal)|T1] | TT], C, Value, [ T1 | PTT]) :-
2967 (Value=OtherVal -> check_cst(TT,C,Value,PTT)
2968 ; assertz(non_det_constant(C)), peel2(TT,PTT)).
2969 peel2([],[]).
2970 peel2([ [_|T1] | TT], [ T1 | PTT]) :- peel2(TT,PTT).
2971
2972
2973 /* --------------------------------- */
2974
2975
2976 /* --------------------------------- */
2977
2978 %%
2979 % Visualize Invariant...
2980 %
2981 % Siehe bvisual.pl
2982
2983 :- use_module(dotsrc(bvisual),[get_tree_from_expr/4, write_dot_graph_to_file/2]).
2984
2985
2986 generate_dot_from_invariant(FileName):-
2987 bmachine:b_get_invariant_from_machine(BExpr),
2988 write_dot_file_for_pred_expr(BExpr,FileName).
2989
2990
2991 :- use_module(b_operation_guards,[get_quantified_operation_enabling_condition/5]).
2992 generate_dot_from_operation(TclOpName,FileName) :-
2993 adapt_tcl_operation_name(TclOpName,OpName),
2994 Simplify=false,
2995 get_quantified_operation_enabling_condition(OpName, BExpr, _BecomesSuchVars, _Precise, Simplify),
2996 write_dot_file_for_pred_expr(BExpr,FileName).
2997 %generate_tree_from_boolean_expression(BExpr, Tree,BecomesSuchVars),
2998 %write_dot_graph_to_file(Tree,FileName).
2999
3000 % a version with additional parameters and additional pre condition / guard predicate
3001 generate_dot_from_operation_with_params(TclOpName,ParameterBindList,RestPreCond, FileName) :-
3002 adapt_tcl_operation_name(TclOpName,OpName),
3003 Simplify=false,
3004 get_quantified_operation_enabling_condition(OpName, BExpr, BecomesSuchVars,_Precise,Simplify),
3005 parse_tclk_parameter_values_and_pred(OpName,ParameterBindList,RestPreCond,CustomPredicate),
3006 insert_custom_predicate_into_guard(BExpr,CustomPredicate,FullPred),
3007 %translate:nested_print_bexpr(FullPred),nl,
3008 % TODO: probably allow all variables to be primed in CustomPredicate:
3009 b_ast_cleanup:annotate_becomes_such_vars(BecomesSuchVars,CustomPredicate,BSV2),
3010 write_dot_file_for_pred_expr(FullPred,FileName,BSV2).
3011
3012 insert_custom_predicate_into_guard(b(exists(Para,Body),pred,Info),Pred,Res) :- !,
3013 Res = b(exists(Para,BodyRes),pred,Info), % TODO: update wd infos
3014 insert_custom_predicate_into_guard(Body,Pred,BodyRes).
3015 insert_custom_predicate_into_guard(Guard,CustomPred,FullPred) :-
3016 % put CustomPred first so that bvisual prioritises solutions coming from user values/predicate
3017 % TODO: we could try and force equalities in CustomPred before calling bvisual
3018 conjunct_predicates([CustomPred,Guard],FullPred).
3019
3020 :- use_module(bmachine, [
3021 b_get_properties_from_machine/1,
3022 b_get_machine_constants/1,
3023 b_machine_has_constants_or_properties/0 ]).
3024 :- use_module(bsyntaxtree,[create_or_merge_exists/3]).
3025 get_properties(BExpr,CreateExists):-
3026 b_get_properties_from_machine(Condition),
3027 ( (CreateExists=true,b_machine_has_constants_or_properties) ->
3028 b_get_machine_constants(IDs),
3029 create_or_merge_exists(IDs, Condition, BExpr)
3030 ;
3031 BExpr = Condition
3032 ).
3033
3034 generate_dot_from_properties(FileName) :-
3035 (current_state_corresponds_to_fully_setup_b_machine -> CreateExists=false; CreateExists=true),
3036 get_properties(BExpr,CreateExists),
3037 write_dot_file_for_pred_expr(BExpr,FileName).
3038
3039 :- use_module(bsyntaxtree,[conjunct_predicates/2]).
3040
3041 generate_dot_from_assertions(FileName) :-
3042 (current_state_corresponds_to_setup_constants_b_machine,
3043 bmachine:b_get_dynamic_assertions_from_machine(BExpr), BExpr \=[]
3044 -> true
3045 ; bmachine:b_get_static_assertions_from_machine(BExpr)
3046 ),
3047 conjunct_predicates(BExpr,BE),
3048 write_dot_file_for_pred_expr(BE,FileName).
3049
3050 generate_dot_from_goal(FileName) :-
3051 b_get_machine_goal(BExpr),!,
3052 write_dot_file_for_pred_expr(BExpr,FileName,all_primed_vars).
3053 generate_dot_from_goal(FileName) :-
3054 write_dot_file_for_pred_expr_and_state(b(string('No GOAL DEFINITION available'),string,[]),[],[],FileName).
3055
3056 generate_dot_from_deadlock_po(FileName) :-
3057 b_state_model_check:get_unsorted_all_guards_false_pred(BExpr),
3058 %print('% CHECKING: '),translate_bexpression(BExpr,PT), print(PT),nl,
3059 write_dot_file_for_pred_expr(BExpr,FileName). % we do not check it is a predicate anymore
3060
3061
3062 generate_dot_from_formula(Pred,FileName) :-
3063 debug_format(19,'Parsing formula ~w~n',[Pred]),
3064 parse_machine_formula(Pred,TypedExpr),
3065 debug_format(19,'Writing dot formula ~w~n',[Pred]),
3066 write_dot_file_for_pred_expr(TypedExpr,FileName,all_primed_vars).
3067
3068
3069 :- use_module(bmachine, [b_parse_machine_formula/3, type_with_errors/4, get_primed_machine_variables/1]).
3070 parse_machine_formula(RawAST,TypedPred) :- compound(RawAST),!, % allow to pass raw AST as well
3071 get_primed_machine_variables(PV),
3072 type_with_errors(RawAST,[prob_ids(visible),identifier(PV),variables],_Type,TypedPred).
3073 parse_machine_formula(PredStr,TypedExpr) :-
3074 get_primed_machine_variables(PV),
3075 b_parse_machine_formula(PredStr,[prob_ids(visible),identifier(PV),variables],TypedExpr).
3076
3077
3078 write_dot_file_for_pred_expr(BExpr,FileName) :-
3079 write_dot_file_for_pred_expr(BExpr,FileName,[]).
3080 write_dot_file_for_pred_expr(BExpr,FileName,BecomesSuchVars) :-
3081 generate_tree_in_cur_state(BExpr, Tree,BecomesSuchVars),
3082 printsilent('% Writing to: '), printsilent(FileName),nls,
3083 write_dot_graph_to_file(Tree,FileName).
3084 write_dot_file_for_pred_expr_and_state(BExpr, LocalState, State,FileName) :-
3085 get_tree_from_expr(Tree, BExpr, LocalState, State),
3086 printsilent('% Writing to: '), printsilent(FileName),nls,
3087 write_dot_graph_to_file(Tree,FileName).
3088
3089 :- use_module(probsrc(state_space),[get_current_predecessor_state_id/1]).
3090 :- use_module(probsrc(specfile),[extract_variables_from_state_as_primed/2]).
3091
3092 generate_tree_in_cur_state(BExpr,Tree,all_primed_vars) :-
3093 (get_current_predecessor_state_id(PredID),
3094 visited_expression(PredID,SrcState),
3095 extract_variables_from_state_as_primed(SrcState,PrimedVarBindings)
3096 -> true
3097 ; PrimedVarBindings=[]
3098 ),
3099 get_current_state_for_b_formula(BExpr,CurState0),
3100 extend_state_with_probids_and_lets(CurState0,CurState1),
3101 append(PrimedVarBindings,CurState1,CurState),
3102 get_tree_from_expr(Tree, BExpr, [], CurState).
3103 generate_tree_in_cur_state(BExpr,Tree,BecomesSuchVars) :-
3104 get_current_state_for_b_formula(BExpr,CurState0),
3105 extend_state_with_probids_and_lets(CurState0,CurState1),
3106 % print(cur(CurState1)),nl,
3107 insert_before_substitution_variables(BecomesSuchVars,[],CurState1,CurState1,CurState),
3108 !,
3109 get_tree_from_expr(Tree, BExpr, [], CurState).
3110
3111 % generate a dot tree representation for a value; mostly useful for symbolic values
3112 write_dot_file_for_value_as_tree(Value,FileName) :-
3113 transform_value_to_expr(Value,BExpr),
3114 temporary_set_preference(formula_tree_minimal_timeout,5,Prev1),
3115 temporary_set_preference(formula_tree_maximal_timeout,30,Prev2),
3116 call_cleanup(generate_tree_in_cur_state(BExpr, Tree,[]),
3117 (reset_temporary_preference(formula_tree_minimal_timeout,Prev1),
3118 reset_temporary_preference(formula_tree_maximal_timeout,Prev2))),
3119 printsilent('% Writing to: '), printsilent(FileName),nls,
3120 write_dot_graph_to_file(Tree,FileName).
3121
3122 :- use_module(probsrc(bsyntaxtree),[create_typed_ids/3]).
3123 :- use_module(library(lists),[maplist/4]).
3124 transform_value_to_expr(closure(P,T,B),E) :-
3125 create_typed_ids(P,T,Parameters),!,
3126 E=b(comprehension_set(Parameters,B),set(any),[]). % TO DO: we could create typing
3127 transform_value_to_expr(Val,b(value(Val),any,[])).
3128
3129 :- use_module(tools,[maplist5/5]).
3130 tcltk_bv_get_tops(Tops) :-
3131 bv_get_top_level(Tops).
3132 tcltk_bv_get_structure(Id,Label,list(Subs)) :-
3133 bv_expand_formula(Id,Label,Subs).
3134 tcltk_bv_is_leaf(Id,Label) :-
3135 bv_expand_formula(Id,Label,[]).
3136 tcltk_bv_get_values(Ids,list(RTexts),list(Tags)) :-
3137 current_state_id(StateId),
3138 bv_get_values(Ids,StateId,Values),
3139 maplist5(tcltk_interface:retrieve_tag_adapted_text_for_id,Ids,Values,Tags,RTexts).
3140 tcltk_bv_get_value(Id,RText,Tag) :-
3141 tcltk_bv_get_values([Id],list([RText]),list([Tag])).
3142 tcltk_bv_show_formula_as_dot_tree(Id,File) :-
3143 bv_get_stored_formula_expr(Id,TExpr),
3144 write_dot_file_for_pred_expr(TExpr,File).
3145 tcltk_bv_get_pp_formula_string(Id,PPFormula) :-
3146 bv_get_stored_formula_expr(Id,TExpr),
3147 translate:translate_bexpression(TExpr,PPFormula).
3148
3149 tcltk_bv_show_formula_as_dot_graph(Id,File) :-
3150 bv_get_stored_formula_expr(Id,TExpr),
3151 get_texpr_type(TExpr,Type),
3152 Type \= pred, Type \= subst,
3153 % tcltk_show_typed_expression_as_dot_graph decomposes expressions and shows value as graph: could be useful for pre-configured DEFINITIONS
3154 tcltk_show_typed_expression_as_dot_graph(TExpr,File).
3155
3156 tcltk_bv_show_value_as_dot_tree(Id,File) :- % useful for symbolic values
3157 current_state_id(StateId),
3158 bv_get_btvalue(Id,StateId,_E,Value),
3159 write_dot_file_for_value_as_tree(Value,File).
3160
3161 % a variation of tcltk_bv_show_value_as_dot_tree without dependence on bvisual2
3162 tcltk_show_identifier_value_as_dot_tree(RawId,File) :- % this also works if bvisual2 is not set up and entry active
3163 get_identifier(RawId,Id),
3164 current_expression(_ID,CurState),
3165 expand_const_and_vars_to_full_store(CurState,EState),
3166 (EState=[] -> add_error(tcltk_show_identifier_value_as_dot_tree,'Initialise machine first, cannot retrieve value for identifier:',Id)
3167 ; lookup_value_for_existing_id(Id,EState,Value)
3168 -> write_dot_file_for_value_as_tree(Value,File)
3169 ; add_error(tcltk_show_identifier_value_as_dot_tree,'Cannot retrieve value for identifier:',Id)).
3170
3171 get_identifier(AtomicID,Res) :- atom(AtomicID), valid_id(AtomicID), !,Res=AtomicID.
3172 get_identifier(identifier(_,ID),Res) :- valid_id(ID),!, Res=ID. % raw ID from prob2_interface
3173 get_identifier(RawFormula,_) :-
3174 add_error(tcltk_show_identifier_value_as_dot_tree,'Please provide valid identifier of constant or variable:',RawFormula),
3175 fail.
3176 valid_id(ID) :- b_is_variable(ID).
3177 valid_id(ID) :- b_is_constant(ID).
3178
3179 retrieve_tag_adapted_text_for_id(Id,Value,Tag,RText) :-
3180 retrieve_tag_text_for_id(Id,Value,Tag,Text),
3181 (Text = '[]' -> RText = '[ ]' ; RText=Text). % for some reason the empty sequence translation [] gets transformed into '' by the tcltk library
3182
3183 retrieve_tag_text_for_id(Id,Value,FullTag,Text) :-
3184 retrieve_tag_text(Value,Tag,Text),
3185 (bv_is_explanation_node(Id) -> convert_explain_tag(Tag,FullTag) ; FullTag=Tag).
3186 retrieve_tag_text(i, inac, '').
3187 retrieve_tag_text(e(Text), error, Text).
3188 retrieve_tag_text(v(Text), value, Text).
3189 retrieve_tag_text(p(true), ptrue, true).
3190 retrieve_tag_text(p(false),pfalse, false).
3191 retrieve_tag_text(bv_info(Text), inac, Text).
3192
3193
3194 tcltk_bv_get_unlimited_value(Id,Text,Tag) :-
3195 current_state_id(StateId),
3196 bv_get_value_unlimited(Id,StateId,Value),
3197 retrieve_tag_text_for_id(Id,Value,Tag,Text1),
3198 atom_codes(Text1,Text). % TODO: In the end, the result was converted from codes to atom and back
3199
3200 % a version which returns just the value as an atom:
3201 tcltk_bv_get_unlimited_value_atom(Id,AtomText) :-
3202 current_state_id(StateId),
3203 bv_get_value_unlimited(Id,StateId,Value),
3204 retrieve_tag_text_for_id(Id,Value,_Tag,AtomText).
3205
3206 convert_explain_tag(ptrue,explaintrue).
3207 convert_explain_tag(pfalse,explainfalse).
3208 convert_explain_tag(X,X).
3209
3210 % -----------------------------------------
3211
3212 % STILL TO DO: refactor eval from here and probcli into separate module
3213
3214 :- dynamic eval_elapsed_time/1.
3215 tcltk_time_call(Call) :-
3216 cputime(T1),Call,cputime(T2),ElapsedTime is T2-T1,
3217 retractall(eval_elapsed_time(_)),assertz(eval_elapsed_time(ElapsedTime)).
3218
3219 :- use_module(eval_strings).
3220
3221
3222 tcltk_eval(String,StringResult,EnumWarning,Solution) :-
3223 get_computed_preference(debug_time_out,DTO),
3224 %print(debug_time_out(DTO)),nl,
3225 time_out_with_enum_warning_one_solution(eval_string(String,StringResult,EnumWarning,LocalState),DTO,TimeOutRes),
3226 (LocalState=[] -> Solution='' ; translate_bstate(LocalState,Solution)),
3227 (is_time_out_result(TimeOutRes) ->
3228 StringResult = '**** TIME-OUT ****', print(StringResult), print(' ('),print(DTO), print('ms)'),nl,
3229 EnumWarning = no
3230 ; print_last_info).
3231
3232 :- public tcltk_eval_string_in_cur_state/2.
3233 tcltk_eval_string_in_cur_state(String,TclValue) :-
3234 eval_string_in_cur_state(String,_,Value),
3235 convert_value_to_tcl(Value,TclValue).
3236 convert_value_to_tcl(int(X),R) :- !, R=X.
3237 convert_value_to_tcl(pred_true,R) :- !, R=1.
3238 convert_value_to_tcl(pred_false,R) :- !, R=0.
3239 convert_value_to_tcl(string(X),R) :- !, R=X.
3240 % TO DO: add sets,...
3241 convert_value_to_tcl(R,R) :- print(cannot_convert_to_tcl(R,R)),nl.
3242
3243 eval_string_in_cur_state(String,Typed,Value) :-
3244 %format('Parsing : "~w"~n',[String]),
3245 bmachine:parse_expression_raw_or_atom_with_prob_ids(String,Typed),
3246 current_state_id(CurID), prob2_interface:get_state(CurID,EState),
3247 %print(evaluating_in_state(CurID)),nl,
3248 b_compute_expression_with_prob_ids(Typed,EState,Value).
3249
3250 % code to translate an expression into a list of lists that can be displayed as a table in Tk
3251 % TO DO: make more robust and add more fancy translations
3252 :- use_module(extrasrc(table_tools),[expand_and_translate_to_table_for_expr/5]).
3253 tcltk_eval_as_table(String,Res) :-
3254 eval_string_in_cur_state(String,Typed,Value),
3255 Res = list([list(Header)|Table]),
3256 expand_and_translate_to_table_for_expr(Typed,Value,Header,Table,['no-row-numbers']).
3257
3258 :- use_module(user_interrupts,[interruptable_call/1]).
3259 interruptable_tcltk_eval(String,StringResult,EnumWarning,Solution) :-
3260 if(interruptable_call(tcltk_eval(String,StringResult,EnumWarning,Solution)),true,
3261 (StringResult = 'Error or User-Interrupt', EnumWarning=unknown, Solution='')).
3262
3263 % -----------------------------------------
3264
3265 % Options can be a singleton list with: prefix, exact, suffix, fuzzy
3266 tcltk_find_value_as_table(String,Options,list([Header|Matches])) :-
3267 eval_string_in_cur_state(String,Typed,GoalValue),
3268 Header = list(['ID','Kind','MatchPath']),
3269 get_texpr_type(Typed,Type),
3270 findall(list([ID,Kind,MatchMsg]),
3271 (find_value_in_cur_state(GoalValue,Type,Options,match(Kind,ID,PathObj)),
3272 translate_bvalue_with_limit(PathObj,1000,PathS),
3273 atom_codes(PathS,MatchMsgC),
3274 debug_format(9,'* match inside ~w ~w @ path: ~w~n',[Kind,ID,PathS]),
3275 atom_codes(MatchMsg,MatchMsgC)),Matches).
3276
3277 % show the matches as a graph with the searched value in the middle and one node per variable/constant
3278 tcltk_find_value_as_graph(String,Options,File) :-
3279 eval_string_in_cur_state(String,Typed,GoalValue),
3280 get_texpr_type(Typed,Type),
3281 findall(Kind-ID-PathObj,find_value_in_cur_state(GoalValue,Type,Options,match(Kind,ID,PathObj)), Matches),
3282 group_find_value_matches(Matches,Groups), % Groups = list of match_group(Kind,ID,Paths)
3283 translate_bvalue_with_limit(GoalValue,60,GoalS),
3284 (get_preference(dot_print_graph_title,true)
3285 -> length(Matches,NrM), length(Groups,NrG),
3286 ajoin(['Occurrences of ',GoalS,': ',NrM,' in ',NrG,' identifier(s)'],Title),
3287 get_preference(dot_title_font_size,TFS), TitleAttrs = [label/Title, labelloc/t, fontsize/TFS]
3288 ; TitleAttrs = []),
3289 (Groups = [_,_,_|_] -> Layout = twopi ; Layout = dot),
3290 gen_dot_graph(File,[graph_name/find_value, no_page_size, layout/Layout, rankdir/'LR', ranksep/1.2,
3291 overlap/scale, fontname/'Helvetica',
3292 node_defaults/[fontname/'Helvetica', fontsize/11, shape/box, style/'rounded,filled'],
3293 edge_defaults/[color/gray55, arrowhead/none, fontname/'Helvetica', fontsize/9]
3294 | TitleAttrs],
3295 use_new_dot_attr_pred(tcltk_interface:find_value_dot_node(GoalS,Groups)),
3296 use_new_dot_attr_pred(tcltk_interface:find_value_dot_edge(Groups)),
3297 dot_no_same_rank,dot_no_subgraph).
3298
3299 group_find_value_matches(Matches,Groups) :-
3300 findall(Kind-ID,member(Kind-ID-_,Matches),KIDs), remove_dups(KIDs,SKIDs),
3301 findall(match_group(Kind,ID,Paths),
3302 (member(Kind-ID,SKIDs), findall(P,member(Kind-ID-P,Matches),Paths)),
3303 Groups).
3304
3305 :- public find_value_dot_node/5, find_value_dot_edge/4.
3306 find_value_dot_node(GoalS,Groups,goal_value,none,
3307 [label/htmllabel(Label), tooltip/Tooltip, shape/ellipse, penwidth/2,
3308 fillcolor/'#FCE4EC', color/'#AD1457']) :-
3309 html_escape(GoalS,EGoal),
3310 (Groups=[] -> Extra='<br/><font point-size="9" color="#707070">not found in any variable or constant</font>'
3311 ; Extra=''),
3312 ajoin(['<<font point-size="9" color="#707070">searched value</font><br/><b>',EGoal,'</b>',Extra,'>'],Label),
3313 ajoin(['Searched value: ',GoalS],Tooltip).
3314 find_value_dot_node(_,Groups,Kind:ID,none,
3315 [label/htmllabel(Label), tooltip/Tooltip, fillcolor/Fill, color/Col | Legend]) :-
3316 member(match_group(Kind,ID,Paths),Groups),
3317 find_value_kind(Kind,Keyw,Col,Fill,LegendText,Order),
3318 (get_preference(dot_print_legend,true) -> Legend=[legend/LegendText, legend_order/Order] ; Legend=[]),
3319 length(Paths,NrPaths),
3320 MaxPaths = 6,
3321 (NrPaths > MaxPaths+1 -> length(Shown,MaxPaths), append(Shown,_,Paths),
3322 More is NrPaths-MaxPaths,
3323 ajoin(['<br/><font color="#707070">… (',More,' more)</font>'],MoreTxt)
3324 ; Shown=Paths, MoreTxt=''),
3325 maplist(find_value_path_html,Shown,PathHtmls),
3326 ajoin_with_sep(PathHtmls,'<br/>',PathsHtml),
3327 html_escape(ID,EID),
3328 ajoin(['<<table border="0" cellborder="0" cellspacing="0" cellpadding="1">',
3329 '<tr><td><font point-size="8" color="#707070">',Keyw,'</font></td></tr>',
3330 '<tr><td><b>',EID,'</b></td></tr>',
3331 '<tr><td balign="left"><font point-size="10">',PathsHtml,MoreTxt,'</font></td></tr></table>>'],Label),
3332 (NrPaths=1 -> ajoin([Keyw,' ',ID,': 1 occurrence'],Tooltip)
3333 ; ajoin([Keyw,' ',ID,': ',NrPaths,' occurrences'],Tooltip)).
3334
3335 find_value_kind(variable,'VARIABLE','#1F5F99','#E3EDF7','variable',10).
3336 find_value_kind(constant,'CONSTANT','#8A6D1E','#F6EFD9','constant',20).
3337
3338 find_value_dot_edge(Groups,goal_value,Kind:ID,Attrs) :-
3339 member(match_group(Kind,ID,Paths),Groups),
3340 length(Paths,Nr),
3341 (Nr>1 -> PW is min(4,1+Nr/4), Attrs=[label/Nr, penwidth/PW] ; Attrs=[]).
3342
3343 % render a path to a match, highlighting the position(s) of the match
3344 find_value_path_html(PathObj,Html) :-
3345 mark_find_value_match(PathObj,MarkedPath),
3346 translate_bvalue_with_limit(MarkedPath,60,PathS),
3347 atom_codes(PathS,Codes),
3348 find_value_marker(Marker), atom_codes(Marker,MC),
3349 split_codes_at_marker(Codes,MC,Parts),
3350 maplist(codes_html_escape,Parts,EParts),
3351 ajoin_with_sep(EParts,'<font color="#AD1457"><b>★</b></font>',Html).
3352
3353 find_value_marker('"@MATCH@"').
3354 mark_find_value_match(term('$MATCH'),R) :- !, R=string('@MATCH@').
3355 mark_find_value_match(T,R) :- compound(T), !, T=..[F|Args], maplist(mark_find_value_match,Args,RArgs), R=..[F|RArgs].
3356 mark_find_value_match(T,T).
3357
3358 split_codes_at_marker(Codes,Marker,[Before|Rest]) :-
3359 append(Before,After,Codes), append(Marker,AfterMarker,After), !,
3360 split_codes_at_marker(AfterMarker,Marker,Rest).
3361 split_codes_at_marker(Codes,_,[Codes]).
3362
3363 codes_html_escape(Codes,E) :- atom_codes(A,Codes), html_escape(A,E).
3364
3365 % find a given value somewhere in a constant or variable value
3366 find_value_in_cur_state(GoalValue,Type,Options,match(Kind,ID,PathObj)) :-
3367 translate:translate_bvalue(GoalValue,VS),
3368 get_current_state_for_b_formula(requires_variables,State), % produce full state
3369 member(bind(ID,Value),State),
3370 ( bmachine:b_is_variable(ID,IDType), Kind=variable
3371 ; bmachine:b_is_constant(ID,IDType), Kind=constant),
3372 debug_format(19,'Searching id ~w for ~w~n',[ID,VS]),
3373 % TODO check if Type occurs in type of ID
3374 find_value(Value,IDType,GoalValue,Type,Options,PathObj).
3375
3376
3377 :- use_module(probsrc(kernel_freetypes),[registered_freetype/2]).
3378 :- use_module(bsyntaxtree,[is_set_type/2]).
3379 :- use_module(kernel_strings,[to_b_string/2]).
3380 find_value(Val,Type,GoalVal,Type,Options,Path) :- !, % target and goal type match; to do: unify_types
3381 (kernel_objects:equal_object(Val,GoalVal) -> Path = term('$MATCH')
3382 ; fuzzy_find_value(Val,Type,GoalVal,Type,Options,Path)).
3383 find_value((A,B),couple(TA,TB),GoalVal,Type,Options,Path) :- !,
3384 ( find_value(A,TA,GoalVal,Type,Options,PA),
3385 Path=','(PA,B)
3386 ; find_value(B,TB,GoalVal,Type,Options,PB),
3387 Path=','(A,PB)).
3388 find_value(rec(Fields),record(FieldTypes),GoalVal,Type,Options,rec([field(Field,Path)])) :- !,
3389 member(field(Field,Val),Fields),
3390 member(field(Field,TVal),FieldTypes),
3391 find_value(Val,TVal,GoalVal,Type,Options,Path).
3392 find_value(avl_set(AVL),AType,GoalVal,Type,Options,[Path]) :- !,
3393 is_set_type(AType,TA),
3394 custom_explicit_sets:avl_member_opt(Value,AVL), % TODO: provide a more proper interface predicate
3395 find_value(Value,TA,GoalVal,Type,Options,Path).
3396 find_value([H|T],set(TA),GoalVal,Type,Options,[Path]) :- !,
3397 member(Value,[H|T]),
3398 find_value(Value,TA,GoalVal,Type,Options,Path).
3399 find_value(freeval(ID,Case,Val),freetype(ID),GoalVal,Type,Options,freeval(Case,Path)) :- !,
3400 (registered_freetype(ID,Cases),
3401 member(case(Case,TVal),Cases) -> true
3402 ; add_error(find_value,'Illegal freeval:',freeval(ID,Case,Val)),fail
3403 ),
3404 find_value(Val,TVal,GoalVal,Type,Options,Path).
3405 find_value(Val,TypeVal,GoalVal,Type,Options,Path) :-
3406 fuzzy_find_value(Val,TypeVal,GoalVal,Type,Options,Path).
3407
3408 fuzzy_find_value(Val,_Type,string(GoalAtom),string,[Option|_],term('$FUZZYMATCH'(TargetAtom))) :-
3409 GoalAtom \= '',
3410 simple_value_to_match(Val),
3411 to_b_string(Val,string(TargetAtom)),
3412 find_match_string(Option,TargetAtom,GoalAtom).
3413
3414 simple_value_to_match(fd(_,_)).
3415 simple_value_to_match(string(_)).
3416 simple_value_to_match(int(_)).
3417 simple_value_to_match(term(_)).
3418 simple_value_to_match(freeval(_,_Case,Val)) :- ground(Val), Val=term(_).
3419
3420 :- use_module(tools_matching,[fuzzy_match_codes_lower_case/2]).
3421
3422 % check whether TargetAtom matches GoalAtom given match option
3423 find_match_string(exact,GoalAtom,GoalAtom).
3424 find_match_string(prefix,TargetAtom,GoalAtom) :-
3425 atom_concat(GoalAtom,_,TargetAtom). % use sub_atom ?
3426 find_match_string(suffix,TargetAtom,GoalAtom) :-
3427 atom_concat(_,GoalAtom,TargetAtom).
3428 find_match_string(infix,TargetAtom,GoalAtom) :-
3429 sub_atom(TargetAtom,_Before,Length,_After,GoalAtom), Length>0.
3430 find_match_string(fuzzy,TargetAtom,GoalAtom) :-
3431 atom_codes(TargetAtom,TC),
3432 atom_codes(GoalAtom,GC),
3433 fuzzy_match_codes_lower_case(TC,GC).
3434 % TODO: regex
3435
3436
3437 :- use_module(prob2_interface, [get_possible_completions/3]).
3438 % ID can be col$, svg$, ... (TODO: maybe pass category names directly ? svg_colors_only, ...)
3439 tcltk_get_possible_completions(ID,list(Completions)) :-
3440 get_possible_completions(ID,[],L),
3441 findall(C,member(completion(C,_Category),L),CL),
3442 sort(CL,Completions).
3443
3444 % -----------------------------------------
3445 % B Simplifier
3446 :- use_module(probporsrc(b_simplifier),[tcltk_simplify_b_predicate/2]).
3447 tcltk_simplify_predicate(String,StringResult) :-
3448 tcltk_simplify_b_predicate(String,StringResult).
3449
3450
3451 % -----------------------------------------
3452 % CBC Check
3453
3454 get_cbc_data_base_id_checks(IDs) :-
3455 findall(ID,b_state_model_check: cbc_check(ID,_Text,_Call,_Res,_Ok),IDs).
3456 get_cbc_data_base_text_checks(Strings) :-
3457 findall(Text1,(b_state_model_check: cbc_check(_ID,Text,_Call,_Res,_Ok),tools: string_concatenate(Text,';',Text1)),Strings).
3458
3459
3460 % -----------------------------------------
3461
3462 % CSP Refinement Search
3463
3464 %:- dynamic tcltk_cspm_mode/0.
3465 %set_tcltk_cspm_mode :- assertz(tcltk_cspm_mode).
3466 %unset_tcltk_cspm_mode :- retractall(tcltk_cspm_mode).
3467
3468
3469 %get_new_csp_process_id(E,File,ID) :-
3470 % ( parse_single_csp_expression_file(E,File,Proc) ->
3471 % haskell_csp: check_compiled_term(Proc), add_csp_process_id1(Proc,ID,haskell_csp:animatable_process)
3472 % ; add_error(parse_single_csp_expression_file,'Invalid process expression: ',E),fail
3473 % ).
3474
3475 %parse_and_analyze_process_expression(ProcExp,File,Proc) :-
3476 % ( parse_single_csp_expression_file(ProcExp,File,Proc) -> true
3477 % ; add_error(parse_single_csp_expression_file,'Invalid process expression: ',ProcExp),fail
3478 % ).
3479
3480 get_csp_process_id(Process,ID) :- get_start_transition_term(Process,Trans),
3481 transition(root,Trans,ID).
3482
3483 :- use_module(probcspsrc(haskell_csp),[animatable_process_without_arguments/1,animatable_process_cli/1]).
3484 add_csp_process_id(Process,NewID) :-
3485 add_csp_process_id1(Process,NewID,animatable_process_cli).
3486
3487 add_csp_process_id1(Process,NewID,Pred) :-
3488 (call(Pred,Process)
3489 -> get_start_transition_term(Process,Trans),
3490 (transition(root,Trans,_,DestID) -> NewID=DestID % process already set up
3491 ; xtl_interface:get_start_expr(Process,NewState),
3492 add_trans_id(root,Trans,NewState,NewID,_)
3493 )
3494 ; add_error_fail(add_csp_process_id,'Not an animatable CSP Process: ',Process)).
3495
3496 get_start_transition_term('MAIN',R) :- !, R= start_cspm_MAIN.
3497 get_start_transition_term(agent_call(_Src,'MAIN',[]),R) :- !, R= start_cspm_MAIN.
3498 get_start_transition_term(P,start_cspm(P)).
3499
3500 add_csp_general_process_id(val_of(Process,_),ID) :- !,
3501 ( animatable_process_without_arguments(Process) % in case the called processes is one without arguments, then we don't have to parse the expression
3502 -> add_csp_process_id(Process,ID)
3503 % code below not covered; loaded_main_file only defined for probcli entry point !
3504 %; animation_mode(cspm),
3505 % loaded_main_file(CSPFile),
3506 % parse_and_analyze_process_expression(Process,CSPFile,Proc),
3507 % (transition(root,start_cspm(Proc),_TransID,ID) -> true
3508 % ; otherwise -> add_trans_id(root,start_cspm(Proc),Proc,ID,_)
3509 % )
3510 ).
3511 add_csp_general_process_id(GenProcExpr,ID) :-
3512 % stripping out the source-loc info
3513 haskell_csp_analyzer: clear_span(GenProcExpr,GenProcExpr1),
3514 get_start_transition_term(GenProcExpr1,Trans),
3515 (transition(root,Trans,_TransID,ID)
3516 -> true
3517 ; add_trans_id(root,Trans,GenProcExpr1,ID,_)
3518 ).
3519
3520 :- public tcltk_csp_in_situ_refinement/4.
3521 tcltk_csp_in_situ_refinement(ImplProcess,AbsProcess,ResTrace,Style) :-
3522 debug_format(9,'Checking ~w ~w ~w~n',[AbsProcess,Style,ImplProcess]),
3523 tcltk_csp_in_situ_refinement(ImplProcess,AbsProcess,ResTrace,Style,10000000).
3524 csp_ref_style('[T=',trace). % Trace Refinement
3525 csp_ref_style('T',trace). % Trace Refinement
3526 csp_ref_style('[SF=',singleton_failures). % Singleton Failures Refinement
3527 csp_ref_style('[F=',failures). % Failures Refinement
3528 csp_ref_style('[R=',refusals). % Refusals Refinement
3529 csp_ref_style('[RD=',refusals_div). % Refusals-Divergence Refinement
3530 csp_ref_style('F',failures). % Failures Refinement
3531 csp_ref_style('[FD=',X) :- csp_ref_style('FailureDivergence',X).
3532 csp_ref_style('FD',X) :- csp_ref_style('FailureDivergence',X).
3533 csp_ref_style('Trace',trace).
3534 csp_ref_style('Failure',failures).
3535 csp_ref_style('FailureDivergence',failure_divergences).
3536 csp_ref_style('RefusalTesting',refusals).
3537 csp_ref_style('RefusalTestingDiv',refusals_div).
3538 csp_ref_style('RevivalTesting',revival) :- add_error(unsupported_refinement_operator,'[V= refinement not yet supported.').
3539 csp_ref_style('RevivalTestingDiv',revival_div) :- add_error(unsupported_refinement_operator,'[VD= refinement not yet supported.').
3540
3541 translate_csp_ref_style(Style,RefStyle) :- (csp_ref_style(Style,RefStyle) -> true ;
3542 add_error_fail(csp,'Unknown refinement style: ',Style)).
3543
3544 :- use_module(extrasrc(refinement_checker),[in_situ_ref_search/5]).
3545
3546 % tcltk_csp_in_situ_refinement('P','Q',R,0,1000). tcltk_csp_in_situ_refinement('Q','P',R,1000).
3547 tcltk_csp_in_situ_refinement(ImplProcess,AbsProcess,ResTrace,Style,MaxNrOfNewNodes) :-
3548 add_csp_process_id(ImplProcess,ImplNodeID),
3549 add_csp_process_id(AbsProcess,SpecNodeID),
3550 translate_csp_ref_style(Style,RefStyle),
3551 in_situ_ref_search(ImplNodeID,SpecNodeID,ResTrace,RefStyle,MaxNrOfNewNodes).
3552
3553 :- use_module(probcspsrc(haskell_csp),[get_csp_assertions/1,translate_csp_assertion/2]).
3554
3555 tcltk_check_csp_assertions(List,Summary) :- get_csp_assertions(Assertions),
3556 treat_csp_ass(Assertions,List,0,0,0,Summary). % TO DO: display _List
3557
3558 treat_csp_ass([],[],T,F,U,[total/Tot, true/T, false/F, unknown/U]) :- Tot is T+F+U.
3559 treat_csp_ass([Assertion|T],['='(PP,Ok)|TPP],True,False,U,Summary) :- !,
3560 (checkAssertion(Assertion,PP,_,Ok,_)
3561 -> ( Ok=true -> T1 is True+1, F1=False, U1=U
3562 ; Ok=false -> T1=True, F1 is False+1, U1=U
3563 ; T1=True, F1=False, U1 is U+1)
3564 ; U1 is U+1, T1=True, PP = '??',
3565 F1=False,Ok=unknown
3566 ),
3567 treat_csp_ass(T,TPP,T1,F1,U1,Summary).
3568 treat_csp_ass([H|T],TP,T1,F1,U,Summary) :-
3569 add_error(treat_csp_ass,'Unknown CSP assertion: ',H),
3570 U1 is U+1, treat_csp_ass(T,TP,T1,F1,U1,Summary).
3571
3572 % assertModelCheckExt(False,val_of(P3,src_span(25,8,25,10,562,2)),DeadlockFree,F)
3573
3574 :- use_module(extrasrc(refinement_checker),[in_situ_model_check/5, reset_refinement_checker/0]).
3575
3576 run_assertion_check(assertModelCheckExt(Negated,Spec,Type,ModelStyle),Negated,ResTrace) :-
3577 haskell_csp_analyzer: compile_body(Spec,'assertModelCheck',[],[],CSpec),
3578 debug_println(9,assertModelCheckExt(Negated,CSpec,Type,ModelStyle)),
3579 add_csp_general_process_id(CSpec,SpecNodeID),
3580 translate_csp_ref_style(ModelStyle,RefStyle),
3581 in_situ_model_check(SpecNodeID,ResTrace,Type,RefStyle,10000000),
3582 formatsilent('Result trace for assertModelCheck: ~w~n',[ResTrace]).
3583 run_assertion_check(assertModelCheck(Negated,Spec,Style),Negated,ResTrace) :-
3584 run_assertion_check(assertModelCheckExt(Negated,Spec,Style,'FailureDivergence'),Negated,ResTrace).
3585 run_assertion_check(assertRef(Negated,Spec,Style,Impl,Span),Negated,ResTrace) :-
3586 haskell_csp_analyzer: compile_body(Spec,'assertRef',[],[],CSpec),
3587 haskell_csp_analyzer: compile_body(Impl,'assertRef',[],[],CImpl),
3588 debug_println(9,assertRef(Negated,CSpec,Style,CImpl,Span)),
3589 add_csp_general_process_id(CSpec,SpecNodeID),
3590 add_csp_general_process_id(CImpl,ImplNodeID),
3591 translate_csp_ref_style(Style,RefStyle),
3592 refinement_checker:in_situ_ref_search(ImplNodeID,SpecNodeID,ResTrace,RefStyle,10000000).
3593 run_assertion_check(assertLtl(Negated,Spec,FormulaAsAtom,_Span),Negated,ResTrace) :-
3594 add_csp_process_id_normalized(Spec,'assertLtl',CSpec,CSpecNodeID),
3595 %% print(add_csp_general_process_id(Spec,CSpec,SpecNodeID)),nl,
3596 reset_animation_history, % do not use tcltk_reset: it would discard errors found so far
3597 ltl_model_check_with_ce1(CSpec,FormulaAsAtom,-1,specific_node(CSpecNodeID),Result),
3598 translate_ltl_result(Result,ResTrace),
3599 debug_println(9,ltl_result(Negated,CSpec,CSpecNodeID,FormulaAsAtom,Result)).
3600 run_assertion_check(assertCtl(Negated,Spec,FormulaAsAtom,_Span),Negated,ResTrace) :-
3601 add_csp_process_id_normalized(Spec,'assertCtl',CSpec,CSpecNodeID),
3602 reset_animation_history, % do not use tcltk_reset: it would discard errors found so far
3603 ctl_model_check_with_ce(CSpec,FormulaAsAtom,-1,specific_node(CSpecNodeID),Result,Trace),
3604 debug_println(9,ctl_result(Negated,CSpec,CSpecNodeID,FormulaAsAtom,Result)),
3605 translate_ctl_result(Result,Trace,ResTrace).
3606
3607 checkAssertion(Assertion,PP,Negated,Ok,ResTrace) :-
3608 translate_csp_assertion(Assertion,PP),
3609 formatsilent('CHECKING ~w~n',[PP]),
3610 debug_println(9,checkAssertion(Assertion)),
3611 reset_refinement_checker,
3612 (run_assertion_check(Assertion,Negated,ResTrace)
3613 -> debug_println(9,result(ResTrace)),
3614 (ResTrace=no_counter_example
3615 -> (Negated = 'False' -> Ok=true ; Ok=false)
3616 ; ResTrace=no_counter_example_found
3617 -> Ok=interrupted
3618 ; ResTrace=[interrupted|_]
3619 -> Ok=interrupted, print('*** Execution interrupted by user ***'),nl
3620 ; ResTrace=[incomplete]
3621 -> Ok=interrupted, print('*** Not all states were explored ***'),nl
3622 ; ResTrace=[nostart]
3623 -> Ok=interrupted, print('*** No initial state found ***'),nl
3624 ; Negated = 'False' -> Ok=false
3625 ; Ok=true
3626 ),
3627 (Ok=true -> printsilent('OK'),nls
3628 ; Ok=interrupted -> print('*** UNKNOWN ***'),nl
3629 ; print('*** FALSE ***'),nl
3630 )
3631 ; add_error_fail(checkAssertion,'Internal Error, Assertion Checking Failed for: ',PP)
3632 ).
3633
3634 add_csp_process_id_normalized(Spec,Functor,CSpec,CSpecNodeID) :-
3635 % stripping out the src_span info
3636 haskell_csp_analyzer: clear_span(Spec,SpecNoSpan),
3637 haskell_csp_analyzer: compile_body(SpecNoSpan,Functor,[],[],CSpec),
3638 add_csp_general_process_id(CSpec,CSpecNodeID).
3639
3640 translate_ltl_result(ok,Res) :- !,
3641 Res = no_counter_example.
3642 translate_ltl_result(no,Res) :- !,
3643 Res = no.
3644 translate_ltl_result(ce(Atom),Res) :-
3645 !, % we have a counter-example for the LTL formula
3646 Res=Atom.
3647 translate_ltl_result(interrupted,Res) :-
3648 !,
3649 Res=[interrupted].
3650 translate_ltl_result(incomplete,Res) :- % not all states explored
3651 !,
3652 Res=[incomplete].
3653 translate_ltl_result(nostart,Res) :- % no initial state found
3654 !,
3655 Res=[nostart].
3656 translate_ltl_result(syntax_error,_Res) :- % the error has already been reported by the LTL parser
3657 !,
3658 fail.
3659 translate_ltl_result(Status,_Res) :-
3660 add_error_fail(ltl_assertions_result, 'Internal Error: unknown LTL assertion result ', Status).
3661
3662 translate_ctl_result(true,_Trace,ResTrace) :- !,
3663 ResTrace = no_counter_example.
3664 translate_ctl_result(false,ce(Atom),ResTrace) :- !,
3665 ResTrace = Atom.
3666 translate_ctl_result(interrupted,_TRace,ResTrace) :-
3667 !,
3668 ResTrace=[interrupted].
3669 translate_ctl_result(Status,_Trace,_ResTrace) :-
3670 add_error_fail(ctl_assertions_result, 'Internal Error: unknown CTL assertion result ', Status).
3671
3672
3673 tcltk_check_csp_assertion(Assertion,CSPFile,Negated,Result) :-
3674 tcltk_check_csp_assertion(Assertion,CSPFile,Negated,_PlTerm,Result).
3675
3676 tcltk_check_csp_assertion(Assertion,CSPFile,Negated,PlTerm,Result) :-
3677 parse_single_csp_declaration(Assertion,CSPFile,PlTerm),
3678 checkAssertion(PlTerm,_PP,Negated,_Ok,Result).
3679
3680 :- public tcltk_play_ltl_ctl_counterexample_trace/4.
3681 tcltk_play_ltl_ctl_counterexample_trace(Assertion,CSPFile,Type,FairnessChecked) :-
3682 announce_event(play_counterexample),
3683 ( Type == ltl -> Functor = assertLtl
3684 ; Type == ctl -> Functor = assertCtl
3685 ; add_error_fail(ltl_ctl_counterexample, 'Internal Error: Model checker type unknown: ',Type)),
3686 % constructing the prolog declaration term
3687 PlDeclTerm =.. [Functor,_Negated,Spec,FormulaAsAtom,_Span],
3688 parse_single_csp_declaration(Assertion,CSPFile,PlDeclTerm),
3689 haskell_csp_analyzer: clear_span(Spec,SpecNoSpan),
3690 haskell_csp_analyzer: compile_body(SpecNoSpan,'assertLtl',[],[],CSpec),
3691 % parsing and preprocessing the LTL/CTL formula
3692 parse_and_preprocess_formula(FormulaAsAtom,Type,PF),
3693 (is_fairness_implication(PF) -> FairnessChecked='yes'; FairnessChecked='no'),
3694 % need to reset history and current state before loading the counter-example
3695 reset_animation_history,
3696 tcltk_play_counterexample(Type,CSpec,PF).
3697
3698 tcltk_play_counterexample(ltl,Spec,Formula) :- !,
3699 tcltk_play_ltl_counterexample(Spec,Formula).
3700 tcltk_play_counterexample(ctl,Spec,Formula) :- !,
3701 tcltk_play_ctl_counterexample(Spec,Formula).
3702 tcltk_play_counterexample(Type,Spec,Formula) :-
3703 add_error_fail(ltl_ctl_counterexample, 'Internal Error: Unknown domain type: ', (Type,Spec,Formula)).
3704
3705 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3706
3707
3708 %%%% Parse and get LTL formulas from LTL File %%%%
3709 get_ltl_formulas_from_file(Filename,Text) :-
3710 parse_ltlfile(Filename, Formulas), debug_println(9,Formulas),
3711 translate_ltl_formulas(Formulas,Text).
3712
3713 translate_ltl_formulas(Formulas,Text) :-
3714 maplist(translate_ltl_formula,Formulas,Strings),
3715 haskell_csp: concatenate_string_list(Strings,Text).
3716
3717 translate_ltl_formula(formula(_Name,Formula),Text) :- !,
3718 pp_ltl_formula(Formula,T),
3719 string_concatenate(T,'$',Text).
3720 translate_ltl_formula(F,'') :- add_error(get_ltl_formulas_from_file,'Illegal formula: ',F).
3721
3722
3723 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3724
3725
3726 tcltk_explore_csp_process(ProcString,SpecNodeID) :-
3727 haskell_csp: parse_single_csp_expression(ltl,ProcString,Res),
3728 haskell_csp_analyzer: clear_span(Res,ResNoSpan),
3729 haskell_csp_analyzer: compile_body(ResNoSpan,'assertLtl',[],[],CRes),
3730 add_csp_general_process_id(CRes,SpecNodeID),
3731 refinement_checker:dfs_check(SpecNodeID,_ResTrace,false,false).
3732
3733 tcltk_visualize_csp_process(SpecNodeID,F) :-
3734 visualize_graph: tcltk_print_csp_process_states_for_dot(F,SpecNodeID).
3735
3736 :- dynamic nr_csp_process_state/1.
3737 get_csp_process_stats(NrNodes) :-
3738 assertz(nr_csp_process_state(0)),
3739 count_nodes,
3740 nr_csp_process_state(NrNodes),
3741 retractall(nr_csp_process_state(_)).
3742
3743 count_nodes :-
3744 refinement_checker: dvisited(_NodeID),
3745 nr_csp_process_state(NrNodes),
3746 NewNrNodes is NrNodes +1,
3747 retractall(nr_csp_process_state(_)),
3748 assertz(nr_csp_process_state(NewNrNodes)),
3749 fail.
3750 count_nodes.
3751
3752 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3753
3754 tcltk_machine_has_assertions :-
3755 ( b_get_static_assertions_from_machine([_|_]); b_get_dynamic_assertions_from_machine([_|_]) ), !.
3756
3757 tcltk_unique_top_level_operation(Name) :- b_top_level_operation(Name),
3758 \+ (b_top_level_operation(N2), N2 \= Name).
3759
3760 tcltk_top_level_operations(list(Res)) :-
3761 findall(Name,b_top_level_operation(Name),Names),
3762 length(Names,L),
3763 (L>5 -> sort(Names,Res) ; Res=Names).
3764
3765 tcltk_get_vacuous_guards(list(L)) :-
3766 eclipse_interface:get_vacuous_guards(LP), % to do: add source column
3767 (LP=[] -> L = ['No vacuous guards']
3768 ; L = [list(['VACUOUS GUARDS'])|L1],
3769 findall(list([P]), member(P,LP), L1)
3770 ).
3771
3772 tcltk_get_vacuous_invariants(list(L)) :-
3773 eclipse_interface:get_vacuous_invariants(LP),
3774 (LP=[] -> L = ['No vacuous invariants']
3775 ; L = [list(['VACUOUS INVARIANTS'])|L1],
3776 findall(list([TP]), (member(P,LP), translate_bexpression(P,TP)), L1)
3777 ).
3778
3779 tcltk_get_vacuous_invariants_table(list([list(['LHS','Op','RHS','Source'])|L])) :-
3780 eclipse_interface:get_vacuous_invariants(LP),
3781 LP \= [], !,
3782 maplist(get_expr_and_source,LP,L).
3783 tcltk_get_vacuous_invariants_table(list(['No vacuous invariants'])).
3784
3785 :- use_module(translate,[translate_bexpression_with_limit/3]).
3786 :- use_module(error_manager,[get_tk_table_position_info/2]).
3787 get_expr_and_source(P,list([TS1,Op,TS2,Src])) :-
3788 decompose(P,LHS,Op,RHS),
3789 translate_bexpression_with_limit(LHS,150,TS1),
3790 translate_bexpression_with_limit(RHS,60,TS2),
3791 get_tk_table_position_info(P,Src).
3792
3793 decompose(b(implication(LHS,RHS),pred,_),LHS,'=>',RHS) :- !.
3794 decompose(b(disjunction(LHS,RHS),pred,_),LHS,'or',RHS) :- !.
3795 decompose(LHS,LHS,'?',b(truth,pred,[])).
3796
3797
3798 % -------------------
3799
3800
3801 :- use_module(extrasrc(mcts_game_play), [mcts_auto_play/4, mcts_auto_play_available/0]).
3802
3803 tcltk_mcts_auto_play :- tcltk_mcts_auto_play(_).
3804 tcltk_mcts_auto_play(TransID) :-
3805 mcts_auto_play_available,
3806 current_state_id(CurID),
3807 mcts_auto_play(CurID,ActionAsTerm,TransID,State2),
3808 (tcltk_perform_action(CurID,ActionAsTerm,TransID,State2)
3809 -> true
3810 ; add_error(tcltk_mcts_auto_play,'Cannot perform chosen action:',ActionAsTerm),fail).
3811
3812
3813 % -----------------------
3814
3815
3816 :- dynamic current_simb_state/1, simb_history/5.
3817
3818 :- use_module(extrasrc(simb_parser)).
3819 :- use_module(extrasrc(simb_simulator)).
3820
3821 tcltk_start_simulation :-
3822 retractall(current_simb_state(_)),
3823 retractall(simb_history(_,_,_,_,_)),
3824 simb_file_loaded(_),!,
3825 reset_animation_history, % do not reset errors
3826 simb_initial_state(Init),
3827 assert(current_simb_state(Init)).
3828 tcltk_start_simulation :- add_error(simb,'Cannot start simulation, no SimB file loaded'),fail.
3829
3830 % Options: visible, stop_if_time_progresses, stop_if_time_exceeds(T)
3831 tcltk_peform_simulation_steps(Nr,ResElapsedTime,StopReason,Opts) :- \+ current_simb_state(_),!,
3832 (tcltk_start_simulation
3833 -> tcltk_peform_simulation_steps2(1,0,Nr,ResElapsedTime,StopReason,Opts)
3834 ; ResElapsedTime=0, StopReason=error % error already reported
3835 ).
3836 tcltk_peform_simulation_steps(Nr,ResElapsedTime,StopReason,Opts) :-
3837 tcltk_peform_simulation_steps2(1,0,Nr,ResElapsedTime,StopReason,Opts).
3838
3839 tcltk_peform_simulation_steps2(CurStepNr,ElapsedTime,MaxNr,ResElapsedTime,StopReason,Opts) :-
3840 stop_simulation(CurStepNr,ElapsedTime,MaxNr,StopReason,Opts), !,
3841 (debug_mode(off) -> true
3842 ; format('Stop simulation at step ~w after ~w ms~n',[CurStepNr,ElapsedTime]),
3843 current_simb_state(State), portray_simb_state(State)),
3844 ResElapsedTime = ElapsedTime.
3845 tcltk_peform_simulation_steps2(CurStepNr,ElapsedTime,MaxNr,ResElapsedTime,StopReason,Opts) :-
3846 (tcltk_peform_simulation_step(Delta,Opts,StepRes) -> true ; StepRes=deadlock),
3847 (StepRes = ok
3848 -> N1 is MaxNr-1,
3849 C1 is CurStepNr+1, E1 is ElapsedTime+Delta,
3850 tcltk_peform_simulation_steps2(C1,E1,N1,ResElapsedTime,StopReason,Opts)
3851 ; StepRes = deadlock
3852 -> ResElapsedTime = ElapsedTime,
3853 StopReason = deadlock,
3854 add_warning(simb,'Simulation is deadlocked at step nr: ',CurStepNr)
3855 %,current_simb_state(State), portray_simb_state(State)
3856 ; ResElapsedTime = ElapsedTime, % the animator could not perform the transition; error already reported
3857 StopReason = error
3858 ).
3859
3860 stop_simulation(_,_,Nr,max_steps_reached,_Opts) :- Nr =< 0.
3861 stop_simulation(CurStepNr,_,_Nr,time_progresses,Opts) :- CurStepNr>1,
3862 member(stop_if_time_progresses,Opts),
3863 current_simb_state(State),
3864 get_simb_delay_until_next_step(State,Delta),
3865 Delta > 0.
3866 stop_simulation(_,ElapsedTime,_Nr,max_time_exceeded,Opts) :-
3867 member(stop_if_time_exceeds(MaxTime),Opts),
3868 ElapsedTime > MaxTime.
3869
3870 % StepRes is ok, deadlock or error (animator could not perform the transition chosen by the simulator)
3871 tcltk_peform_simulation_step(Delta,Opts,StepRes) :-
3872 current_state_id(CurID), % todo: assert/retract in tcltk_peform_simulation_steps
3873 retract(current_simb_state(State)),!,
3874 simb_update_current_state_id(State,CurID,State2),
3875 (simb_perform_step(Opts,State2, TransID, Delta, Probability,NewSimBState)
3876 -> (simb_perform_animator_transition(CurID,TransID)
3877 -> % only update the simulator once the animator has performed the transition, so that both stay synchronised
3878 assert(current_simb_state(NewSimBState)),
3879 save_last_simulation_step(State2,TransID,Delta,Probability),
3880 StepRes = ok
3881 ; assert(current_simb_state(State2)),
3882 StepRes = error
3883 )
3884 ; assert(current_simb_state(State2)),
3885 StepRes = deadlock
3886 ).
3887
3888 simb_perform_animator_transition(_,none) :- !.
3889 simb_perform_animator_transition(CurID,TransID) :-
3890 (tcltk_perform_action(CurID,_,TransID,_)
3891 -> true % TODO: add time and maybe activation id store_transition_infos(TransInfo,TransID)
3892 ; add_error(simb,'Cannot perform chosen transition:',TransID),fail).
3893
3894 % save last simulation state and the transition that was performed from it
3895 save_last_simulation_step(LastSimBState,TransID,Delta,Probability) :-
3896 tcltk_get_simb_history_length(Len), L1 is Len+1,
3897 asserta(simb_history(L1,TransID,Delta,Probability,LastSimBState)).
3898
3899 tcltk_get_simb_history_length(Len) :- simb_history(Len,_,_,_,_),!.
3900 tcltk_get_simb_history_length(0).
3901
3902 % try and go back one simulation step
3903 tcltk_backtrack_simulation_step :-
3904 simb_history(Step,TransID,_Delta,_Prob,LastSimBState),!,
3905 get_simb_current_state_id(LastSimBState,LastCurID),
3906 (TransID = none -> true
3907 ; tcltk_can_backtrack_to_state_id(LastCurID) -> tcltk_backtrack
3908 ; add_warning(simb,'Animator and simulator not synchronised, cannot step back in animator to state, : ',LastCurID)
3909 ),
3910 % only remove the history entry once the animator has stepped back
3911 retract(simb_history(Step,_,_,_,_)),
3912 retractall(current_simb_state(_)), % TODO: add to forward history
3913 assert(current_simb_state(LastSimBState)).
3914
3915 tcltk_can_backtrack_simulation_step :-
3916 simb_history(_,TransID,_Delta,_Prob,LastSimBState),
3917 (TransID=none -> true
3918 ; get_simb_current_state_id(LastSimBState,LastCurID),
3919 tcltk_can_backtrack_to_state_id(LastCurID)).
3920
3921 tk_get_simb_history_entry([Step,Time,Delta,ProbS,ActID,ActionString]) :-
3922 simb_history(Step,TransID,Delta,Prob,LastSimBState),
3923 (Prob=none -> ProbS = 'det' ; ProbS = Prob),
3924 get_simb_current_state_id(LastSimBState,CurID),
3925 translate_event_from_src_and_target_id(CurID,TransID,ActionString),
3926 get_simb_time(LastSimBState,Time),
3927 get_simb_next_activation_term(LastSimBState,ActID,_Params). % TODO: extract number of activations, ...
3928
3929 translate_event_from_src_and_target_id(_,none,ActionString) :- !, ActionString='-'.
3930 translate_event_from_src_and_target_id(CurID,TransID,ActionString) :-
3931 transition(CurID,ActionAsTerm,TransID,NewID),
3932 translate_event_with_src_and_target_id(ActionAsTerm,CurID,NewID,40,ActionString).
3933
3934 tk_get_simb_history_table(list([list(['Step','Time','Delta','Probability','ActivationID','VisibleEvent'])|RList])) :-
3935 findall(list(EntryList),tk_get_simb_history_entry(EntryList),List),
3936 reverse(List,RList).
3937
3938 simb_perform_step(Opts,State, TransID, Delta, Probability, NewSimBState) :- member(visible,Opts),!,
3939 simb_perform_visible_step(State, TransID, Delta, Probability, NewSimBState).
3940 simb_perform_step(_,State, TransID, Delta, Probability, NewSimBState) :-
3941 simb_perform_step(State, TransID, Delta, Probability, NewSimBState).
3942
3943 tcltk_delay_until_next_step(Time) :-
3944 current_simb_state(State), !, get_simb_delay_until_next_step(State,Time).
3945 tcltk_delay_until_next_step(0).
3946
3947 tcltk_simulation_time(Time) :-
3948 current_simb_state(State), !, get_simb_time(State,Time).
3949 tcltk_simulation_time('-').
3950
3951 tk_get_simb_scheduling_table_stats(Info) :-
3952 current_simb_state(State), !, get_simb_scheduling_table_info(State,Info).
3953 tk_get_simb_scheduling_table_stats('-').
3954
3955
3956 tk_get_simb_scheduling_table(list([list(['Time(ms)','Prio','ActivationID','Params'])|List])) :-
3957 current_simb_state(State),!, %simb_simulator:portray_simb_state(State),nl,
3958 findall(list([Time,Prio,ID,ParamStr]),(get_simb_scheduling_entry(State,Time,Prio,ID,Params),
3959 get_simb_params(Params,ParamStr)),List).
3960 tk_get_simb_scheduling_table(list(['Simulation Not Started'])).
3961
3962 get_simb_params([],Res) :- !, Res='-'.
3963 get_simb_params(List,ParamString) :-
3964 get_param_tokens(List,Tokens), ajoin(Tokens,ParamString).
3965
3966 % note we could use translate_bstate_limited; but it inserts spaces/newlines
3967 :- use_module(probsrc(translate), [translate_bvalue_with_limit/3]).
3968 get_param_tokens([],[]).
3969 get_param_tokens([bind(Name,Val)],[Name,'=',ValS]) :- !,
3970 translate_bvalue_with_limit(Val,20,ValS).
3971 get_param_tokens([bind(Name,Val)|T],[Name,'=',ValS,','|TT]) :-
3972 translate_bvalue_with_limit(Val,20,ValS),
3973 get_param_tokens(T,TT).
3974
3975 tk_get_simb_activations(list([list(['ActivationID','Prio','Kind','After','TransSelection','Guard','Execute'])|List])) :-
3976 simb_file_loaded(_),!,
3977 findall(list([ID,PrioS,ActKind,AftS,TransSelection,Gs,ExList]),
3978 (simb_activation(ID,Prio,ActKind),
3979 simb_activation_effect(ID,Execute,AddGuard,TransSelection,After,_ActivationList),
3980 get_simb_number_as_str(After,20,AftS),
3981 get_simb_number_as_str(Prio,20,PrioS),
3982 ajoin_with_sep(Execute,',',ExList),
3983 translate_bexpression_with_limit(AddGuard,20,Gs)),List).
3984 tk_get_simb_activations(list(['Simulation Not Loaded'])).
3985
3986 get_simb_number_as_str(After,Lim,AftS) :-
3987 (number(After) -> AftS = After ; translate_bexpression_with_limit(After,Lim,AftS)).
3988
3989 % for reacting to clicks in tk_get_simb_activations
3990 tk_get_simb_activation_details(Nr,ID,list([list(['Attribute','Value'])|Details])) :-
3991 findall(ID, simb_activation(ID,_Prio,_ActKind), List),
3992 nth1(Nr,List,ID),
3993 findall(list([Attr,Val]),describe_activation(ID,Attr,Val),Details).
3994
3995 :- use_module(probsrc(bsyntaxtree), [def_get_texpr_id/2]).
3996
3997 describe_activation(ID,id,ID).
3998 describe_activation(ID,param,Para) :-
3999 simb_activation_params(ID,TParams),
4000 member(TID,TParams), def_get_texpr_id(TID,ParaID),
4001 get_texpr_type(TID,Type), pretty_type(Type,String),
4002 ajoin([ParaID,' : ',String],Para).
4003 describe_activation(ID,priority,PrioS) :-
4004 simb_activation(ID,Prio,_ActKind),get_simb_number_as_str(Prio,150,PrioS).
4005 describe_activation(ID,activationKind,ActKind) :- simb_activation(ID,_Prio,ActKind).
4006 describe_activation(ID,additionalGuard,Gs) :-
4007 simb_activation_effect(ID,_,AddGuard,_,_After,_),translate_bexpression_with_limit(AddGuard,150,Gs).
4008 describe_activation(ID,after,AfterS) :-
4009 simb_activation_effect(ID,_,_,_,After,_),get_simb_number_as_str(After,150,AfterS).
4010 describe_activation(ID,execute,OpName) :-
4011 simb_activation_effect(ID,Execute,_,_TransSelect,_After,_), member(OpName,Execute).
4012 describe_activation(ID,transitionSelection,TransSelect) :-
4013 simb_activation_effect(ID,_,_,TransSelect,_After,_).
4014 describe_activation(ID,activating,Activating) :-
4015 simb_activation_effect(ID,_,_,_TransSelect,_After,ActivatingList),
4016 member(A,ActivatingList),
4017 (atomic(A) -> Activating=A
4018 ; A=triggerActivation(A2,_Params,_Prob) -> Activating=A2 % TODO: show params
4019 ; member(chooseActivation(A2,Prob),A), get_simb_number_as_str(Prob,30,P2), ajoin([A2,':',P2],Activating)).
4020 describe_activation(ID,Option,true) :-
4021 simb_activation_options(ID,Options), member(Option,Options).
4022 % TODO: extend for all other infos
4023
4024 % ---------------------
4025
4026 :- use_module(probsrc(tools),[wrap_and_truncate_atom/4,string_escape/2]).
4027 :- use_module(probsrc(preferences),[temporary_set_preference/3, reset_temporary_preference/2]).
4028
4029 tcltk_print_simb_activation_graph(File) :-
4030 (current_simb_state(State) -> true ; State=none),
4031 temporary_set_preference(dot_print_self_loops,true,Chng),
4032 (get_preference(dot_print_graph_title,true)
4033 -> get_preference(dot_title_font_size,TFS), TitleAttrs = [label/'SimB activation diagram', labelloc/t, fontsize/TFS] ; TitleAttrs=[]),
4034 call_cleanup(gen_dot_graph(File,[graph_name/simb_activations, no_page_size, fontname/'Helvetica',
4035 nodesep/0.35, ranksep/0.55,
4036 node_defaults/[fontname/'Helvetica', fontsize/11, shape/box,
4037 style/'rounded,filled', margin/'0.12,0.06'],
4038 edge_defaults/[fontname/'Helvetica', fontsize/9, arrowsize/0.8]
4039 | TitleAttrs],
4040 use_new_dot_attr_pred(tcltk_interface:dot_activation_node(State)),
4041 use_new_dot_attr_pred(tcltk_interface:dot_activation_trans(State)),
4042 dot_no_same_rank,dot_no_subgraph),
4043 reset_temporary_preference(dot_print_self_loops,Chng)).
4044
4045 :- public dot_activation_node/4, dot_activation_trans/4.
4046 % one node per SimB activation, showing its parameters, timing, priority, executed event and guard
4047 dot_activation_node(State,ID,none,[label/htmllabel(Label), tooltip/Tooltip, fillcolor/Fill, color/Col | Attrs]) :-
4048 simb_activation(ID,Prio,ActKind),
4049 simb_activation_effect(ID,Execute,AddGuard,_TransSelection,After,_ActivationList),
4050 (get_simb_scheduling_entry(State,Time,_Prio,ID,_)
4051 -> Class=scheduled, ajoin(['scheduled at ',Time,' ms'],SchedTxt), Rows0=[SchedTxt]
4052 ; (sub_atom(ID,0,1,_,'$') -> Class=internal ; Class=normal), Rows0=[]),
4053 simb_activation_class_colours(Class,Fill,Col,LegendText,Order),
4054 (simb_activation_params(ID,TParams), TParams = [_|_], get_texpr_ids(TParams,Params)
4055 -> ajoin_with_sep(Params,', ',ParamsS), ajoin(['params: ',ParamsS],ParamsRow), Rows1=[ParamsRow|Rows0]
4056 ; Rows1=Rows0),
4057 (Prio=1 -> Rows2=Rows1
4058 ; get_simb_number_as_str(Prio,30,PrioS), ajoin(['priority: ',PrioS],PrioRow), append(Rows1,[PrioRow],Rows2)),
4059 (After=0 -> Rows3=Rows2
4060 ; get_simb_number_as_str(After,30,AftS), ajoin(['after: ',AftS],AftRow), append(Rows2,[AftRow],Rows3)),
4061 (Execute=[] -> Rows4=Rows3
4062 ; Execute=[Ex], atom(Ex) -> (Ex=ID -> Rows4=Rows3 ; ajoin(['execute: ',Ex],ExRow), append(Rows3,[ExRow],Rows4))
4063 ; length(Execute,Len) -> ajoin(['execute list of ',Len,' events'],ExRow), append(Rows3,[ExRow],Rows4)
4064 ; append(Rows3,['execute: ??'],Rows4)),
4065 (AddGuard=b(truth,_,_) -> Rows=Rows4
4066 ; translate_bexpression_with_limit(AddGuard,40,Gs), ajoin(['guard: ',Gs],GRow), append(Rows4,[GRow],Rows)),
4067 html_escape(ID,EID),
4068 maplist(html_escape,Rows,ERows),
4069 ajoin_with_sep(ERows,'<br/>',RowsHtml),
4070 (ERows=[] -> RowsPart='' ; ajoin(['<br/><font point-size="9" color="#505050">',RowsHtml,'</font>'],RowsPart)),
4071 ajoin(['<<font point-size="8" color="#707070">',ActKind,'</font><br/><b>',EID,'</b>',RowsPart,'>'],Label),
4072 ajoin_with_sep([ID|Rows],'\n',Tooltip),
4073 (Class=scheduled -> Attrs=[penwidth/2|LAttrs] ; Attrs=LAttrs),
4074 (get_preference(dot_print_legend,true) -> LAttrs=[legend/LegendText, legend_order/Order] ; LAttrs=[]).
4075
4076 simb_activation_class_colours(normal,'#E3EDF7','#1F5F99','activation',10).
4077 simb_activation_class_colours(scheduled,'#F3E5F5','#6A1B9A','currently scheduled activation',20).
4078 simb_activation_class_colours(internal,'#F5F5F5','#757575','setup/initialisation activation',30).
4079
4080 dot_activation_trans(_State,NodeID,SuccNodeID,[color/Col, fontcolor/Col, style/Style | Attrs]) :-
4081 simb_activation(NodeID,_,_ActKind),
4082 simb_activation_effect(NodeID,_Execute,_AddGuard,_TransSelection,_After,ActivationList),
4083 (member(SuccNodeID,ActivationList), simb_activation_id(SuccNodeID), Kind=activates, Attrs0=[]
4084 ; member(triggerActivation(SuccNodeID,_Params,Prob),ActivationList), % TODO: show params
4085 (Prob=none -> Kind=activates, Attrs0=[]
4086 ; get_simb_number_as_str(Prob,30,Label), Kind=probabilistic, Attrs0=[label/Label])
4087 ; member(List,ActivationList),member(chooseActivation(SuccNodeID,Prob),List),
4088 get_simb_number_as_str(Prob,30,Label), Kind=choice, Attrs0=[label/Label]
4089 ),
4090 simb_activation_edge_style(Kind,Col,Style,LegendText,Order),
4091 (get_preference(dot_print_legend,true) -> Attrs=[legend/LegendText, legend_order/Order|Attrs0] ; Attrs=Attrs0).
4092
4093 simb_activation_edge_style(activates,'#1F5F99',solid,'activates',50).
4094 simb_activation_edge_style(probabilistic,'#C77700',dashed,'activates with probability',60).
4095 simb_activation_edge_style(choice,'#6A1B9A',dashed,'chooses one activation with probability',70).
4096