1 % Heinrich Heine Universitaet Duesseldorf
2 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(prob2_interface,
6 [initialise_specification/0,
7 get_version/7, get_user_signal_reference/1,
8 get_prob_total_number_of_errors/1,
9 prob2_get_animation_mode/2,
10
11 load_classical_b_from_list_of_facts/2,
12 update_preferences_from_spec/0, update_preferences_from_spec/1,
13
14 load_event_b_project/4,
15
16 load_cspm_spec_from_cspm_file/1,
17 load_z_spec_from_fuzz_file/1,
18 load_z_spec_from_tex_file/1,
19 load_xtl_spec_from_prolog_file/1,
20 load_alloy_spec_from_term/2,
21
22 prob2_reset_prob/0,
23 reset_animator/0, clear_animator/0, start_animation/0,
24
25 serialize/2,
26 deserialize/2,
27
28 get_state/2,
29 get_b_state/2,
30
31 compute_operations_for_state/2,
32 compute_additional_candidate_operations_for_state/2,
33 get_operation_description_for_state_and_transition_id/3,
34 prob2_get_transition_infos/2,
35 prob2_execute_custom_operations/6,
36
37 get_op_from_id/5, get_op_from_id/4,
38
39 is_initialised_state/1,
40 is_initialised_b_state/1,
41 state_property/3,
42 op_timeout_occurred/2,
43
44 prob2_get_state_errors/2,
45
46 prob2_evaluate_formulas/3,
47 register_prob2_formulas/2,
48 unregister_prob2_formulas/1,
49 get_animation_image_list/1, get_animation_image_matrix_for_state/6,
50 get_react_to_item_right_click_options_for_state/4,
51 react_to_item_right_click_option_for_state/6,
52
53 prob2_get_formula_type/3,
54
55 get_states_for_predicate/3,
56
57 filter_states_for_predicate/3,
58
59 get_top_level_formulas/1,
60 insert_formula_for_expansion/2,
61 prob2_evaluate_bvisual2_formulas/3,
62 prob2_evaluate_bvisual2_formulas/4,
63 prob2_expand_bvisual2_formula/3,
64
65 do_modelchecking/5,
66 set_goal_for_model_checking/1,
67 reset_goal_for_model_checking/0,
68 compute_efficient_statespace_stats/3,
69 compute_coverage/5,
70 get_modelchecking_coverage/5,
71 get_statistics/2,
72 prob2_deadlock_freedom_check/2,
73 prob2_invariant_check/2,
74 prob2_redundant_invariants/2,
75
76
77
78 get_enable_matrix/2,
79
80 prob2_do_ltl_modelcheck/3,
81 prob2_do_ltl_modelcheck/4,
82 prob2_do_ctl_modelcheck/4,
83 prob2_do_ctl_modelcheck/6,
84
85 find_trace_to_node/2,
86 find_trace_from_node_to_node/3,
87 find_state_for_predicate/3,
88
89 cbc_disprove/5, cbc_disprove/6,
90 cbc_disprove_counter_example_dot/5,
91 cbc_disprover_statistics/2, cbc_reset_disprover_statistics/0,
92 get_theory_mapping_targets/2,
93 cbc_solve_with_opts/5,
94 cbc_timed_solve_with_opts/6,
95 pretty_print_predicate/3,
96 cbc_generate_test_cases/3,
97 prob2_find_test_path/4,
98
99 ast_leaf_walks/2,
100
101
102 check_csp_assertions/3,
103
104 list_eclipse_preferences/1,
105 list_all_eclipse_preferences/1, % also includes advanced eclipse preferences
106 list_current_eclipse_preferences/1,
107 get_eclipse_preference/2,
108 set_eclipse_preference/2,
109
110 get_signature_merge_state_space/2,
111 get_transition_diagram/2,
112
113 write_dotty_transition_diagram/2,
114 write_dotty_signature_merge/2,
115 write_dot_for_state_viz/2,
116 write_dotty_state_space/1,
117 is_dotty_command/1, write_dotty/2,
118 is_dotty_command_for_expr/1, write_dotty_for_expr/3,
119 get_dot_commands_in_state/2, call_dot_command_in_state/4,
120 get_dot_commands_with_trace/2, call_dot_command_with_trace/4,
121 get_plantuml_commands_in_state/2, call_plantuml_command_in_state/4,
122 get_plantuml_commands_with_trace/2, call_plantuml_command_with_trace/4,
123 get_table_commands_in_state/2, call_table_command_in_state/4,
124 get_table_commands_with_trace/2, call_table_command_with_trace/4,
125
126 get_error_messages_with_span_info/1,
127
128 generate_trace_until_condition_fulfilled/4,
129 execute_model/5, execute_model/6,
130 get_unsat_core_with_fixed_conjuncts/3,
131 get_minimum_unsat_core_with_fixed_conjuncts/3,
132
133 prob2_construct_trace/6,
134 prob2_find_trace/5,
135 prob2_refine_trace/8,
136
137 symbolic_model_check/2,
138
139 % synthesis
140 start_synthesis_from_ui_/13,
141 start_synthesis_single_operation_from_ui_/11,
142 get_valid_and_invalid_equality_predicates_for_operation_/6,
143 get_valid_and_invalid_equality_predicates_for_invariants_/4,
144 get_invariant_violating_vars_from_examples_/3,
145 adapt_machine_code_for_operations_/2,
146 reset_synthesis_context_/0,
147 generate_data_from_machine_operation_/6,
148 generate_synthesis_data_from_predicate_untyped_/5,
149 generate_operation_data_from_machine_path_/4,
150
151 get_pretty_print/1, get_pretty_print_unicode/1,
152 get_machine_internal_representation/2,
153
154 get_operations_and_names/2,
155
156 get_primed_predicate/2,
157 get_nonquantifying_primed_predicate/2,
158 get_weakest_precondition/3,
159 before_after_predicate/2,
160
161 get_machine_operation_names/1, get_machine_operation_infos/1, get_machine_operation_infos_typed/1,
162 get_machine_identifiers/2,
163 get_machine_files/1,
164
165 get_possible_completions/3, get_possible_completion/3,
166 get_possible_fuzzy_matches/2,
167
168 prob2_extended_static_check/1,
169 prob2_check_well_definedness/2,
170 prob2_ensure_wd/2,
171
172 prob2_load_visb_file/1,
173 prob2_load_visb_definitions_from_list_of_facts/2,
174 prob2_get_loaded_visb_file/1,
175 prob2_visb_file_loaded/2,
176 prob2_visb_attributes_for_state/2,
177 prob2_visb_click_events_and_hovers/2, prob2_visb_perform_click/4,
178 prob2_visb_items/1, prob2_visb_svg_objects/1, prob2_visb_default_svg_file_contents/1,
179 prob2_read_visb_path_from_definitions/1,
180 prob2_export_visb_html_for_history/2,
181 prob2_export_visb_html_for_history/3,
182 prob2_save_trace_file/3, prob2_save_trace_file/4,
183 prob2_export_visb_for_current_state/1,
184 prob2_export_visb_html_for_states/3,
185 prob2_get_visb_html_for_states/3,
186
187 prob2_replay_json_trace_file/4,
188 prob2_replay_json_trace_file_with_messages/5,
189 prob2_replay_json_trace_file_with_table/6,
190 prob2_get_equivalence_class_states/4,
191 prob2_interactive_replay_json_trace_file/2,
192 prob2_interactive_replay_status/6,
193 prob2_interactive_replay_fast_forward/7,
194
195 get_constants_predicate/1, get_constants_predicate/2,
196 replay_state_trace_from_file/3,
197
198 prob2_save_html_history/2,
199 prob2_export_rule_report/3,
200 prob2_export_state_as_machine/3,
201 export_proof/4,
202
203 do_ltsmin_modelchecking/3
204 ]).
205
206 :- use_module(module_information).
207 :- module_info(group,cli).
208 :- module_info(description,'This module provides the new ProB2 Prolog interface to Java and other languages (usually called via socket server).').
209
210 :- use_module(library(sets)). % list_to_set
211 :- use_module(state_space, [time_out_for_node/1, time_out_for_node/3,
212 virtual_time_out_for_node/1, time_out_for_invariant/1, max_reached_for_node/1,
213 max_reached_or_timeout_for_node/1,
214 visited_expression/2, transition/4, visited_expression_id/1,
215 set_context_state/2, clear_context_state/0,
216 state_error/3, current_state_id/1, set_current_state_id/1,
217 get_state_space_stats/3,
218 try_set_trace_by_transition_ids/1
219 ]).
220 :- use_module(external_functions,[set_current_state_for_external_fun/1, clear_state_for_external_fun/0]).
221 % new profiler
222 %:- use_module('../extensions/profiler/profiler.pl').
223
224
225 :- use_module(eventhandling, [announce_event/1]).
226 :- use_module(version, [version/4, revision/1, lastchangeddate/1]).
227 :- use_module(pref_definitions, [b_get_preferences_from_specification/0, b_get_preferences_from_specification/1]).
228 :- use_module(bsyntaxtree, [conjunct_predicates/2, get_texpr_type/2,
229 get_texpr_types/2, get_texpr_expr/2,
230 find_identifier_uses/3]).
231 :- use_module(state_space_exploration_modes,[set_depth_breadth_first_mode/1]).
232 :- use_module(bmachine, [b_type_expression/5, b_get_machine_operation/4, b_get_machine_operation/6,
233 b_type_open_predicate/5, b_top_level_operation/1,
234 get_machine_operation_additional_identifiers/2,
235 b_load_machine_from_list_of_facts/2,
236 b_set_eventb_project_flat/3, load_additional_information/1,
237 b_machine_precompile/0, other_spec_precompile/0,
238 b_set_parsed_typed_machine_goal/1,
239 b_is_variable/2, b_is_constant/1, b_is_variable/1, b_is_constant/2
240 ]).
241 :- use_module(probltlsrc(ctl), [ctl_model_check_with_ast/6]).
242 :- use_module(probltlsrc(ltl), [ltl_model_check_with_ce/4,preprocess_formula/2]).
243 :- use_module(probltlsrc(ltl_tools), [typecheck_temporal_formula/3]).
244 :- use_module(probltlsrc(ltl_verification), [evaluate_ltl_formula/6, evaluate_ltl_state_property/3]).
245 :- use_module(b_interpreter, [b_test_boolean_expression_cs/5, b_compute_expression_nowf/6]).
246 :- use_module(b_global_sets, [add_prob_deferred_set_elements_to_store/3]).
247 :- use_module(extension('user_signal/user_signal'), [user_interruptable_call_det/2,
248 ignore_user_interrupt_det/1]).
249 :- use_module(library(lists), [maplist/2, maplist/3, maplist/4]).
250 :- use_module(library(codesio), [read_from_codes/2, write_term_to_codes/4]).
251 :- use_module(specfile, [expand_const_and_vars_to_full_store/2, animation_mode/1,
252 csp_mode/0,
253 b_or_z_mode/0, xtl_mode/0,
254 set_currently_opened_file/1, set_currently_opened_b_file/1,
255 set_minor_animation_mode_from_file/1,
256 set_currently_opening_file/1, set_failed_to_open_file/1,
257 set_currently_opened_package/1, animation_minor_mode/1,
258 set_animation_mode/1, set_animation_minor_mode/1]).
259 :- use_module(translate, [with_translation_mode/2, get_language_mode/1, with_language_mode/2,
260 translate_bvalue_for_expression/3,
261 suppress_rodin_positions/1, reset_suppress_rodin_positions/1,
262 translate_event/2, translate_bstate/2, translate_state_error/2,
263 translate_bexpression/2, translate_bvalue_with_limit/3,
264 translate_bvalue_with_type_and_limit/4,
265 translate_event_error/2, explain_event_trace/3, explain_state_error/3,
266 translate_xtl_value/2]).
267 :- use_module(error_manager, [add_error_and_fail/3,
268 get_all_errors_with_span_info_and_reset/1,
269 get_all_errors_with_span_and_context_and_reset/1,
270 add_error/3, add_error/2, add_error/4,
271 add_message/2, add_message/3, add_debug_message/3, reset_errors/0,
272 add_warning/3,
273 add_all_perrors/1,
274 no_real_perror_occurred/1,
275 get_error/2,
276 catch_enumeration_warning_exceptions/2,
277 real_error_occurred/0,
278 warning_occurred/0]).
279 :- use_module(tools, [string_concatenate/3, split_atom/3,
280 safe_atom_codes/2,ajoin/2]).
281 :- use_module(extrasrc(bvisual2), [bv_get_top_level/1,
282 bv_insert_formula/3, bv_expand_formula/3,
283 bv_formula_description/2, bv_formula_discharged_info/2,
284 bv_formula_origin/2,
285 bv_get_values/3, bv_get_values_unlimited/3,
286 bv_get_formula_functor_symbol/2, bv_formula_labels/2,
287 bv_is_typed_predicate/1, bv_is_typed_formula/1]).
288 :- use_module(preferences, [eclipse_preference/2, get_preference/2,
289 preference_description/2, preference_val_type_list/2,
290 preference_default_value/2, preference_category/2,
291 set_preference/2, advanced_eclipse_preference/2,
292 deprecated_eclipse_preference/4,
293 obsolete_eclipse_preference/1]).
294 :- use_module(disproversrc(disprover), [disprove/5, disprove_with_opts/6, disprover_counter_example_dot/5,
295 get_prover_result_stats/2, reset_prover_result_stats/0]).
296 :- use_module(seqproversrc(sequent_prover_exports), [export_proof/4]).
297 :- use_module(solver_interface, [solve_predicate/5,
298 call_with_smt_mode_enabled/1]).
299 :- use_module(probcspsrc(haskell_csp), [parse_and_load_cspm_file/1]).
300 :- use_module(dotsrc(state_space_reduction),[reset_ignored_events/0, set_ignored_events/1,
301 compute_signature_merge/0, compute_transition_diagram/1,
302 get_reduced_node/4, reduced_trans/5,
303 generate_node_color/5, generate_node_labels/3,
304 generate_transition_label/3, generate_transition_color_and_style/6,
305 write_signature_merge_to_dotfile/2]).
306 :- use_module(dotsrc(state_as_dot_graph),[print_cstate_graph/2]).
307 :- use_module(debug, [debug_println/2]).
308 :- use_module(extrasrc(unsat_cores), [unsat_chr_core_with_fixed_conjuncts_auto_time_limit/4,
309 minimum_unsat_core_with_fixed_conjuncts/3]).
310 :- use_module(smt_solvers_interface(smt_solvers_interface), [smt_solve_predicate_in_state/5, smt_solve_predicate/4]).
311
312 :- use_module(typechecker).
313 :- use_module(self_check).
314
315 :- use_module(synthesis('deep_learning/predicate_data_generator'), [generate_synthesis_data_from_predicate_untyped/5]).
316 :- use_module(synthesis('deep_learning/operation_data_generator'), [generate_operation_data_from_machine_path/4,
317 generate_data_from_machine_operation/6]).
318
319 :- use_module(synthesis(b_synthesis),[start_synthesis_from_ui/13,
320 start_synthesis_single_operation_from_ui/11,
321 reset_synthesis_context/0]).
322 :- use_module(synthesis(synthesis_util),[get_valid_and_invalid_equality_predicates_for_operation/6,
323 get_valid_and_invalid_equality_predicates_for_invariants/4,
324 get_invariant_violating_vars_from_examples/3,
325 adapt_machine_code_for_operations/2]).
326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
327
328 /**
329 Access information about the current version of the ProB core.
330
331 #### called by:
332 * ProB 2.0: GetVersionCommand
333 */
334 get_version(Major,Minor,Service,Qualifier,GitRevision,LastChangedDate,PrologInfo) :-
335 version(Major,Minor,Service,Qualifier),
336 revision(GitRevision), lastchangeddate(LastChangedDate), current_prolog_flag(version,PrologInfo).
337
338 :- use_module(extension('user_signal/user_signal'),[get_user_signal_ref/1]).
339 % only used by probproxy:
340 get_user_signal_reference(Ref) :- get_user_signal_ref(Ref).
341
342 % get the total number of errors of ProB's Prolog code; cannot be accidentally reset
343 % useful for validation reports,...
344 :- use_module(error_manager,[get_total_number_of_errors/1]).
345 get_prob_total_number_of_errors(X) :- get_total_number_of_errors(X).
346
347 /**
348 Get the current animation and animation minor mode.
349
350 #### called by:
351 * ProB Java: GetAnimationModeCommand
352 */
353 prob2_get_animation_mode(Mode,MinorMode) :-
354 animation_mode(Mode), % always set?
355 (animation_minor_mode(MinorMode) -> true ; MinorMode=none).
356
357 /* ------------------------- */
358 /* B Loading Interface */
359 /* ------------------------- */
360
361 /**
362 load_classical_b_from_list_of_facts(+MainFilename,+ListOfFacts)
363
364 Loads a classical b model.
365
366 #### called by:
367 * ProB 2.0: LoadBProjectCommand
368 */
369 load_classical_b_from_list_of_facts(MainFilename,ListOfFacts) :-
370 clear_animator,
371 set_animation_mode(b),
372 set_currently_opening_file(MainFilename),
373 (b_load_machine_from_list_of_facts(MainFilename,ListOfFacts)
374 -> set_currently_opened_b_file(MainFilename),
375 update_preferences_from_spec
376 ; set_failed_to_open_file(MainFilename), fail).
377
378 /**
379 update preferences from SET_PREF Definitions in B machines:
380 should be called after loading a model and before start_animation
381 */
382 update_preferences_from_spec :- update_preferences_from_spec(_).
383 update_preferences_from_spec(List) :-
384 ((b_or_z_mode ; xtl_mode) -> b_get_preferences_from_specification(List) ; List=[]).
385
386
387
388 /* ------------------------- */
389 /* Event-B Loading Interface */
390 /* ------------------------- */
391
392 /**
393 Loads an Event-B model.
394
395 #### called by:
396 * ProB Plugin: de.prob.eventb.translator.internal.EventBTranslator, DisproverLoadCommand
397 * ProB 2.0: de.prob.model.eventb.translate.EventBModelTranslator (LoadEventBProjectCommand)
398 */
399 load_event_b_project(Machines,Contexts,Proofs,Errors) :-
400 clear_animator,
401 % set_animation_mode(b), set_animation_minor_mode(eventb), now done in b_set_eventb_project_flat
402 b_set_eventb_project_flat(Machines,Contexts,Proofs),
403 load_additional_information(Proofs),
404 Errors = [],
405 set_currently_opened_package(event_b_project).
406
407 /* ------------------------- */
408 /* CSP Loading Interface */
409 /* ------------------------- */
410
411 /**
412 load_cspm_spec_from_cspm_file(+CSPMFile)
413
414 Takes a path to a CSPM specification and loads the file using the CSPM parser.
415
416 #### called by:
417 * ProB 2.0: LoadCSPCommand
418 */
419 load_cspm_spec_from_cspm_file(CSPMFile) :-
420 clear_animator,
421 set_animation_mode(cspm),
422 set_currently_opening_file(CSPMFile),
423 parse_and_load_cspm_file(CSPMFile),
424 !,
425 set_currently_opened_file(CSPMFile).
426 load_cspm_spec_from_cspm_file(CSPMFile) :- set_failed_to_open_file(CSPMFile),fail.
427
428
429 /* ------------------------- */
430 /* Z Loading Interface */
431 /* ------------------------- */
432
433 :- use_module(bmachine,[b_set_typed_machine/2]).
434 :- use_module(parsercall,[call_fuzz_parser/2]).
435 :- use_module(prozsrc(proz),[open_proz_file/2]).
436 load_fuzz_file_internal(FuzzFile) :-
437 open_proz_file(FuzzFile,BMachine),
438 b_set_typed_machine(BMachine,FuzzFile).
439
440 load_z_spec_from_fuzz_file(FuzzFile) :-
441 clear_animator,
442 set_animation_mode(b), set_animation_minor_mode(z),
443 set_currently_opening_file(FuzzFile),
444 (load_fuzz_file_internal(FuzzFile)
445 -> set_currently_opened_b_file(FuzzFile)
446 ; set_failed_to_open_file(FuzzFile),fail
447 ).
448
449 load_z_spec_from_tex_file(TexFile) :-
450 clear_animator,
451 call_fuzz_parser(TexFile,FuzzFile),
452 load_z_spec_from_fuzz_file(FuzzFile).
453
454 /* ------------------------- */
455 /* XTL Loading Interface */
456 /* ------------------------- */
457
458 :- use_module(xtl_interface,[open_xtl_file/1]).
459 :- use_module(bmachine,[b_set_empty_machine/0]).
460 load_xtl_spec_from_prolog_file(PrologFile) :-
461 clear_animator,
462 set_animation_mode(xtl),
463 b_set_empty_machine,
464 set_currently_opening_file(PrologFile),
465 (open_xtl_file(PrologFile)
466 -> set_currently_opened_file(PrologFile),
467 update_preferences_from_spec
468 ; set_failed_to_open_file(PrologFile),fail
469 ).
470
471 :- use_module(probsrc('alloy2b/alloy2b'),[load_alloy_model/2]).
472 load_alloy_spec_from_term(PrologTerm,AlloyFile) :-
473 clear_animator,
474 load_alloy_model(PrologTerm,AlloyFile).
475 /* ------------------------- */
476 /* Animation */
477 /* ------------------------- */
478
479 reset_animator :- announce_event(reset_specification). % just reset; keeping same spec
480 clear_animator :- reset_animator,announce_event(clear_specification).
481
482 /**
483 prob2_reset_prob
484
485 Reset ProB to a clean state as if it was newly started
486 (except for total_number_of_errors).
487
488 #### called by:
489 * ProB 2.0: ResetProBCommand
490 */
491 prob2_reset_prob :- announce_event(clear_specification), announce_event(reset_prob).
492
493 start_animation :- %reset_errors, % we no longer reset_errors here !
494 initialise_specification,!.
495 start_animation :- add_error(start_animation,'Start Animation Failed').
496 %NOW done by events: reset_flow, state_space_initialise, reduce_graph_reset, reset_runtime_profiler,
497 % reset_refinement_checker reset_model_checker,
498 % reset_dynamics, % new profiler
499
500 %:- use_module(eventhandling,[register_event_listener/3]).
501 %:- register_event_listener(clear_specification,reset_prob2_interface,
502 % 'Reset prob2_interface caches.').
503 %reset_prob2_interface.
504
505
506 initialise_specification :- /* call once before starting animation or model checking */
507 announce_event(start_initialising_specification),
508 ( b_or_z_mode -> b_machine_precompile
509 ;
510 preferences:get_preference(symmetry_mode,X),
511 ( X=off -> true
512 ;
513 add_message(initialise_specification,'Symmetry can only be used for B & Z specifications'),
514 preferences:set_preference(symmetry_mode,off) /* Turn symmetry off */
515 ),
516 %tools:print_bt_message(other_spec_precompile),
517 other_spec_precompile
518 ),
519 %TODO(DP,11.8.2008)
520 % now done in state_space: user:initialise_operation_not_yet_covered,
521 % now done via event_handline: reset_external_functions,
522 announce_event(specification_initialised),
523 load_optional_csp_guide_file.
524
525 :- use_module(bmachine,[b_get_definition/5, b_absolute_file_name_relative_to_main_machine/2]).
526 :- use_module(library(file_systems),[file_exists/1]).
527 :- use_module(tcltk_interface,[tcltk_add_csp_file/1]).
528 load_optional_csp_guide_file :-
529 (b_or_z_mode,
530 b_get_definition('CSP_GUIDE_FILE',expression,[],RawExpr,_Deps), %CSP_CONTROLLER
531 (RawExpr = string(Pos,CSP_File) -> true
532 ; (arg(1,RawExpr,Pos) ; Pos=unknown),
533 add_error(csp_guide,'CSP_GUIDE_FILE must be a string pointing to a CSP file with a MAIN process!','',Pos),
534 fail
535 ),
536 b_absolute_file_name_relative_to_main_machine(CSP_File,AbsFile)
537 -> (file_exists(AbsFile)
538 -> tcltk_add_csp_file(AbsFile)
539 ; add_error(csp_guide,'CSP_GUIDE file does not exist:',AbsFile,Pos)
540 )
541 ; true).
542
543 /* ------------------------- */
544 /* Handling States */
545 /* ------------------------- */
546
547 /**
548 serialize(+Id,-SerializedState)
549
550 Produces a prolog serialization of a given state id
551
552 #### called by:
553 * ProB 2.0: SerializeStateCommand
554 */
555 :- use_module(tools_printing,[better_write_canonical_to_codes/3]).
556 serialize(Id,SerializedState) :-
557 visited_expression(Id,State),
558 better_write_canonical_to_codes(State,Codes,[0'.]), %'
559 atom_codes(SerializedState,Codes).
560
561 /**
562 deserialize(-NewId,+SerializedState)
563
564 Deserialize a state and add it if necessary
565
566 #### called by:
567 * ProB 2.0: DeserializeStateCommand
568 */
569 :- use_module(state_space_exploration_modes,[get_id_of_node_and_add_if_required/6]).
570 deserialize(NewId,SerializedState) :-
571 atom_codes(SerializedState,Codes),
572 read_from_codes(Codes,State),
573 get_id_of_node_and_add_if_required(State,NewId,_Res,root,'$unknown_operation',[]).
574
575 get_state(ID,BState) :- get_state_with_kind(ID,BState,_,_).
576 get_state_with_kind(ID,BState,Kind,ConstID) :-
577 if(visited_expression(ID,State),true,(ID=root,State=root)),
578 get_state2(State,BState,Kind),
579 get_constants_id(State,ID,ConstID).
580 get_state2(csp_and_b(CSPState,BState),[bind('CSP_CONTROLLER',CSPState)|ExpandedBState],Kind) :- !,
581 get_state2(BState,ExpandedBState,Kind).
582 get_state2(concrete_constants(BState),BState,constants_only_state) :- !.
583 get_state2(root,BState,empty_state) :- !, BState=[].
584 get_state2(State,Res,full_initialised_state) :-
585 expand_const_and_vars_to_full_store(State,BState),
586 (BState=[_|_] -> Res=BState ; Res=[] /* we have [] or a CSP process or similar */).
587
588 get_constants_id(const_and_vars(ConstID,_),_,Res) :- !,Res=ConstID.
589 get_constants_id(concrete_constants(_),ConstID,Res) :- !,Res=ConstID.
590 get_constants_id(_,_,-1).
591
592 /**
593 Get the predicate representation of a BState
594
595 #### called by:
596 * ProB 2.0: GetBStateCommand
597 */
598 get_b_state(StateId, BState) :-
599 get_state(StateId, S), translate_bstate(S, BState).
600
601 /**
602 compute_operations_for_state(+StateID,-Transitions)
603
604 Compute the enabled operations (without the backtrack options) for a given state id.
605 Transitions is a list of operation tuples with the form op(TransitionId, Name,SrcId,DestId)
606
607 #### called by:
608 * ProB 2.0: GetEnabledOperationsCommand
609 */
610 compute_operations_for_state(StateID, Transitions) :-
611 visited_expression_id(StateID),
612 tcltk_interface:tcltk_compute_options(StateID,OpsSTAndIDs),
613 (create_simple_op_terms(OpsSTAndIDs,StateID,Transitions) -> true
614 ; add_error_and_fail(prob2_interface, 'Creating op terms failed', OpsSTAndIDs)).
615
616 create_simple_op_terms([],_,[]).
617 create_simple_op_terms([(Id,Op,Dst)|T],StateID,[op(Id,Name,StateID,Dst)|FT]) :-
618 extract_op_name(Op,Name),
619 create_simple_op_terms(T,StateID,FT).
620
621 set_current_state(ID) :- current_state_id(ID),!. % no need to jump
622 set_current_state(ID) :- /* jumps to the given node; can be backtracked */
623 visited_expression_id(ID),
624 tcltk_interface:tcltk_goto_state(jump,ID).
625
626 :- use_module(specfile,[max_operations_zero_for_operation/1, get_operation_description_for_transition_id/3]).
627 :- use_module(tcltk_interface,[potentially_enabled_operation/4]).
628 % in case of MAX_OPERATIONS=0 just show the additional potentially enabled operations after compute_operations_for_state
629 % GuardPrecise is either precise or imprecise
630 % TimeOutOccurred is either true or false
631 compute_additional_candidate_operations_for_state(StateID, Candidates) :-
632 findall(candidate(OpName,ParamValues,TimeOutOccurred,GuardPrecise),
633 find_candidate_operation(StateID,OpName,ParamValues,TimeOutOccurred,GuardPrecise),Candidates).
634
635 find_candidate_operation(StateID,OpName,ParamValues,TimeOutOccurred,GuardPrecise) :-
636 b_or_z_mode, !,
637 max_operations_zero_for_operation(OpName),
638 potentially_enabled_operation(StateID,OpName,TimeOutOccurred,GuardPrecise),
639 ParamValues=[].
640 find_candidate_operation(StateID,OpName,ParamValues,TimeOutOccurred,GuardPrecise) :-
641 xtl_mode, !,
642 visited_expression(StateID,State),
643 xtl_interface:xtl_symbolic_transition_potentially_enabled(OpName,ParamValues,State),
644 TimeOutOccurred=false, GuardPrecise=precise.
645
646 % will try and compute a textual description of the transition,
647 % in particular when a string template has been stored as comment of the operation/event
648 get_operation_description_for_state_and_transition_id(StateId,TransId,Desc) :-
649 (get_operation_description_for_transition_id(StateId,TransId,Desc) -> true
650 ; Desc = ''). % No description available
651
652 prob2_get_transition_infos(TransId,Infos) :- findall(Info,find_and_explain_transition_info(TransId,Info),Infos).
653
654 :- use_module(state_space,[transition_info/2]).
655 find_and_explain_transition_info(TransId,Info) :-
656 transition_info(TransId,RawInfo),
657 (translate:explain_transition_info(RawInfo,Codes)
658 -> functor(RawInfo,RawName,_), % keep raw info name
659 atom_codes(Info0,Codes),
660 Info =.. [RawName,Info0]
661 ; Info = RawInfo).
662
663 /**
664 prob2_execute_custom_operations(+CurID, +OpName, +ParsedPredicate, +MaxNrOfSolutions, -TOperations, -Errors)
665
666 Calculates an operation given a predicate from the user.
667
668 #### called by:
669 * ProB 2.0: GetOperationByPredicateCommand
670 */
671 :- use_module(bmachine,[b_is_operation_name/1, b_is_initialisation_name/1]).
672 prob2_execute_custom_operations(_CurID, _OpName, _Pred, MaxNrOfSolutions, TOps, Errs) :-
673 MaxNrOfSolutions < 1,
674 !,
675 TOps = [],Errs = ['max nr of solutions too small'].
676 prob2_execute_custom_operations(_CurID, OpName, _Pred, _Max, TOps, Errs) :-
677 \+ valid_op_name(OpName),
678 !,
679 TOps = [],
680 (b_is_operation_name(OpName) -> ajoin(['Not a Top-Level Operation ', OpName], Msg)
681 ; ajoin(['Unknown Operation ', OpName], Msg)),
682 Errs = [Msg].
683 prob2_execute_custom_operations(CurID, OpName, ParsedPredicate, MaxNrOfSolutions, TOperations, ErrorsOut) :-
684 set_current_state(CurID),
685 prob2_execute_custom_operations_aux(CurID, OpName, ParsedPredicate, MaxNrOfSolutions, TOperations, ErrorsOut).
686
687 % special case for TRUE=TRUE predicate to avoid parser overhead
688 prob2_execute_custom_operations_aux(CurID, OpName, Pred, MaxNrOfSolutions, TOperations, ErrorsOut) :-
689 raw_truth(Pred),!,
690 findall(TO, prob2_execute_custom_operation(CurID,OpName,TO,MaxNrOfSolutions), TOperations),
691 (TOperations = []
692 -> gen_exec_error_message(CurID,OpName,truth,Msg),
693 ErrorsOut = [Msg]
694 ; ErrorsOut = []).
695 prob2_execute_custom_operations_aux(CurID, OpName, ParsedPredicate, MaxNrOfSolutions, TOperations, ErrorsOut) :-
696 ( is_special_op(OpName,_)
697 -> Scope = [prob_ids(visible),variables,external_library(all_available_libraries)]
698 ; %b_top_level_operation(OpName),
699 get_machine_operation_additional_identifiers(OpName,AdditionalIds),
700 % adds parameters, results and x$0 refers to variable value of variable x before operation
701 Scope = [identifier(AdditionalIds),prob_ids(visible),variables,external_library(all_available_libraries)]
702 % prob scope allows one to use identifiers for deferred set elements
703 ),
704 b_type_expression(ParsedPredicate, Scope, _, TypedPred, Errors),
705 (Errors = [] ->
706 findall(TO, prob2_execute_custom_operation_with_predicate(CurID,OpName,TypedPred,TO,MaxNrOfSolutions),
707 TOperations),
708 retractall(bmachine:b_machine_temp_predicate(_)),
709 (TOperations = []
710 -> gen_exec_error_message(CurID,OpName,TypedPred,Msg),
711 ErrorsOut = [Msg]
712 ; ErrorsOut = [])
713 ; TOperations = [],
714 ErrorsOut = [typechecker_errors(Errors)]
715 ).
716
717
718 :- use_module(specfile,[get_operation_name/2]).
719 :- use_module(state_space,[is_concrete_constants_state_id/1]).
720 gen_exec_error_message(root,OpName,_,Msg) :- \+ is_special_op(OpName,_),!,
721 ajoin(['Machine is not initialised, could not execute operation ', OpName], Msg).
722 gen_exec_error_message(CurID,OpName,_,Msg) :- is_concrete_constants_state_id(CurID),
723 \+ is_special_op(OpName,_),!,
724 ajoin(['Machine is not initialised, could not execute operation ', OpName], Msg).
725 gen_exec_error_message(CurID,'$setup_constants',_,Msg) :- is_concrete_constants_state_id(CurID),
726 !,
727 Msg = 'Constants are already set up, could not execute SETUP_CONSTANTS '.
728 gen_exec_error_message(CurID,OpName,_,Msg) :-
729 CurID \= root,
730 \+ is_concrete_constants_state_id(CurID),
731 is_special_op(OpName,OpS), !,
732 ajoin(['Machine is already initialised, cannot execute ', OpS], Msg).
733 gen_exec_error_message(ID,OpName,truth,Msg) :- !,
734 (is_special_op(OpName,OpS) -> true ; OpS=OpName),
735 ajoin(['Could not execute operation ', OpS, ' in state ', ID], Msg).
736 gen_exec_error_message(ID,OpName,_,Msg) :- (is_special_op(OpName,OpS) -> true ; OpS=OpName),
737 (transition(ID,Op,_,_), get_operation_name(Op,OpName)
738 -> M2 = ' (but a transition for operation exists)' ; M2 = ''),
739 ajoin(['Could not execute operation ', OpS, ' in state ', ID, ' with additional predicate',M2], Msg).
740 is_special_op('$setup_constants','SETUP_CONSTANTS').
741 is_special_op('$initialise_machine','INITIALISATION').
742
743 % true if a raw expression definitely represents truth
744 raw_truth(equal(_,E1,E2)) :- raw_equals(E1,E2).
745 raw_equals(boolean_true(_),boolean_true(_)).
746 raw_equals(boolean_false(_),boolean_false(_)).
747 raw_equals(integer(_,I),integer(_,I)).
748 valid_op_name(_) :- xtl_mode, !. % ignore this check for XTL mode (we have no list of all valid transition names)
749 valid_op_name('$initialise_machine').
750 valid_op_name('$setup_constants').
751 valid_op_name(OpName) :- b_top_level_operation(OpName).
752 %valid_op_name(OpName) :- b_get_promoted_machine_operations(OpName).
753
754
755
756 prob2_find_trace(CurId,Names,Preds,OpsOut,ErrOut) :-
757 find_trace(CurId,Names,Preds,[],OpsOut,[],ErrOut),!,
758 print(OpsOut),nl.
759
760
761 find_trace_iterator([], _Names,_Preds, CurOut, CurOut,CurErrOut,CurErrOut ).
762
763 find_trace_iterator([CurID|RestID], NameList, PredList, [CurOps | RestCandidates], [CurOpsOut|RestCandidatesOut], CurErrOut, ErrOut):-
764 find_trace(CurID, NameList, PredList, CurOps, CurOpsOut, CurErrOut, ErrOut1),
765 find_trace_iterator(RestID, NameList, PredList, RestCandidates, RestCandidatesOut, CurErrOut, ErrOut2),
766 append(ErrOut1, ErrOut2, ErrOut).
767
768 %expects result of length 1
769 find_trace(_CurId,[],[],OpsOutIn,OpsOutIn,ErrOut,ErrOut).
770 find_trace(CurId,[Name|Names],[Pred|Preds],CurOpsOut,OpsOut,CurErrOut,ErrOut) :-
771 prob2_execute_custom_operations(CurId,Name,Pred,10,ListOfListOfOps,SingleErr),
772 (ListOfListOfOps = [] ->
773 OpsOut=CurOpsOut,
774 append(CurErrOut, SingleErr, ErrOut) %% No transitions found -> return with the current state
775 ;
776 find_new_ids(ListOfListOfOps, IdsList),
777 pack_as_list(ListOfListOfOps, ListOfListOfOpsPacked), %%Start a new exploration path for each solution
778 maplist(append(CurOpsOut),ListOfListOfOpsPacked,NewOpsOut),
779 append(CurErrOut,SingleErr,NewErrOut),
780 find_trace_iterator(IdsList,Names,Preds,NewOpsOut,OpsOutIn,NewErrOut,ErrOut),
781 longest_match(OpsOutIn,[], OpsOut)
782 ).
783
784
785 refine_trace_start_kick_off(CurID, [OP|RestOP], [Preds|RestPreds], RefineAlternatives, RefinesSkip, Result, MaxDepth, MaxBreadth) :-
786 refine_trace_step(CurID, OP, Preds, RefineAlternatives, RefinesSkip, [], TransitionTakenOut, [], Solutions, IdsList, MaxDepth, MaxBreadth),
787 create_traces(IdsList, Solutions, TransitionTakenOut, AllTraces),
788 refine_trace_main_loop(AllTraces, RestOP, RestPreds, RefineAlternatives, RefinesSkip, Result, MaxDepth, MaxBreadth).
789
790 refine_trace_main_loop(AllTraces, [], [], _RefineAlternatives, _RefinesSkip, AllTraces, _MaxDepth, _MaxBreadth).
791
792 refine_trace_main_loop(AllTraces, [OP | RestOP], [Preds | RestPred], RefineAlternatives, RefinesSkip, Result, MaxDepth, MaxBreadth) :-
793 find_path(AllTraces, OP, Preds, RefineAlternatives, RefinesSkip, Results, MaxDepth, MaxBreadth),
794 strip_ID(Results, StrippedIDs),
795 list_to_set(StrippedIDs, Set),
796 select_with_ID(Set, Results, MinimizedResults),
797 (MinimizedResults = [] -> Result = [];
798 take_best(MinimizedResults, BestResults),
799 (BestResults = [] ->
800 refine_trace_main_loop(MinimizedResults, [OP | RestOP], [Preds | RestPred], RefineAlternatives, RefinesSkip, Result, MaxDepth, MaxBreadth); % Skip/Stuttering step
801 (refine_trace_main_loop(BestResults, RestOP, RestPred, RefineAlternatives, RefinesSkip, PreResult, MaxDepth, MaxBreadth) -> % Normal step
802 Result = PreResult;
803 refine_trace_main_loop(MinimizedResults, [OP | RestOP], [Preds | RestPred], RefineAlternatives, RefinesSkip, Result, MaxDepth, MaxBreadth) % Skip/Stuttering after normal step led to dead end
804 )
805 )
806 ).
807
808
809
810 select_with_ID([], _, []).
811
812 select_with_ID([First | Rest], [trace(First, R,B)|TraceRest], [trace(First, R,B)| RestResult]) :-
813 select_with_ID(Rest, TraceRest, RestResult).
814
815 select_with_ID([First | Rest], [trace(Second, _,_)|TraceRest], RestResult) :-
816 First \= Second,
817 select_with_ID([First | Rest], TraceRest, RestResult).
818
819
820 strip_ID([], []).
821
822 strip_ID([trace(ID, _, _) | List], [ID | Rest]):-
823 strip_ID(List, Rest).
824
825
826 find_path([], _OP, _Preds, _RefineAlternatives, _RefinesSkip, [], _MaxDepth, _MaxBreadth).
827
828 find_path([trace(CurID, TraceInput, TransitionTakenIn) | RestTraces], OP, Preds, RefineAlternatives, RefinesSkip, AllTraces, MaxDepth, MaxBreadth) :-
829 refine_trace_step(CurID, OP, Preds, RefineAlternatives, RefinesSkip, TransitionTakenIn, TransitionTakenOut, TraceInput, Solutions, IdsList, MaxDepth, MaxBreadth),
830 create_traces(IdsList, Solutions, TransitionTakenOut, Traces),
831 take_best(Traces, NextResult),
832 find_path(RestTraces, OP, Preds, RefineAlternatives, RefinesSkip, Results, MaxDepth, MaxBreadth),
833 (NextResult = [] ->
834 append(Results, Traces, AllTraces);
835 append(Results, NextResult, AllTraces)).
836
837
838 create_traces([],[],[],[]).
839
840 create_traces([FIds |Ids], [FSolutions | Solutions], [FSkips | Skips], [trace(FIds, FSolutions, FSkips) | Rest]) :-
841 create_traces(Ids, Solutions, Skips, Rest).
842
843
844 take_best([], []).
845
846 take_best([trace(FIds, FSolutions, []) | Rest], [trace(FIds, FSolutions, [])| ORest]) :- !,
847 take_best(Rest, ORest).
848
849 take_best([trace(_, _, _) | Rest], ORest) :-
850 take_best(Rest, ORest).
851
852
853 refine_trace_step(_CurId, [], [], _RefineAlternatives, _RefinesSkip, _TransitionTakenIn, _TransitionTakenOut, Trace, Trace, [], _MaxDepth, _MaxBreadth) :- !.
854
855 %Skip/Normal Step
856 refine_trace_step(CurId, Op, Pred, _RefineAlternatives, _RefinesSkip, _TransitionTakenInput, TransitionTakenOutput, TraceInput, TraceOutput, IdsList, _MaxDepth, MaxBreadth) :-
857 apply_refinement_variants(CurId, Op, Pred, PossiblePaths, MaxBreadth),
858 PossiblePaths \= [],!,
859 find_new_ids(PossiblePaths, IdsList),
860 pack_as_list(PossiblePaths, PossiblePathsPacked),
861 maplist(append(TraceInput), PossiblePathsPacked, TraceOutput),
862 create_map_of_maps(TraceOutput, TransitionTakenOutput).
863
864 %Skip/Stuttering Step
865 refine_trace_step(CurID, Op, _Pred, RefineAlternatives, RefinesSkip, TransitionTakenInput, TransitionTakenOutput, TraceInput, TraceOutput, IdsList, MaxDepth, _MaxBreadth) :-
866 \+ length(TransitionTakenInput, MaxDepth),!, %%Current max depth
867 compute_operations_for_state(CurID, SuitableOperations),
868 clean_targets(SuitableOperations, RefinesSkip, PossibleSkipTargetsSkip),
869 clean_targets(SuitableOperations, RefineAlternatives, RefiningOps),
870 clean_targets(RefiningOps, Op, PossibleTargetsRefines),
871 append(PossibleTargetsRefines, PossibleSkipTargetsSkip, PossibleTargets),
872 (PossibleTargets = [] ->
873 TraceOutput = [],
874 TransitionTakenOutput = TransitionTakenInput,
875 IdsList = [];
876 find_new_ids(PossibleTargets, IdsList),
877 pack_as_list(PossibleTargets, CleansedPacked),
878 maplist(append(TransitionTakenInput), CleansedPacked, TransitionTakenOutput),
879 maplist(append(TraceInput), CleansedPacked, TraceOutput)
880 ).
881
882
883
884
885 clean_targets([], _RefinesOrSkip, []).
886
887 clean_targets([op(Trans, Name, From, Id)|Rest], RefinesOrSkip, [op(Trans, Name, From, Id)|RestOPs]) :-
888 memberchk(Name, RefinesOrSkip),
889 clean_targets(Rest, RefinesOrSkip, RestOPs).
890
891 clean_targets([op(_Trans, Name, _From, _Id)|Rest], RefinesOrSkip, RestOPs) :-
892 \+ memberchk(Name, RefinesOrSkip),
893 clean_targets(Rest, RefinesOrSkip, RestOPs).
894
895 create_map_of_maps([],[]).
896
897 create_map_of_maps([_|Rest], [[]|SRest]) :-
898 create_map_of_maps(Rest, SRest).
899
900
901 %% StartingPoint, Operations, Predicates, 1:n refinemets, Refinements that are actually use refines, Skip events, Results, Maximum search depth
902 prob2_refine_trace(CurId, OPs, Preds, RefineAlternatives, RefinesSkip, Result, MaxDepth, MaxBreadth) :-
903 refine_trace_start_kick_off(CurId,OPs,Preds, RefineAlternatives, RefinesSkip, ShortestResults, MaxDepth, MaxBreadth),
904 (ShortestResults = [] -> Result = ShortestResults;
905 select_solution(ShortestResults, Result)
906 ).
907
908
909
910
911 select_solution([trace(_, T, _) | _], T).
912
913 select_solution([_ | Rest], Solution) :-
914 select_solution(Rest, Solution).
915
916
917 apply_refinement_variants( _CurId, [], _Pred, [], _MaxBreadth).
918 apply_refinement_variants( CurID, [Name | Names], Pred, Result, MaxBreadth) :-
919 prob2_execute_custom_operations(CurID, Name, Pred, MaxBreadth, AcResult, _SingleErr), %% We want to catch all possiblities, we do not care for an failing option
920 apply_refinement_variants(CurID, Names, Pred, OtherResults, MaxBreadth),
921 append(AcResult, OtherResults, Result).
922
923
924 pack_as_list([], []) .
925 pack_as_list([First | Rest], [[First]| Rest2]) :-
926 pack_as_list(Rest, Rest2).
927
928 longest_match([], Current, Current):-!.
929 longest_match([First|Rest], Current, Result) :-
930 length(Current, CL),
931 length(First, FL),
932 (CL >= FL -> longest_match(Rest, Current, Result) ; longest_match(Rest, First, Result)).
933
934 find_new_ids([], []).
935 find_new_ids([First|Rest], [Id | RestIds]):-
936 First = op(_Trans,_Name,_From,Id),
937 find_new_ids(Rest, RestIds).
938
939
940 /**
941
942 Calculates a trace given a list of operation names and a list of guards.
943 In case of errors, a partial trace is generated that jumps over the errornous operation / event.
944 In addition, a list of integers should be given as argument that make possible to execute some
945 operations in the oprations list multiple times or as long as they are disabled (in this case one should give -1).
946 E.g. by calling prob2_construct_trace(0,[e1,e2,e3],[TRUE,TRUE,TRUE],[2,1,-1],OpsOut,ErrOut) the predicate calculates
947 a trace starting at the state with the ID 0 where e1 is executed sequentially 2 times, after that e2 once,
948 and finally e3 until it becomes disabled.
949
950 #### called by:
951 * ProB 2.0: ConstructTraceCommand
952 */
953
954 prob2_construct_trace(CurId,Names,Preds,Nrs,OpsOut,ErrOut) :-
955 construct_trace(CurId,Names,Preds,Nrs,[],OpsOut,[],ErrOut).
956
957 construct_trace(_CurId,[],[],[],OpsOut,OpsOut,ErrOut,ErrOut).
958 construct_trace(CurId,[Name|Names],[Pred|Preds],[NrName|NrNames],CurOpsOut,OpsOut,CurErrOut,ErrOut) :-
959 execute_nr_of_custom_operations(CurId,Name,Pred,NrName,NewId,ListOfOps,ListOfErrs),
960 append(CurOpsOut,ListOfOps,NewOpsOut),
961 append(CurErrOut,ListOfErrs,NewErrOut),
962 construct_trace(NewId,Names,Preds,NrNames,NewOpsOut,OpsOut,NewErrOut,ErrOut).
963
964 execute_nr_of_custom_operations(CurId,_Name,_Pred,0,CurId,[],[]).
965 execute_nr_of_custom_operations(CurId,Name,Pred,Nr,NewId,ListOfOps,ListOfErrs) :-
966 ( Nr = -1 ->
967 execute_until_disabled(CurId,Name,Pred,NewId,ListOfOps,ListOfErrs)
968 ; % Nr is greater than 0
969 prob2_execute_custom_operations(CurId,Name,Pred,1,ListContainingSingleOp,SingleErr),
970 ( ListContainingSingleOp = [] ->
971 NextId=CurId
972 ; ListContainingSingleOp = [op(_Trans,_Name,_From,To)],
973 NextId = To
974 ),
975 append(ListContainingSingleOp,Ops,ListOfOps),
976 append(SingleErr,Errs,ListOfErrs),
977 NewNr is Nr - 1,
978 execute_nr_of_custom_operations(NextId,Name,Pred,NewNr,NewId,Ops,Errs)
979 ).
980
981
982 execute_until_disabled(CurId,OpName,Pred,NewId,ListOfOps,ListOfErrs) :-
983 execute_until_disabled(CurId,OpName,Pred,NewId,[],ListOfOps,ListOfErrs).
984
985 execute_until_disabled(CurId,OpName,Pred,NewId,CurListOfOps,ListOfOps,ListOfErrs) :-
986 prob2_execute_custom_operations(CurId,OpName,Pred,1,ListContainingSingleOp,SingleErr),
987 ( ListContainingSingleOp = [] -> % reached a state where OpName is not executed
988 NewId=CurId,
989 ListOfOps=CurListOfOps,
990 ajoin(['Could not execute Operation ', OpName, ' with additional predicate'], Msg),
991 (member(Msg,SingleErr) -> % Error message generated because OpName is disabled at some state
992 ListOfErrs = []
993 ; % unexpected error occurred, need to be reported
994 ListOfErrs = SingleErr
995 )
996 ; ListContainingSingleOp = [op(Trans,Name,From,To)],
997 ( member(op(_T,_N,To,_To),CurListOfOps) -> % in case of a loop we terminate, otherwise we will go forever
998 ListOfOps = CurListOfOps,
999 NewId=From
1000 ;
1001 NextId = To,
1002 append(CurListOfOps,[op(Trans,Name,From,To)],NewCurListOfOps),
1003 execute_until_disabled(NextId,OpName,Pred,NewId,NewCurListOfOps,ListOfOps,ListOfErrs)
1004 )
1005 ).
1006
1007 % TO DO: check if we need to recompute the operation effect: if the ParsedPredicate is TRUE
1008 % (TRUE = equal(none,integer(none,1),integer(none,1)) ) & MaxNrOfSolutions <=
1009 % what has already been used previously, we can simply reuse transition from the state space
1010
1011 prob2_execute_custom_operation(CurID,OpName,Transition,Max) :-
1012 set_context_state(CurID,prob2_execute_custom_operation), % errors will be added to state space as state errors
1013 call_cleanup(prob2_exec_custom_aux(CurID,OpName,Transition,Max),
1014 clear_context_state).
1015 prob2_exec_custom_aux(CurID,OpName,Transition,_Max) :- xtl_mode,!,
1016 visited_expression(CurID,InState),
1017 (xtl_interface:xtl_transition_parameters(OpName,[])
1018 -> Operation = OpName % ground operation for symbolic transitions without parameters
1019 ; true),
1020 xtl_interface:xtl_transition_with_symbolic(InState,Operation,NewState,TransInfos),
1021 functor(Operation,OpName,_),
1022 tcltk_interface:add_trans_id_infos(CurID,Operation,NewState,NewID,TransId,TransInfos),
1023 Transition = op(TransId,OpName,CurID,NewID).
1024 prob2_exec_custom_aux(CurID,OpName,Transition,Max) :-
1025 visited_expression(CurID,InState),
1026 %add_prob_deferred_set_elements_to_store(InState1, InState, visible), % does not work for root, const_and_vars
1027 specfile:compute_operation_effect_max(InState,OpName,Operation,NewState,_TransPathInfo,Max),
1028 % logger:writeln_log(sol(OpName,NewState)), %%
1029 tcltk_interface:add_trans_id(CurID,Operation,NewState,NewID,TransId),
1030 % logger:writeln_log(ids(OpName,Operation,NewID,TransId)), %%
1031 Transition = op(TransId,OpName,CurID,NewID).
1032
1033 :- use_module(succeed_max,[succeed_max_call_id/3]).
1034 :- use_module(b_state_model_check,[execute_operation_by_predicate_in_state/6]).
1035 :- use_module(b_global_sets,[inline_prob_deferred_set_elements_into_bexpr/2]).
1036 :- use_module(bmachine,[assert_temp_typed_predicate/1,reset_temp_predicate/0]).
1037 prob2_execute_custom_operation_with_predicate(CurID,OpName,Predicate,Transition,Max) :-
1038 set_context_state(CurID,prob2_execute_custom_operation_with_predicate),
1039 call_cleanup(prob2_exec_custom_pred_aux(CurID,OpName,Predicate,Transition,Max),
1040 clear_context_state).
1041 prob2_exec_custom_pred_aux(CurID,OpName,Predicate,Transition,Max) :-
1042 catch(
1043 prob2_execute_custom_operation_with_predicate_aux(CurID,OpName,Predicate,Transition,Max),
1044 enumeration_warning(_,_,_,_,_),
1045 (add_warning(prob2_execute_custom_operation_with_predicate,'Enumeration warning when executing operation with predicate: ',OpName),
1046 fail)).
1047 prob2_execute_custom_operation_with_predicate_aux(CurID,OpName,Predicate,Transition,Max) :-
1048 (b_or_z_mode -> b_top_level_operation(OpName) ; true),
1049 !,
1050 visited_expression(CurID,InState),
1051 succeed_max_call_id(prob2_execute_custom_operation,
1052 execute_operation_by_predicate_in_state(InState,OpName,Predicate,Operation,NewState,TransInfo),Max),
1053 tcltk_interface:add_trans_id_infos(CurID,Operation,NewState,NewID,TransId,TransInfo),
1054 Transition = op(TransId,OpName,CurID,NewID).
1055 prob2_execute_custom_operation_with_predicate_aux(CurID,OpName,Predicate,Transition,MaxNrOfSolutions) :-
1056 % temporary fix: old style execution for INIT, setup_constants; INIT does not work yet for Event-B !
1057 inline_prob_deferred_set_elements_into_bexpr(Predicate,CP),
1058 %translate:print_bexpr(CP),nl,
1059 assert_temp_typed_predicate(CP),
1060 call_cleanup(prob2_execute_custom_operation(CurID,OpName,Transition,MaxNrOfSolutions),
1061 reset_temp_predicate).
1062
1063 /**
1064 get_op_from_id(+StateId,+TransId,+Options,-Params,-RetVals)
1065 get_op_from_id(+TransId,+Options,-Params,-RetVals)
1066
1067 Extracts information about the parameters and return values for the
1068 specified transition.
1069
1070 #### called by:
1071 * ProB 2.0: GetOpFromId
1072 */
1073
1074 % this version does not have the source node available
1075 % this can be slow in large state spaces as we need to linearly look for a matching transition
1076 get_op_from_id(TransId,Options,Params,RetVals) :-
1077 get_op_from_id(_,TransId,Options,Params,RetVals).
1078
1079 get_op_from_id(_,skip,_Options,Params,RetVals) :- !, % skip term created by trace_to_op_terms
1080 Params=[], RetVals=[].
1081 get_op_from_id(SrcId,TransId,Options,Params,RetVals) :-
1082 (is_list(Options) ->
1083 % The eval-related options aren't actually used by this predicate.
1084 parse_eval_opts(_EvalOpts, Options, Options1),
1085 parse_pp_opts(PPOpts, Options1, [])
1086 ;
1087 PPOpts = pp_opts(Options,ascii,_)
1088 ),
1089 (transition(SrcId,Op,TransId,_Dest) -> true
1090 ; add_internal_error('Cannot find transition: ',get_op_from_id(SrcId,TransId,Options,Params,RetVals)),
1091 transition(S2,Op,TransId,_Dest),
1092 write(found_transition_from(S2,Op,TransId)),nl
1093 ),
1094 create_op_tuple(Op,PPOpts,Params,RetVals).
1095
1096 /**
1097 create_op_tuple(+OpTerm, +PPOpts, -Params, -RetVals)
1098
1099 Creates an operation tuple from transition id, source id, an op term, and a destination id.
1100 If creation is unsuccessful, an error is added and the predicate fails.
1101 See comment for extract_op_tuple for a description of OpTuple
1102 */
1103 create_op_tuple(OpTerm, PPOpts, Params, RetVals) :-
1104 (extract_op_tuple(OpTerm, PPOpts, Params, RetVals) -> true;
1105 add_error_and_fail(prob2_interface, 'Could not create OpTuple ', extract_op_tuple(OpTerm, Params, RetVals))).
1106
1107 /**
1108 extract_op_tuple(+OpTerm, +PPOpts, -Params, -RetVals)
1109
1110 Extracts the parameters and return values of the operations
1111 */
1112 extract_op_tuple(OpTerm, PPOpts, Params, RetVals) :-
1113 (animation_mode(cspm)
1114 -> extract_csp_op(OpTerm, Params, RetVals)
1115 ; animation_mode(csp_and_b),
1116 OpTerm = tau(Tau)
1117 -> translate:translate_csp_tau(Tau, PPTau),
1118 Params=[PPTau], RetVals=[]
1119 ; animation_mode(xtl)
1120 -> extract_xtl_op(OpTerm, Params, RetVals)
1121 ; extract_b_op(OpTerm, PPOpts, Params, RetVals)
1122 ).
1123
1124 /**
1125 extract_csp_op(+OpTerm, -Params, -RetVals)
1126
1127 Extracts information for a CSP operation.
1128 */
1129 extract_csp_op(OpTerm, Params, []) :-
1130 translate_event(OpTerm, PPEvent),
1131 split_atom(PPEvent,['.','!'],[_Op|Params]).
1132
1133 /**
1134 extract_xtl_op(+OpTerm, -Params, -RetVals)
1135
1136 Extracts information for a XTL operation.
1137 */
1138 extract_xtl_op(OpTerm, Params, []) :-
1139 OpTerm =.. [_Name|Args],
1140 maplist(translate_xtl_value,Args,Params).
1141
1142 /**
1143 extract_b_op(+OpTerm, +PPOpts, -Params, -RetVals)
1144
1145 Extracts information for a B operation.
1146 */
1147 extract_b_op(OpTerm, PPOpts, Params, RetVals) :-
1148 extract_b_op_infos(OpTerm, _Name, PSource, RSource),
1149 maplist(pretty_print_bvalue(PPOpts), PSource, Params),
1150 maplist(pretty_print_bvalue(PPOpts), RSource, RetVals).
1151
1152 %! extract_b_op_infos(+Term, -Name, -Arguments, -RetVals)
1153 extract_b_op_infos(Term, Name, Arguments, RetVals) :-
1154 (Term = '-->'(OpTerm,RetVals) -> true;
1155 OpTerm = Term, RetVals = []),
1156 OpTerm =.. [Name|Arguments].
1157
1158 extract_op_name(OpTerm,Name) :-
1159 (animation_mode(cspm) ->
1160 extract_csp_name_and_args(OpTerm, Name, _Args)
1161 ; extract_b_op_infos(OpTerm, Name, _Params, _RetVals)
1162 ).
1163 %! extract_csp_name_and_args(+OpTerm, -Name, -Args)
1164 extract_csp_name_and_args(io(Args,ChName,_SPAN),ChName,Args).
1165 extract_csp_name_and_args(start_cspm(Name), Name, []).
1166 extract_csp_name_and_args(start_cspm_MAIN,'start_cspm_MAIN',[]).
1167 extract_csp_name_and_args(tick(_),tick,[]).
1168 extract_csp_name_and_args(tau(_),tau,[]).
1169 extract_csp_name_and_args(_OP,'?',[]).
1170
1171 set_default_eval_opts(eval_opts(_StateId, ProvideLets, EvalExpand, TimeoutMs)) :-
1172 % Fill in any unbound arguments with default values.
1173 % StateId is currently required and has no automatic default.
1174 (var(ProvideLets) -> ProvideLets = false ; true),
1175 (var(EvalExpand) -> EvalExpand = force ; true), % for compatibility - this isn't a good default...
1176 (var(TimeoutMs) -> TimeoutMs = 30000 ; true).
1177 default_eval_opts(EvalOpts) :-
1178 EvalOpts = eval_opts(_,_,_,_),
1179 set_default_eval_opts(EvalOpts).
1180
1181 /**
1182 parse_eval_opts(-EvalOpts, +Options, -Options0)
1183
1184 Supported options:
1185 * state(StateId): state in which to evaluate the formulas
1186 * provide_stored_let_values: make stored let values visible to the formulas (see eval_let_store module)
1187 * eval_expand(EvalExpand): any of the expand modes supported by store:normalise_value_for_var/4
1188 * timeout(TimeoutMs): per-formula evaluation timeout in milliseconds
1189 */
1190 parse_eval_opts(eval_opts(StateId,ProvideLets,EvalExpand,TimeoutMs), Options, Options4) :-
1191 (selectchk(state(StateId), Options, Options1) -> true ; Options1 = Options),
1192 (selectchk(provide_stored_let_values, Options1, Options2) -> ProvideLets = true ; Options2 = Options1),
1193 (selectchk(eval_expand(EvalExpand), Options2, Options3) -> true ; Options3 = Options2),
1194 (selectchk(timeout(TimeoutMs), Options3, Options4) -> true ; Options4 = Options3).
1195
1196 set_default_pp_opts(pp_opts(Truncate, TransMode, Language)) :-
1197 % Fill in any unbound arguments with default values.
1198 (var(Truncate) -> Truncate = truncate ; true),
1199 (var(TransMode) -> TransMode = unicode ; true),
1200 (var(Language) -> get_language_mode(Language) ; true).
1201
1202 /**
1203 parse_pp_opts(-PPOpts, +Options, -Options0)
1204
1205 Supported options:
1206 * truncate(Truncate): either truncate or expand - controls whether result strings are truncated
1207 * translation_mode(TransMode): any of the modes supported by set_translation_mode/1
1208 * language(Language): any of the languages supported by set_language_mode/1
1209 */
1210 parse_pp_opts(pp_opts(Truncate,TransMode,Language),Options,Options3) :-
1211 (selectchk(truncate(Truncate), Options, Options1) -> true ; Options1 = Options),
1212 % TODO Allow requesting multiple translation modes at once (would be useful for Jupyter)
1213 (selectchk(translation_mode(TransMode), Options1, Options2) -> true ; Options2 = Options1),
1214 (selectchk(language(Language), Options2, Options3) -> true ; Options3 = Options2).
1215
1216 limit_for_pretty_print(truncate,600).
1217 limit_for_pretty_print(expand,-1).
1218
1219 pretty_print_bvalue(pp_opts(Truncate,TransMode,Lang),Formula,Result) :-
1220 set_default_pp_opts(pp_opts(Truncate,TransMode,Lang)),
1221 limit_for_pretty_print(Truncate, Limit),
1222 with_translation_mode(TransMode,
1223 with_language_mode(Lang,
1224 translate_bvalue_with_limit(Formula,Limit,Result))).
1225
1226 pretty_print_bvalue_with_type(pp_opts(Truncate,TransMode,Lang),Formula,Type,Result) :-
1227 set_default_pp_opts(pp_opts(Truncate,TransMode,Lang)),
1228 limit_for_pretty_print(Truncate, Limit),
1229 with_translation_mode(TransMode,
1230 with_language_mode(Lang,
1231 translate_bvalue_with_type_and_limit(Formula,Type,Limit,Result))).
1232
1233 /* ------------------------- */
1234 /* Boolean Properties */
1235 /* ------------------------- */
1236
1237 :- use_module(state_space,[visited_state_corresponds_to_setup_constants_b_machine/1]).
1238 is_constants_set_up_state(ID) :-
1239 b_or_z_mode
1240 -> visited_state_corresponds_to_setup_constants_b_machine(ID)
1241 ; true.
1242
1243 is_initialised_state(ID) :- b_or_z_mode,!,
1244 is_initialised_b_state(ID).
1245 is_initialised_state(ID) :-
1246 visited_expression_id(ID), ID \= root.
1247
1248 :- use_module(state_space,[visited_state_corresponds_to_initialised_b_machine/1]).
1249 is_initialised_b_state(ID) :-
1250 visited_state_corresponds_to_initialised_b_machine(ID).
1251
1252 :- use_module(xtl_interface,[xtl_invariant_violated/1]).
1253 invariantKO(StateID) :- xtl_mode,!,
1254 visited_expression(StateID,State),
1255 xtl_invariant_violated(State).
1256 invariantKO(StateID) :- is_initialised_state(StateID),
1257 %get_state(StateID,State),
1258 if(visited_expression(StateID,State),true,(StateID=root,State=root)),
1259 prepare_state_for_specfile_trans(State,StateID,PreparedState),
1260 tcltk_interface:check_invariantKO(StateID,PreparedState),
1261 state_space:invariant_violated(StateID). % test redundant for B
1262
1263 /**
1264 Takes a state id and finds all of the operations for which a timeout occurred
1265
1266 #### called by:
1267 * ProB Plugin: GetTimeoutedOperationsCommand
1268 * ProB 2.0: GetOperationsWithTimeout
1269 */
1270 op_timeout_occurred(StateID,OpNameList) :-
1271 findall(OpName,time_out_for_node(StateID,OpName,_Type),OpNameList).
1272
1273 inv_timeout_occurred(StateID) :- time_out_for_invariant(StateID).
1274 timeout_occurred(StateID) :- time_out_for_node(StateID).
1275 max_operations_reached(StateID) :- max_reached_for_node(StateID).
1276
1277 /**
1278 state_property(+Property,+StateId,-Status)
1279
1280 Finds the status for a given property
1281 Properties can be: invariantKO, timeout_occurred, max_operations_reached, initialised, explored
1282 Statuses are expected to be boolean values: either true or false
1283
1284 #### called by:
1285 * ProB Plugin: CheckBooleanPropertyCommand
1286 * ProB 2.0: CheckBooleanPropertyCommand
1287 */
1288 state_property(Property,StateId,Status) :-
1289 (state_property2(Property,StateId) -> Status = true ; Status = false).
1290 state_property2(invariantKO,StateId) :- invariantKO(StateId).
1291 state_property2(timeout_occurred,StateId) :- inv_timeout_occurred(StateId) ; timeout_occurred(StateId).
1292 state_property2(virtual_timeout_occurred,StateId) :- virtual_time_out_for_node(StateId).
1293 state_property2(max_operations_reached,StateId) :- max_operations_reached(StateId).
1294 state_property2(valid_state,StateId) :- visited_expression_id(StateId).
1295 state_property2(explored,StateId) :- % the outgoing transitions have been computed
1296 visited_expression_id(StateId), \+ not_all_transitions_added(StateId).
1297 state_property2(constants_set_up,StateId) :- is_constants_set_up_state(StateId).
1298 state_property2(initialised,StateId) :-
1299 (specfile:csp_mode ->
1300 true % in CSP the content of the state is irrelevant for the semantic of the state space
1301 ; is_initialised_state(StateId)
1302 ).
1303
1304
1305 /**
1306 prob2_get_state_errors(+StateId,-Errors)
1307
1308 Takes a id for a given state in the state space and produces a list of all
1309 state based errors.
1310
1311 #### called by:
1312 * ProB 2.0: GetStateBasedErrorsCommand
1313 */
1314 prob2_get_state_errors(StateId,Errors) :-
1315 findall(E, (state_error(StateId,_,Error), convert_error(Error,E)), Errors).
1316
1317 :- use_module(error_manager,[extract_span_description/2]).
1318 convert_error(invariant_violated,_) :- !, fail.
1319 convert_error(eventerror(Event,EError,Trace),error([event(Event),description(Short),long_description(Long)])) :-
1320 !,
1321 translate_event_error(EError,Short),
1322 explain_event_trace(Trace,LongStr,_Span),
1323 safe_atom_codes(Long,LongStr).
1324 convert_error(Error,error([description(Short),long_description(Long)|Tail])) :-
1325 translate_state_error(Error,Short),
1326 explain_state_error(Error,Span,LongStr),
1327 safe_atom_codes(Long,LongStr),
1328 % TODO Also return Span as structured error locations, not just a text description
1329 (extract_span_description(Span,SDescr) ->
1330 Tail = [span_description(SDescr)]
1331 ;
1332 Tail = []
1333 ).
1334
1335 /* ------------------------- */
1336 /* Evaluate Formulas */
1337 /* ------------------------- */
1338
1339 % term in string (see String argument) should be terminated by full-stop!!!
1340 evaluate_csp_expression_string(PlClause,R) :-
1341 read_from_codes(PlClause,PlTerm),
1342 evaluate_csp_expression_aux(PlTerm,R).
1343
1344 :- use_module(probcspsrc(haskell_csp), [evaluate_parsed_csp_expression_with_timing/2]).
1345 evaluate_csp_expression_aux(PlTerm,R) :-
1346 evaluate_parsed_csp_expression_with_timing(PlTerm,Res),
1347 translate:translate_cspm_expression(Res, R).
1348 evaluate_csp_expression_aux(Other,_R) :-
1349 add_error_and_fail(prob2_interface, 'Unexpected CSP Expression: ', Other).
1350
1351 :- assert_must_succeed((X=identifier(none,x),
1352 prob2_evaluate_formulas(
1353 [bexpr(comprehension_set(none,[X],greater(none,mult_or_cart(none,X,X),integer(none,2))))],
1354 [state(root)],
1355 Res
1356 ),
1357 Res = [result(Str,[],_)],
1358 atom_codes(Str,Codes),
1359 (phrase("/*@symbolic*/ ",Codes,C2) -> true ; C2=Codes),
1360 (phrase("{x\x2223\x * x > 2}", C2) ; % string below but with Rodin bar symbol
1361 phrase("{x|x * x > 2}", C2)))).
1362
1363 /**
1364 prob2_evaluate_formulas(+Formulas, +Options, -Results)
1365
1366 Evaluate a list of formulas.
1367 This is more efficient than evaluating each formula individually,
1368 because some calculations (e. g. expanding the current state) don't have to be repeated for each formula.
1369
1370 Supported formula types:
1371 * bpred(Raw)
1372 * bexpr(Raw)
1373 * csp(TermCodes)
1374
1375 Supported options:
1376 * all options supported by parse_eval_opts/3
1377 * all options supported by parse_pp_opts/3
1378
1379 Possible results:
1380 * result(Value,Solutions,Errors): evaluation succeeded
1381 * Value: String rep of the value calculated by ProB
1382 * Solutions: List of solutions as a triple: bind(Name,PPSol)
1383 * Name: Free variable from formula
1384 * PPSol: String representation of the solution bound to the name
1385 * Errors: List of error/3 terms for non-fatal errors (warnings or messages) that occurred during evaluation
1386 * errors(Value,Errors): Typechecking or evaluation failed
1387 * Value: Short description of error type (e. g. 'NOT-WELL-DEFINED', 'UNKNOWN')
1388 * Errors: List of error/3 terms for all errors that occurred
1389 * enum_warning: An enumeration warning was thrown during evaluation
1390 */
1391 prob2_evaluate_formulas(Formulas, Options, Results) :-
1392 parse_eval_opts(EvalOpts, Options, Options1),
1393 set_default_eval_opts(EvalOpts),
1394 EvalOpts = eval_opts(StateId,ProvideLets,_,_),
1395 parse_pp_opts(PPOpts,Options1,[]),
1396 % useful for certain external functions in LibraryMeta.def, e.g., ENABLED, EVAL_OVER_HISTORY, CHANGED, ...:
1397 set_current_state_for_external_fun(StateId),
1398 call_cleanup(
1399 (get_bstate_with_deferred_sets_for_formulas(StateId,Formulas,ProvideLets,State,StateKind),
1400 % _Machine is shared across all calls so that full_b_machine only needs to be computed once.
1401 maplist(evaluate_formula_in_state(EvalOpts,PPOpts,StateKind,State,_Machine),Formulas,Results)
1402 ),
1403 clear_state_for_external_fun).
1404
1405 evaluate_formula_in_state(EvalOpts, PPOpts, StateKind, State, Machine, Formula, Result) :-
1406 evaluate_formula_in_state_aux(Formula, EvalOpts, PPOpts, StateKind, State, Machine, Result).
1407
1408 evaluate_formula_in_state_aux(csp(Raw), _EvalOpts, _PPOpts, _StateKind, _State, _Machine, R) :- !,
1409 ( evaluate_csp_expression_string(Raw,Res) ->
1410 R = result(Res,[],[]);
1411 R = errors('UNKNOWN',[error('Unexpected CSP Expression',internal_error,[])])).
1412 evaluate_formula_in_state_aux(registered(FormulaID), EvalOpts, PPOpts, StateKind, State, _Machine, R) :-
1413 !,
1414 (prob2_formula(FormulaID, Typed, Requirements) ->
1415 evaluate_typechecked_b_formula_in_state(StateKind, Requirements, State, Typed, EvalOpts, PPOpts, R)
1416 ;
1417 R = errors('ERROR', [error('No formula registered with this UUID',internal_error,[])])
1418 ).
1419 evaluate_formula_in_state_aux(Formula, EvalOpts, PPOpts, StateKind, State, Machine, R) :-
1420 %logger:writeln_log_time(typechecking_raw(PredOrExpr)),
1421 (formula_typecheck_for_eval(Formula,EvalOpts,Machine,Typed) ->
1422 %logger:writeln_log_time(evaluate_typechecked_b_formula_in_state(StateKind)),
1423 %print('EVAL:'),nl,translate:print_bexpr(Typed),nl,
1424 evaluate_typechecked_b_formula_in_state(StateKind,formula(Typed),State,Typed,EvalOpts,PPOpts,R)
1425 ;
1426 get_all_errors_with_span_info_and_reset(Errors),
1427 R = errors('ERROR',Errors)
1428 ).
1429
1430 :- use_module(eval_let_store, [extend_state_with_stored_lets/2]).
1431 % Kind is empty_state, constants_only_state, full_initialised_state
1432 get_bstate_with_deferred_sets_for_formulas(StateId,Formulas,ProvideLets,State,Kind) :-
1433 (Formulas=[_], % we have a single untyped formula
1434 StateId \= root, \+ is_concrete_constants_state_id(StateId) % otherwise get_state_for_b_formula will raise error
1435 -> Kind = not_yet_obtained, % obtain state later, after formula has been type checked and we know what it needs
1436 State = lazy_get_state(StateId,ProvideLets)
1437 ; get_bstate_with_deferred_sets(StateId,ProvideLets,State,Kind)
1438 ).
1439 get_bstate_with_deferred_sets(StateId,ProvideLets,State,Kind) :-
1440 get_state_with_kind(StateId, State1,Kind,_CstID),
1441 add_prob_deferred_set_elements_to_store(State1, State2, visible),
1442 (ProvideLets = true -> extend_state_with_stored_lets(State2, State) ; State = State2).
1443
1444 get_bstate_with_deferred_sets_for_b_formula(StateId,TypedFormula,ProvideLets,State) :-
1445 get_state_for_b_formula(StateId,TypedFormula,State1),
1446 add_prob_deferred_set_elements_to_store(State1, State2, visible),
1447 (ProvideLets = true -> extend_state_with_stored_lets(State2, State) ; State = State2).
1448
1449 /**
1450 prob2_get_formula_type(+Formula,-PPType,-Errors)
1451
1452 Type checks the given untyped formula to determine its type and any type errors.
1453
1454 #### Params:
1455 * Formula - bexpr(Raw) or bpred(Raw), where Raw is the Prolog representation of non-typechecked expression or predicate
1456 * PPType - pretty-printed type of formula
1457 * Errors - any errors that have occured during typechecking
1458
1459 #### called by:
1460 ProB 2.0: FormulaTypecheckCommand
1461 */
1462 prob2_get_formula_type(Formula,PPType,Errors) :-
1463 default_eval_opts(EvalOpts),
1464 formula_typecheck2_for_eval(Formula,EvalOpts,_,TypedFormula,PErrors),
1465 add_all_perrors(PErrors),
1466 get_texpr_type(TypedFormula,Type),
1467 translate:pretty_type(Type,PPType),
1468 get_all_errors_with_span_info_and_reset(Errors).
1469
1470 formula_typecheck_for_eval(Formula,EvalOpts,M,TypedFormula) :-
1471 formula_typecheck2_for_eval(Formula,EvalOpts,M,TypedFormula,PErrors),
1472 add_all_perrors(PErrors),
1473 no_real_perror_occurred(PErrors).
1474
1475 % this predicate returns the internal Prolog type:
1476 %! formula_typecheck2_for_eval(+PredOrExpr,+EvalOpts,?Machine,+RawFormula,-TypedFormula,-Type,-Errors)
1477 formula_typecheck2_for_eval(bpred(Raw),EvalOpts,M,Typed,PErrors) :-
1478 !, predicate_typecheck_for_eval(M,Raw,EvalOpts,Typed,PErrors).
1479 formula_typecheck2_for_eval(bexpr(Raw),EvalOpts,M,Typed,PErrors) :-
1480 !, expression_typecheck_for_eval(M,Raw,EvalOpts,Typed,PErrors).
1481 formula_typecheck2_for_eval(Else,_,_M,_Typed,_PErrors) :-
1482 add_error_and_fail(prob2_interface,'Unsupported formula term:', Else),fail.
1483
1484 predicate_typecheck_for_eval(Raw,Typed) :-
1485 predicate_typecheck_for_eval(_,Raw,Typed).
1486 predicate_typecheck_for_eval(M,Raw,Typed) :-
1487 set_default_eval_opts(EvalOpts),
1488 predicate_typecheck_for_eval(M,Raw,EvalOpts,Typed,PErrors),
1489 add_all_perrors(PErrors),
1490 no_real_perror_occurred(PErrors).
1491 predicate_typecheck_for_eval(M,Raw,EvalOpts,Typed,PErrors) :-
1492 get_eval_scope_with_opts(EvalOpts,Scope), % TODO: pass options
1493 bmachine:b_type_open_predicate_for_full_b_machine(M,open(exists),Raw,Scope,Typed,PErrors).
1494
1495 :- use_module(bmachine,[b_is_variable/2, b_is_constant/2, b_type_expression_for_full_b_machine/6]).
1496 expression_typecheck_for_eval(Raw,Typed) :-
1497 expression_typecheck_for_eval(_,Raw,Typed).
1498 expression_typecheck_for_eval(M,Raw,Typed) :-
1499 set_default_eval_opts(EvalOpts),
1500 expression_typecheck_for_eval(M,Raw,EvalOpts,Typed,PErrors),
1501 add_all_perrors(PErrors),
1502 no_real_perror_occurred(PErrors).
1503 expression_typecheck_for_eval(_,identifier(Pos,ID),_,Typed,PErrors) :-
1504 (b_is_variable(ID,Type) ; b_is_constant(ID,Type)),
1505 !, % hack to avoid type-checking simple identifiers which just need to be looked up in state
1506 PErrors=[], Typed = b(identifier(ID),Type,[nodeid(Pos)]).
1507 expression_typecheck_for_eval(M,Raw,EvalOpts,Typed,PErrors) :-
1508 get_eval_scope_with_opts(EvalOpts,Scope), % TODO: pass options
1509 b_type_expression_for_full_b_machine(M,Raw,Scope,_Type,Typed,PErrors).
1510
1511 :- use_module(eval_let_store,[get_stored_let_typing_scope/1, reset_let_values/0]).
1512
1513 % a more conservative version, only add external libraries if requested
1514 get_eval_scope_with_opts(eval_opts(_,ProvideLets,_,_),Scope) :- !,
1515 (ProvideLets=true -> get_eval_scope_with_opts([provide_stored_let_values],Scope)
1516 ; get_eval_scope_with_opts([],Scope)).
1517 get_eval_scope_with_opts(Options,Scope) :-
1518 (member(provide_stored_let_values,Options),
1519 reset_let_values, % purge all invalid values
1520 get_stored_let_typing_scope(Scope1) % make stored values available; TODO: they also need to be added to the state with extend_state_with_stored_lets
1521 -> Scope = [Scope1|Scope2]
1522 ; Scope=Scope2),
1523 (member(all_available_libraries,Options) -> get_eval_scope(all,Scope2) ; get_eval_scope(safe,Scope2)).
1524
1525 % get scope for typechecker:
1526 get_eval_scope(Scope) :- get_eval_scope(all,Scope).
1527 get_eval_scope(ExtKind,[prob_ids(visible),Scope,
1528 external_library(Libs)]) :-
1529 % external_library for VisB and Debugging; TODO: should we only make it available in some contexts
1530 % Note: the external_library entries must come after Scope
1531 get_main_eval_scope(Scope),
1532 get_libraries(ExtKind,Libs).
1533 get_main_eval_scope(assertions_scope_and_additional_defs) :-
1534 get_preference(allow_operation_calls_in_expr,true),!.
1535 get_main_eval_scope(variables_and_additional_defs).
1536
1537 get_libraries(all,all_available_libraries).
1538 get_libraries(_,safe_available_libraries).
1539
1540
1541 % TODO Can the evaluation code be integrated with eval_strings again, and/or merged with bvisual2?
1542
1543 :- use_module(tools_meta,[safe_time_out/3]).
1544 % NOTE: This predicate always resets the error manager.
1545 % Any errors, warnings, etc. that occurred will be returned inside Result,
1546 % including any errors that occurred *before* this predicate is called!
1547 evaluate_typechecked_b_formula_in_state(StateKind,Requirements,State,Typed,EvalOpts,PPOpts,Result) :-
1548 ( State=lazy_get_state(StateId,ProvideLets),
1549 get_bstate_with_deferred_sets_for_b_formula(StateId,Typed,ProvideLets,RealState)
1550 % TO DO: we could try and get only those identifiers that are really used
1551 -> evaluate_typechecked_b_formula_in_state(RealState,Typed,EvalOpts,PPOpts,Result)
1552 ; requirements_met(Requirements,StateKind) ->
1553 evaluate_typechecked_b_formula_in_state(State,Typed,EvalOpts,PPOpts,Result)
1554 ;
1555 get_all_errors_with_span_info_and_reset(Errors),
1556 % TODO: extend ProB2 to recognise new error message:
1557 % (Requirements=requires_constants -> EMsg = 'NOT-INITIALISED' ; EMsg = 'CONSTANTS-NOT-SETUP'),
1558 Result = errors('NOT-INITIALISED',Errors)
1559 ).
1560 evaluate_typechecked_b_formula_in_state(State,Typed,eval_opts(_StateId,_ProvideLets,EvalExpand,TO),PPOpts,Result) :-
1561 safe_time_out(
1562 catch_enumeration_warning_exceptions(
1563 evaluate_formula_eval(State,Typed,EvalExpand,Res,Solution),
1564 Res = enum_warning),
1565 TO,TimeOutRes),
1566 (TimeOutRes=time_out -> Res=error(time_out) ; true),
1567 (real_error_occurred -> RealError = real_error ; RealError = no_real_error),
1568 get_all_errors_with_span_info_and_reset(Errors),
1569 extract_result(Res,Typed,Solution,PPOpts,Errors,RealError,Result).
1570
1571 extract_result(enum_warning,_,_,_,_,_,R) :- !, R=enum_warning.
1572 extract_result(error(ErrDesc),_,_Sol,_PPOpts,Errors,_RealError,Result) :- !,
1573 Result = errors(ErrDesc, Errors).
1574 extract_result(value(Term),Typed,Solutions,PPOpts,Errors,RealError,Result) :- !,
1575 get_texpr_type(Typed, Type),
1576 pretty_print_bvalue_with_type(PPOpts,Term,Type,R),
1577 (RealError == no_real_error ->
1578 % TODO: get the type of each of the solutions and pass it to the pretty print
1579 prettyprint_solutions(PPOpts,Solutions,PPSol),
1580 Result = result(R,PPSol,Errors)
1581 ;
1582 Result = errors(R,Errors)
1583 ).
1584
1585 %:- use_module(eval_strings,[eval_predicate/5]). % TODO: export and refactor
1586 % TO DO: move this into another more general module:
1587 evaluate_formula_eval(State,Typed,_EvalExpand,Res,LocalState) :-
1588 get_texpr_type(Typed,pred),
1589 !,
1590 eval_predicate(State,Typed,Res,LocalState).
1591 evaluate_formula_eval(State,Typed,EvalExpand,Res,[]) :-
1592 evaluate_expression(State,Typed,EvalExpand,Res).
1593
1594 :- use_module(clpfd_interface,[catch_clpfd_overflow_call2/2]).
1595 :- use_module(error_manager,[enter_new_error_scope/2, exit_error_scope/3,clear_all_errors_in_error_scope/1,
1596 event_occurred_in_error_scope/1, abort_error_occured_in_error_scope/0]).
1597 :- use_module(store,[normalise_value_for_var/4]).
1598 % a simplified/modified version of eval_strings:eval_expression
1599 % evaluate an expression Typed in an expanded state EState giving string result Result and Prolog value NValue
1600 evaluate_expression(EState,Typed,EvalExpand,Term) :-
1601 enter_new_error_scope(ScopeID,evaluate_expression),
1602 clear_all_errors_in_error_scope(ScopeID),
1603 %replace_expression_by_kodkod_if_enabled(Typed,Typed2),
1604 catch_clpfd_overflow_call2(b_interpreter:b_compute_expression_nowf(Typed,[],EState,Value,'ProB2',0),fail), % We could return CLPFD overflow error result
1605 !,
1606 %logger:writeln_log_time(normalise_value_for_var(evaluate_expression)),
1607 normalise_value_for_var(evaluate_expression,EvalExpand,Value,NValue),
1608 get_unknown_error_result(ErrRes),
1609 exit_error_scope(ScopeID,ErrOcc,evaluate_expression),
1610 % FIXME Is ErrOcc ever true here?
1611 % For WD errors, b_compute_expression_nowf fails, so this code is never reached.
1612 % Enumeration warnings are thrown as exceptions and so also bypass this code.
1613 (ErrOcc=true
1614 -> Term = error(ErrRes)
1615 ; Term = value(NValue)
1616 ).
1617 evaluate_expression(_,_,_,error(ErrRes)) :-
1618 get_unknown_error_result(ErrRes),
1619 exit_error_scope(_ScopeID,_,evaluate_expression).
1620
1621 % which result should be displayed in case of failure/errors:
1622 get_unknown_error_result(ErrRes) :-
1623 (abort_error_occured_in_error_scope -> ErrRes = 'NOT-WELL-DEFINED' ; ErrRes = 'UNKNOWN').
1624
1625 % a simplified/modified version of eval_strings:eval_predicate_aux
1626 eval_predicate(State, ExTyped,Result,LocalState) :-
1627 enter_new_error_scope(ScopeID,eval_predicate), clear_all_errors_in_error_scope(ScopeID),
1628 (catch_clpfd_overflow_call2(prob2_interface:eval_predicate2(State, ExTyped,LocalState,Res),
1629 fail)
1630 -> true
1631 ; event_occurred_in_error_scope(enumeration_warning(_,_,_,_,_Critical))
1632 -> Res=enum_warning
1633 ; eval_predicate2_fail_result(ExTyped,Res) % either value(pred_true) or value(pred_false)
1634 ),
1635 get_unknown_error_result(ErrRes),
1636 exit_error_scope(ScopeID,ErrOcc,eval_predicate),
1637 (ErrOcc=true
1638 -> Result = error(ErrRes)
1639 ; Result = Res
1640 ).
1641
1642 :- use_module(probsrc(bsyntaxtree), [safe_create_texpr/4]).
1643 :- use_module(eval_strings, []).
1644 eval_predicate2(State, ExTyped,LocalState,value(pred_true)) :-
1645 eval_strings:is_existential_quantifier(ExTyped,Parameters,Typed), % TO DO: move to module
1646 !,
1647 test_bool_exists(State, Parameters,Typed,LocalState).
1648 eval_predicate2(State, ExTyped,LocalState,value(pred_false)) :-
1649 is_universal_quantifier(ExTyped,Parameters,TypedLHS,TypedRHS),
1650 !,
1651 safe_create_texpr(negation(TypedRHS),pred,[try_smt],NegRHS),
1652 conjunct_predicates([TypedLHS,NegRHS],Conjunction), % replace Kodkod?
1653 test_bool_exists(State, Parameters,Conjunction,LocalState).
1654 eval_predicate2(State, Typed,LocalState,value(pred_true)) :- LocalState=[],
1655 b_test_boolean_expression_cs(Typed,LocalState,State,'ProB2-Java',0).
1656
1657 % what should the result be if the above eval_predicate2 fails (without enumeration warning):
1658 eval_predicate2_fail_result(ExTyped,Res) :-
1659 is_universal_quantifier(ExTyped,_,_,_),!, Res=value(pred_true).
1660 eval_predicate2_fail_result(_,value(pred_false)).
1661
1662
1663 test_bool_exists(EState, Parameters,Typed,LocalState) :-
1664 kernel_waitflags:init_wait_flags(WF,[test_bool_exists]),
1665 b_interpreter:set_up_typed_localstate(Parameters,_FreshOutputVars,TypedVals,[],LocalState,positive),
1666 b_enumerate:b_tighter_enumerate_values_in_ctxt(TypedVals,Typed,WF),
1667 b_interpreter:b_test_boolean_expression(Typed,LocalState,EState,WF),
1668 kernel_waitflags:ground_wait_flags(WF).
1669
1670 is_universal_quantifier(b(forall(Parameters,LHS,RHS),pred,_),Parameters,LHS,RHS).
1671
1672 :- dynamic prob2_formula/3.
1673
1674 :- use_module(bmachine, [determine_type_of_formula/2]).
1675 register_prob2_formula1(_, FormulaUUID, _) :- prob2_formula(FormulaUUID,_,_),!.
1676 register_prob2_formula1(M, FormulaUUID, Formula) :-
1677 default_eval_opts(EOpts),
1678 formula_typecheck_for_eval(Formula,EOpts,M,Typed),
1679 determine_type_of_formula(Typed,Requirements),
1680 assertz(prob2_formula(FormulaUUID, Typed, Requirements)).
1681
1682 %! register_prob2_formulas(+FormulaUUIDs, +Formulas)
1683 register_prob2_formulas(FormulaUUIDs,Formulas) :-
1684 % _Machine is shared across all calls so that full_b_machine only needs to be computed once.
1685 maplist(register_prob2_formula1(_Machine),FormulaUUIDs,Formulas).
1686
1687
1688 % TO DO: determine upon registering whether a formula reads nothing, just constants, or also variables
1689
1690 % unregister a single or a list of formula ids:
1691 unregister_prob2_formula(FormulaUUID) :- retractall(prob2_formula(FormulaUUID,_,_)).
1692 unregister_prob2_formulas(Fs) :- maplist(unregister_prob2_formula,Fs).
1693
1694
1695 % check whether we can evaluate the formula in the state:
1696 requirements_met(requires_nothing,_).
1697 requirements_met(requires_constants,constants_only_state).
1698 requirements_met(requires_constants,full_initialised_state).
1699 requirements_met(requires_variables,full_initialised_state).
1700 requirements_met(formula(Typed),State) :-
1701 (State=full_initialised_state -> true
1702 ; determine_type_of_formula(Typed,Requirements), requirements_met(Requirements,State)).
1703
1704
1705
1706 % API for showing Tk Animation Images in Java FX (or other):
1707 :- use_module(extrasrc(graphical_state_viewer_images),[get_animation_images/1,
1708 get_animation_image_grid/6, get_react_to_item_right_click_options/4, react_to_item_right_click/6]).
1709 get_animation_image_list(ImageList) :- get_animation_images(ImageList).
1710 % Format: [image_file(0,'images/empty_box_white.gif'),...,image_file(6,'images/F.gif')]
1711
1712 get_animation_image_matrix_for_state(ID,Matrix,MinRow,MaxRow,MinCol,MaxCol) :-
1713 (get_animation_image_grid(ID,M,M1,M2,M3,M4)
1714 -> Matrix=M, MinRow=M1, MaxRow=M2, MinCol=M3, MaxCol=M4
1715 ; Matrix=[], MinRow = -1, MaxRow = 0, MinCol = -1, MaxCol = 0).
1716 % Format: [entry(1,1,image(0)),... entry(2,3,text(some_atom)),...], entry(Row,Col,ImgOrText)
1717
1718 % returns a list of terms option(transition_term, description) for the various options that are available in the state ID
1719 % for Row/Col (Y/X)
1720 get_react_to_item_right_click_options_for_state(ID,Row,Col,Options) :-
1721 get_react_to_item_right_click_options(ID,Col,Row,Options).
1722
1723 % should be called for one option provided by get_react_to_item_right_click_options_for_state
1724 react_to_item_right_click_option_for_state(ID,Row,Col,Option,TransitionID,NewID) :-
1725 react_to_item_right_click(ID,Col,Row,Option,TransitionID,NewID).
1726
1727 % | ?- prob2_interface:get_react_to_item_right_click_options_for_state(3,1,1,L).
1728 % L = ['Set(1,1,1)','Set(1,1,2)','Set(1,1,3)','Solve'|...] ?
1729 % | ?- prob2_interface:react_to_item_right_click_option_for_state(3,1,1,'Set(1,1,1)',NewID).
1730 % Performed: Set(int(1),int(1),int(1))
1731 % NewID = ..., TransitionID=...
1732
1733 /**
1734 get_states_for_predicate(+Raw,-States,-Errors)
1735
1736 Takes a predicate and finds a list of all state ids for which the
1737 predicate holds. The states that are not intitialized (i.e. root) are
1738 included in the list. The list that is returned is therefore the union
1739 of the uninitialised states and the states for which the predicate holds.
1740
1741 #### called by:
1742 * ProB 2.0: GetStatesFromPredicate
1743 */
1744 get_states_for_predicate(Raw,States,Errors) :-
1745 (predicate_typecheck_for_eval(Raw,Typed) ->
1746 findall(StateId,get_state_for_predicate(StateId,Typed),States),
1747 Errors = []
1748 ;
1749 States = [],
1750 get_all_errors_with_span_info_and_reset(Errors)
1751 ).
1752
1753 get_state_for_predicate(StateId,Typed) :-
1754 state_space:visited_expression(StateId,StatePacked),
1755 ( is_initialised_state(StateId) ->
1756 expand_const_and_vars_to_full_store(StatePacked,State),
1757 b_test_boolean_expression_cs(Typed,[],State,'ProB2-Java',0)
1758 ;
1759 true
1760 ).
1761
1762 /**
1763 This cycles through all of the solutions and extracts the string
1764 representation of the solutions.
1765 */
1766 prettyprint_solutions(_PPOpts,[],[]).
1767 prettyprint_solutions(PPOpts,[bind(Name,Res)|T],[PP|R]) :-
1768 pretty_print_bvalue(PPOpts,Res,PPRes),
1769 PP = solution(Name,PPRes),
1770 prettyprint_solutions(PPOpts,T,R).
1771
1772 /**
1773 filter_states_for_predicate(+Raw,+States,-Filtered)
1774
1775 Takes a list of state ids and a predicate and finds all of the states
1776 for which the predicate is true
1777
1778 #### called by:
1779 * ProB 2.0: FilterStatesForPredicateCommand
1780 */
1781 filter_states_for_predicate(Raw,States,Filtered) :-
1782 (predicate_typecheck_for_eval(Raw,Typed) ->
1783 filter_states_for_typed_predicate(Typed,States,Filtered)
1784 ;
1785 get_all_errors_with_span_info_and_reset(Errors),
1786 Filtered = errors(Errors)
1787 ).
1788
1789 filter_states_for_typed_predicate(_,[],[]).
1790 filter_states_for_typed_predicate(Typed,[Id|States],Filtered) :-
1791 get_bstate_with_deferred_sets(Id,false,State,Kind),
1792 ( Kind = full_initialised_state -> %is_initialised_state(Id) ->
1793 (b_test_boolean_expression_cs(Typed,[],State,'ProB2-Java',0) ->
1794 Filtered = [Id|Rest] ;
1795 Filtered = Rest
1796 )
1797 ; Filtered = [Id|Rest]
1798 ),
1799 filter_states_for_typed_predicate(Typed,States,Rest).
1800
1801 /* ------------------------- */
1802 /* Formula Expansion */
1803 /* ------------------------- */
1804
1805 /**
1806 get_top_level_formulas(-TopIds)
1807
1808 Gets all top-level formula IDs from bvisual2.
1809
1810 #### called by:
1811 * ProB 2.0: GetTopLevelFormulasCommand
1812 */
1813 get_top_level_formulas(TopIds) :-
1814 suppress_rodin_positions(C),
1815 bv_get_top_level(TopIds),
1816 reset_suppress_rodin_positions(C).
1817
1818 /**
1819 insert_formula_for_expansion(+AST,-Id)
1820
1821 Inserts a formula into bvisual2 module
1822 The formula is inserted as a child of level "user" in bvisual2
1823
1824 #### called by:
1825 * ProB 2.0: InsertFormulaForVisualizationCommand
1826 */
1827 insert_formula_for_expansion(Typed,Id) :- Typed = b(_,_,_),!,
1828 suppress_rodin_positions(C),
1829 bv_insert_formula(Typed,user,Id),
1830 reset_suppress_rodin_positions(C).
1831
1832 insert_formula_for_expansion(AST,Id) :-
1833 suppress_rodin_positions(C),
1834 b_type_expression(AST,[variables],_,Typed,Errors),
1835 ( Errors == [] ->
1836 bv_insert_formula(Typed,user,Id),
1837 reset_suppress_rodin_positions(C)
1838 ;
1839 add_all_perrors(Errors), reset_suppress_rodin_positions(C),
1840 fail).
1841
1842 /**
1843 prob2_evaluate_bvisual2_formulas(+Ids,+StateId,-Values)
1844
1845 Uses the bvisual2 module to evaluate the given formulas.
1846 Unlike expand_formula_nonrecursive/6, this predicate only evaluates the formulas,
1847 but doesn't return their label, description, or subformulas.
1848
1849 #### called by:
1850 * ProB 2.0: EvaluateBVisual2FormulasCommand
1851 */
1852 prob2_evaluate_bvisual2_formulas(Ids,StateId,Values) :-
1853 prob2_evaluate_bvisual2_formulas(Ids,StateId,[],Values).
1854
1855 /**
1856 prob2_evaluate_bvisual2_formulas(+Ids,+StateId,+Options,-Values)
1857
1858 New version of the above predicate which also supports options.
1859 Currently supported options:
1860 - unlimited: does not truncate terms
1861 */
1862 prob2_evaluate_bvisual2_formulas(Ids,StateId,Options,Values) :-
1863 (member(unlimited,Options) ->
1864 bv_get_values_unlimited(Ids,StateId,Values)
1865 ; bv_get_values(Ids,StateId,Values)).
1866
1867 /**
1868 prob2_expand_bvisual2_formula(+FormulaId,+Options,-ExpandedFormula)
1869
1870 Uses the bvisual2 module to expand a specified formula,
1871 optionally also expanding child formulas recursively and/or evaluating all expanded formulas.
1872 FormulaId must be a bvisual2 formula ID,
1873 as returned for example by get_top_level_formulas/1, insert_formula_for_expansion/2, or prob2_expand_bvisual2_formula/3.
1874
1875 #### called by:
1876 * ProB 2.0: ExpandBVisual2FormulaCommand
1877 */
1878 prob2_expand_bvisual2_formula(FormulaId,Options,ExpandedFormula) :-
1879 % Check that no unknown or duplicate options were passed.
1880 (selectchk(evaluate(_), Options, Options1) -> true ; Options1 = Options),
1881 (selectchk(recursive, Options1, Options2) -> true ; Options2 = Options1),
1882 Options2 == [],
1883
1884 suppress_rodin_positions(C),
1885 expand_bvisual2_formula_internal(Options,FormulaId,ExpandedFormula),
1886 reset_suppress_rodin_positions(C).
1887
1888 expand_bvisual2_formula_internal(Options,FormulaId,formula(Entries)) :-
1889 findall(Attribute, bvisual2_formula_attribute(FormulaId,Options,Attribute), Entries).
1890
1891 bvisual2_formula_attribute(FormulaId,_,id(FormulaId)).
1892 bvisual2_formula_attribute(FormulaId,_,description(Desc)) :-
1893 (bv_formula_description(FormulaId,Description) -> true ; Description=''),
1894 bv_formula_origin(FormulaId,Origin), % TODO: store this as a seperate attribute
1895 (Description='' -> Origin \= '', Desc = Origin
1896 ; Origin='' -> Desc = Description
1897 ; ajoin([Description,'\n',Origin],Desc)).
1898 bvisual2_formula_attribute(FormulaId,_,functor_symbol(FunctorSymbol)) :-
1899 bv_get_formula_functor_symbol(FormulaId,FunctorSymbol).
1900 bvisual2_formula_attribute(FormulaId,_,rodin_labels(Labels)) :-
1901 bv_formula_labels(FormulaId,Labels).
1902 bvisual2_formula_attribute(FormulaId,_,proof_info(DischargedInfo)) :-
1903 bv_formula_discharged_info(FormulaId,DischargedInfo).
1904 bvisual2_formula_attribute(FormulaId,Options,value(EvaluatedValue)) :-
1905 memberchk(evaluate(StateId), Options),
1906 % TODO Refactor to combine multiple bv_get_values calls?
1907 bv_get_values([FormulaId], StateId, [EvaluatedValue]).
1908 bvisual2_formula_attribute(FormulaId,_,type(Type)) :-
1909 (bv_is_typed_predicate(FormulaId) ->
1910 Type = predicate;
1911 (bv_is_typed_formula(FormulaId) -> Type = expression; Type = other)).
1912 bvisual2_formula_attribute(FormulaId,Options,Attribute) :-
1913 bv_expand_formula(FormulaId,Label,ChildrenIds),
1914 (Attribute = label(Label) ; bvisual2_formula_children_attribute(ChildrenIds,Options,Attribute)).
1915
1916
1917 bvisual2_formula_children_attribute(ChildrenIds,Options,children(ExpandedChildren)) :-
1918 memberchk(recursive, Options),
1919 !,
1920 maplist(expand_bvisual2_formula_internal(Options), ChildrenIds, ExpandedChildren).
1921 bvisual2_formula_children_attribute(ChildrenIds,_,children_ids(ChildrenIds)).
1922
1923
1924 /* ------------------------- */
1925 /* Model Checking */
1926 /* ------------------------- */
1927
1928 /**
1929 do_modelchecking(+MaxNumberOfStatesToCheck,+Time,+Options,-Result,-Stats)
1930
1931 #### do_modelchecking(+MaxNumberOfStatesToCheck, +Time,+Options,-Result,stats(-NrNodes,-NrTrans,-NrProcessed))
1932 * +MaxNumberOfStatesToCheck : maximum number of states to be checked
1933 * +Time : Timeout specified by the user in ms
1934 * +Options : List of options specified by the user. Used for predicate do_modelchecking(Time,Options,Result)
1935 * -NrNodes : total number of nodes in state space. Calculated with get_state_space_stats
1936 * -NrTrans : total number of nodes in state space. Calculated with get_state_space_stats
1937 * -NrProcessed : total number of calculated nodes in state space. Calculated with get_state_space_stats
1938 When Time Milliseconds have elapsed the modelchecker should stop after its next step
1939
1940 #### called by:
1941 * ProB Plugin: ModelCheckingCommand
1942 * ProB 2.0: ModelCheckingStepCommand
1943 */
1944 do_modelchecking(MaxNumberOfStatesToCheck, Time, Options, Result, stats(NrNodes,NrTrans,NrProcessed)) :-
1945 statistics(walltime, [CurTime,_]), /* get current time in ms */
1946 LimitTime is CurTime+Time,
1947 option_set(find_deadlocks, Options, Deadlock),
1948 option_set(find_invariant_violations, Options, Invariant),
1949 option_set(find_assertion_violations, Options, Assertions),
1950 (option_set(ignore_state_errors, Options, 1) -> FindStateErrors=0 ; FindStateErrors=1),
1951 option_set(inspect_existing_nodes, Options, InspectExistingNodes),
1952 option_set(stop_at_full_coverage, Options, StopAtFullCoverage),
1953 (option_set(breadth_first_search, Options, 1) -> set_depth_breadth_first_mode(breadth_first) ;
1954 option_set(depth_first_search, Options, 1) -> set_depth_breadth_first_mode(depth_first) ;
1955 set_depth_breadth_first_mode(mixed)),
1956 option_set(find_goal, Options, Goal),
1957 get_preference(por,WithPOR),
1958 tcltk_interface:do_model_check(MaxNumberOfStatesToCheck, _, LimitTime, Res, Deadlock, Invariant, Goal,Assertions,
1959 FindStateErrors,StopAtFullCoverage, WithPOR, InspectExistingNodes),
1960 build_modelcheck_return(Res, Result),
1961 get_state_space_stats(NrNodes, NrTrans, NrProcessed).
1962
1963
1964 /**
1965 set_goal_for_model_checking(+Goal)
1966
1967 Sets the goal for model checking. The Option search_for_goal needs to be set when starting
1968 model checking in order for this to have an effect on the model checking.
1969
1970 #### called by:
1971 * ProB 2.0: SetBGoalCommand
1972 */
1973 set_goal_for_model_checking(Goal) :-
1974 predicate_typecheck_for_eval(Goal,TypedGoal),
1975 b_set_parsed_typed_machine_goal(TypedGoal).
1976
1977 /**
1978 reset_goal_for_model_checking
1979
1980 Reset the goal for model checking. Will remove a saved custom goal and load the goal from DEFINITIONS if it exists.
1981
1982 #### called by:
1983 * ProB 2.0: ResetBGoalCommand
1984 */
1985 :- use_module(probsrc(bmachine), [b_unset_machine_goal/0, b_reset_machine_goal_from_DEFINITIONS/0]).
1986 reset_goal_for_model_checking :-
1987 b_unset_machine_goal,
1988 (b_or_z_mode -> (b_reset_machine_goal_from_DEFINITIONS ; true) ; true),
1989 !.
1990
1991 /**
1992 option_set(+Element, +List, -Result)
1993
1994 Takes an atom and unifies Result with 1 if the atom is in the List.
1995 Otherwise, Result is unified with 0.
1996 */
1997 option_set(Element, List, Result) :-
1998 ( member(Element,List)
1999 -> Result = 1
2000 ; Result = 0).
2001
2002 %! build_modelcheck_return(+MCRes, -JavaResult)
2003 build_modelcheck_return(MCRes, JavaResult) :-
2004 build_modelcheck_return2(MCRes, JavaResult) -> true
2005 ; nl, print('### Unknown Model Check Error Result:'), print(MCRes), nl, /* TODO: Why do we print something here? Can we get rid of this print? (Q? from Joy)*/
2006 current_state_id(State), JavaResult=general_error(State, MCRes).
2007
2008 build_modelcheck_return2(no, not_yet_finished(100000)).
2009 build_modelcheck_return2([timeout,N], not_yet_finished(N1)) :- N1 is 100000 - N.
2010 build_modelcheck_return2(deadlock, deadlock(State)):- current_state_id(State).
2011 build_modelcheck_return2(invariant_violation, invariant_violation(State)):- current_state_id(State).
2012 build_modelcheck_return2(xtl_error, xtl_error(State)):- current_state_id(State).
2013 build_modelcheck_return2(assertion_violation, assertion_violation(State)):- current_state_id(State).
2014 build_modelcheck_return2(state_error(_), state_error(State)):- current_state_id(State).
2015 build_modelcheck_return2(goal_found, goal_found(State)) :- current_state_id(State).
2016 build_modelcheck_return2(well_definedness_error, well_definedness_error(State)) :- current_state_id(State).
2017 build_modelcheck_return2(general_error_occurred, general_error(State)):- current_state_id(State).
2018 build_modelcheck_return2(full_coverage, full_coverage).
2019 build_modelcheck_return2(all, Res) :- max_reached_or_timeout_for_node(_),!, Res=ok_not_all_nodes_considered.
2020 build_modelcheck_return2(all, ok).
2021
2022 :- use_module(symbolic_model_checker(bmc),[bmc_symbolic_model_check/1]).
2023 :- use_module(symbolic_model_checker(kinduction), [kinduction_symbolic_model_check/1, tinduction_symbolic_model_check/1]).
2024 :- use_module(symbolic_model_checker(ic3), [ic3_symbolic_model_check/1]).
2025 symbolic_model_check(bmc,Result) :-
2026 bmc_symbolic_model_check(Result).
2027 symbolic_model_check(kinduction,Result) :-
2028 kinduction_symbolic_model_check(Result).
2029 symbolic_model_check(tinduction,Result) :-
2030 tinduction_symbolic_model_check(Result).
2031 symbolic_model_check(ic3,Result) :-
2032 ic3_symbolic_model_check(Result).
2033
2034 /**
2035 compute_efficient_statespace_stats(-NrNodes, -NrTrans, -NrProcessed)
2036
2037 Computes the coverage statistics of the current state space at any given time.
2038 The information of interest includes the total number of nodes and transitions, as well as
2039 a list of statistics about the nodes and operations and a list of the operations that have been uncovered sofar.
2040
2041 #### called by:
2042 * ProB Plugin: ComputeCoverageCommand
2043 * ProB 2.0: ComputeCoverageCommand
2044 */
2045 :- use_module(extrasrc(coverage_statistics),
2046 [compute_the_coverage/5, operation_hit/2,query_node_hit/2, uncovered_operation/1]).
2047
2048 compute_efficient_statespace_stats(NrNodes, NrTrans, NrProcessed) :-
2049 get_state_space_stats(NrNodes, NrTrans, NrProcessed).
2050
2051 %! compute_coverage(-TotalNodeNr,-TotalTransSum,-NodeStat,-OpStat,-Uncovered)
2052 compute_coverage(TotalNodeNr,TotalTransSum,NodeStat,OpStat,Uncovered) :-
2053 compute_the_coverage(_,TotalNodeNr,TotalTransSum,false,false),
2054 findall(S2,(operation_hit(OpS,Nr),string_concatenate(':',Nr,S1),string_concatenate(OpS,S1,S2)),OpStat),
2055 findall(S2,(query_node_hit(Prop,Nr),string_concatenate(':',Nr,S1),string_concatenate(Prop,S1,S2)),NodeStat),
2056 findall(OpName, uncovered_operation(OpName),Uncovered).
2057
2058
2059 get_modelchecking_coverage(TotalNodeNr,TotalTransSum,NodeStat,OpStat,Uncovered) :-
2060 compute_the_coverage(_,TotalNodeNr,TotalTransSum,false,false),
2061 findall(entry(OpS,Nr),operation_hit(OpS,Nr),OpStat),
2062 findall(entry(Prop,Nr),query_node_hit(Prop,Nr),NodeStat),
2063 findall(OpName, uncovered_operation(OpName),Uncovered).
2064
2065 /**
2066 get_statistics(+Option,-Value)
2067
2068 Takes an option for the statistics and returns the corresponding value.
2069
2070 #### called by:
2071 * ProB 2.0: GetStatisticsCommand
2072 */
2073
2074 get_statistics(global_runtime,V) :- statistics(runtime,[V,_]).
2075 get_statistics(global_walltime,V) :- statistics(walltime,[V,_]).
2076 get_statistics(delta_runtime,V) :- statistics(runtime,[_,V]).
2077 get_statistics(delta_walltime,V) :- statistics(walltime,[_,V]).
2078 get_statistics(memory_used,V) :- statistics(memory_used,V).
2079 get_statistics(memory_free,V) :- statistics(memory_free,V).
2080 get_statistics(global_stack_used,V) :- statistics(global_stack_used,V).
2081 get_statistics(local_stack_used,V) :- statistics(local_stack_used,V).
2082 %get_statistics(global_stack_free,V) :- statistics(global_stack_free,V).
2083 %get_statistics(local_stack_free,V) :- statistics(local_stack_free,V).
2084 get_statistics(trail_used,V) :- statistics(trail_used,V).
2085 get_statistics(choice_used,V) :- statistics(choice_used,V).
2086 get_statistics(atoms_used,V) :- statistics(atoms_used,V).
2087 get_statistics(atoms_nbused,V) :- statistics(atoms_nbused,V).
2088 get_statistics(gc_count,V) :- statistics(gc_count,V).
2089 get_statistics(gc_time,V) :- statistics(gc_time,V).
2090
2091 /**
2092 prob2_deadlock_freedom_check(+Predicate,-Result)
2093
2094 Performs deadlock freedom checking with constraint Predicate and calulates the Result.
2095
2096 #### called by:
2097 * ProB 2.0: ConstraintBasedDeadlockCheckCommand
2098 */
2099 prob2_deadlock_freedom_check(Predicate,Result) :-
2100 b_type_expression(Predicate,[variables],pred,TPredicate,Errors),
2101 ( Errors == [] ->
2102 prob2_deadlock_freedom_check1(TPredicate,Result)
2103 ;
2104 Result = errors(Errors)).
2105 prob2_deadlock_freedom_check1(Predicate,Result) :-
2106 % always do a deadlock check with SMT mode enabled
2107 call_with_smt_mode_enabled(prob2_deadlock_freedom_check2(Predicate,Result)).
2108 :- use_module(clpfd_interface,[catch_clpfd_overflow_call1/1]).
2109 :- use_module(b_state_model_check,[cbc_deadlock_freedom_check/3]).
2110 prob2_deadlock_freedom_check2(Predicate,Result) :-
2111 user_interruptable_call_det(clpfd_interface:catch_clpfd_overflow_call1(
2112 b_state_model_check:cbc_deadlock_freedom_check(CheckResult,Predicate,0)),
2113 InterruptResult),!,
2114 ( InterruptResult = interrupted ->
2115 Result = interrupted
2116 ; CheckResult = time_out ->
2117 Result = interrupted
2118 ; CheckResult = deadlock(State) ->
2119 Result = deadlock(Transition,StateId),
2120 add_artificial_transition(root,deadlock_check,State,StateId,Transition)
2121 ; CheckResult = no_deadlock(ImpreciseOps),
2122 b_state_model_check:add_cbc_deadlock_imprecise_warning(ImpreciseOps),
2123 Result = no_deadlock_found).
2124 prob2_deadlock_freedom_check2(_Predicate,no_deadlock_found).
2125
2126
2127
2128
2129
2130
2131 /**
2132 prob2_invariant_check(+Ops,-Result)
2133
2134 Performs invariant cbc checking for either for all operations or a list of operations.
2135
2136 #### called by:
2137 * ProB 2.0: ConstraintBasedInvariantCheckCommand
2138 */
2139 prob2_invariant_check(all,Result) :-
2140 findall(OpName,b_is_op_or_init(OpName),Ops),
2141 % TO DO: also treat $initailise_machine; but state_model_check_invariant does not support it yet
2142 prob2_invariant_check2(Ops,Result).
2143 prob2_invariant_check(ops(Ops),Result) :-
2144 prob2_invariant_check2(Ops,Result).
2145 prob2_invariant_check2(Ops,Result) :-
2146 call_with_smt_mode_enabled(prob2_invariant_check3(Ops,Result,[])).
2147 prob2_invariant_check3([]) --> !.
2148 prob2_invariant_check3([Op|Rest]) -->
2149 prob2_invariant_check_for_single_op(Op),
2150 prob2_invariant_check3(Rest).
2151 prob2_invariant_check_for_single_op(OpName,In,Out) :-
2152 ( clpfd_interface:catch_clpfd_overflow_call1(
2153 b_state_model_check:state_model_check_invariant(OpName,State1,Operation,State2)) ->
2154 In = [counterexample(OpName,Trans1,Trans2)|Out],
2155 atom_concat( invariant_check_ , OpName, RootTrans),
2156 add_artificial_transition(root, RootTrans,State1,StateId1,Trans1),
2157 add_artificial_transition(StateId1,Operation,State2,_StateId2,Trans2)
2158 ;
2159 In = Out).
2160
2161 b_is_op_or_init(OpName) :- b_is_operation_name(OpName).
2162 b_is_op_or_init(OpName) :- b_is_initialisation_name(OpName).
2163
2164 :- use_module(b_state_model_check,[cbc_find_redundant_invariants/2]).
2165 prob2_redundant_invariants(Redundant, Timeout) :-
2166 cbc_find_redundant_invariants(Redundant, Timeout).
2167
2168 /**
2169 add_artificial_transition(+SrcId,+Operation,+DstState,+DstId,-TransitionTuple)
2170
2171 creates a helper transition that is artificially added to the state space (e.g. during CBC deadlock checking)
2172 This transition is added to the state space.
2173 A triple TransitionTuple in the form op(TransId,OpName,SrcId,DstId) for this transition is generated.
2174 */
2175 % TODO: return list of transitions and re-use concrete_constants if possible, see seperate_state_into_const_and_vars
2176 add_artificial_transition(SrcId,Operation,DstState,DstId,TransitionTuple) :-
2177 tcltk_interface:tcltk_add_new_transition_transid(SrcId,Operation,DstId,DstState,[],TransId),
2178 extract_op_name(Operation,OpName),
2179 TransitionTuple = op(TransId,OpName,SrcId,DstId).
2180
2181 /**
2182 computes the enabling relation information for the provided operations of interest
2183 get_enable_matrix(-PairsOfOperations,+EnableResult)
2184 PairsOfOperations: list of pair(Op1,Op2) of operations pairs for which the enable relation is to be computed
2185 EnableResult: list of terms enable_edges(Op1,Op2,enable_edges(E,KE,D,KD)) of same length
2186 */
2187 get_enable_matrix(PairsOfOperations,EnableResult) :-
2188 maplist(compute_enable_matrix_entry(100),PairsOfOperations,EnableResult).
2189
2190 :- use_module(cbcsrc(enabling_analysis),[compute_cbc_enable_rel/4]).
2191 compute_enable_matrix_entry(ExtraTimeout,pair(OpName1,OpName2),
2192 enable_rel(OpName1,OpName2,
2193 enable_edges(Enable,KeepEnabled,Disable,KeepDisabled))) :-
2194 compute_cbc_enable_rel(OpName1,OpName2,ExtraTimeout,[Enable,KeepEnabled,Disable,KeepDisabled]).
2195
2196 /**
2197 prob2_do_ltl_modelcheck(+Formula,+Options,-Result)
2198
2199 Performs an LTL model checking step.
2200
2201 Supported options:
2202 * max_new_states(Max) - maximum number of new states that will be explored, or -1 (the default) for no limit
2203 * mode(Mode) - init (the default) to check starting from every initialized state, or specific_node(StateID) to check starting from one specific state
2204
2205 #### called by:
2206 * ProB 2.0: LtlCheckingCommand
2207 */
2208 prob2_do_ltl_modelcheck(Formula, Options, Result) :-
2209 (selectchk(max_new_states(Max), Options, Options1) -> true ; Max = -1, Options1 = Options),
2210 (selectchk(mode(Mode), Options1, Options2) -> true ; Mode = init, Options2 = Options1),
2211 Options2 == [],
2212
2213 typecheck_temporal_formula(Formula,TypeCheckedFormula,Status),
2214 (Status=ok ->
2215 ltl_model_check_with_ce(TypeCheckedFormula,Max,Mode,Result1),
2216 prob2_ltl_adapt_operations(Result1,Result)
2217 ;
2218 get_all_errors_with_span_info_and_reset(Errors),
2219 Result = type_error(Errors)
2220 ).
2221
2222 % Old command without option list - can be removed after release of ProB Java API 4.14.0.
2223 prob2_do_ltl_modelcheck(Formula,Max,Result,Errors) :-
2224 prob2_do_ltl_modelcheck(Formula, [max_new_states(Max)], Res),
2225 (Res = type_error(Errors) ->
2226 Result = typeerror
2227 ;
2228 Result = Res,
2229 Errors = []
2230 ).
2231
2232 prob2_ltl_adapt_operations(counterexample(CE1,LoopEntry,PathToCE1), Res) :- !,
2233 Res = counterexample(CE,LoopEntry,PathToCE),
2234 create_simple_op_terms_for_path(PathToCE1,root,PathToCE),
2235 prob2_ltl_adapt_ce(CE1,CE).
2236 prob2_ltl_adapt_operations(Result,Result).
2237
2238 prob2_ltl_adapt_ce([],[]).
2239 prob2_ltl_adapt_ce([atom(StateId,_,OpTuple)|Irest],[Transition|Orest]) :-
2240 prob2_ltl_adapt_ce2(OpTuple,StateId,Transition),
2241 prob2_ltl_adapt_ce(Irest,Orest).
2242 prob2_ltl_adapt_ce2(none,_StateId,none).
2243 prob2_ltl_adapt_ce2((TransId,Action,DestId),StateId,op(TransId,Name,StateId,DestId)) :-
2244 extract_op_name(Action,Name).
2245
2246
2247 create_simple_op_terms_for_path([],_,[]).
2248 create_simple_op_terms_for_path([(Id,Op,DstId)|T],StateID,[op(Id,Name,StateID,DstId)|FT]) :-
2249 extract_op_name(Op,Name),
2250 create_simple_op_terms_for_path(T,DstId,FT). % difference to create_simple_op_terms: we move to DstId
2251
2252
2253 /**
2254 prob2_do_ctl_modelcheck(+Formula, +Options, -Result, -CE)
2255
2256 Performs an CTL model checking step.
2257
2258 Supported options:
2259 * max_new_states(Max) - maximum number of new states that will be explored, or -1 (the default) for no limit
2260 * mode(Mode) - init (the default) to check starting from every initialized state, or specific_node(StateID) to check starting from one specific state
2261
2262 #### called by:
2263 * ProB 2.0: CtlCheckingCommand
2264 */
2265 prob2_do_ctl_modelcheck(Formula, Options, Result, CE) :-
2266 (selectchk(max_new_states(Max), Options, Options1) -> true ; Max = -1, Options1 = Options),
2267 (selectchk(mode(Mode), Options1, Options2) -> true ; Mode = init, Options2 = Options1),
2268 Options2 == [],
2269
2270 typecheck_temporal_formula(Formula, TypeCheckedFormula, Status),
2271 (Status = ok ->
2272 ctl_model_check_with_ast(main, TypeCheckedFormula, Max, Mode, Result, CE)
2273 ;
2274 get_all_errors_with_span_info_and_reset(Errors),
2275 Result = type_error(Errors),
2276 CE = [] % no counter example
2277 ).
2278
2279 % Old command without option list - can be removed after release of ProB Java API 4.14.0.
2280 prob2_do_ctl_modelcheck(Formula, MaxNodes, Mode, Res, CE, Errors) :-
2281 prob2_do_ctl_modelcheck(Formula, [max_new_states(MaxNodes), mode(Mode)], Res, CE),
2282 (Res = type_error(Errors) ->
2283 true %Result = typeerror
2284 ;
2285 %Result = Res,
2286 Errors = []
2287 ).
2288
2289
2290 /* ------------------------- */
2291 /* Find Traces */
2292 /* ------------------------- */
2293
2294 /**
2295 find_trace_to_node(+StateId,-Trace)
2296
2297 Finds a trace from the root state to the specified state in the current state space.
2298
2299 #### Parameters:
2300 * StateId
2301 * Trace - List of op tuples op(OpId,SrcId,DestId) corresponding to the trace calculated by ProB or atom no_trace_found if the call was unsuccessful
2302
2303 #### called by:
2304 * ProB 2.0: GetShortestTraceCommand
2305 */
2306 find_trace_to_node(StateId, Trace) :-
2307 find_trace_from_node_to_node(root, StateId, Trace).
2308
2309 /**
2310 find_trace_from_node_to_node(+FromId,+ToId,-Trace)
2311
2312 Finds a trace from one state to a goal state in the current state space.
2313
2314 #### Parameters:
2315 * FromId - Id of source node
2316 * ToId - Id of destination node
2317 * Trace - List of op tuples op(OpId,SrcId,DestId) corresponding to the trace calculated by ProB or atom no_trace_found if the call was unsuccessful
2318
2319 #### called by:
2320 * ProB 2.0: GetShortestTraceCommand
2321 */
2322 find_trace_from_node_to_node(FromId, ToId, Trace) :-
2323 (tcltk_interface:find_shortest_trace_to_node(FromId, ToId, OpIDs, _TraceIDs) ->
2324 trace_to_op_terms(OpIDs,FromId,Trace);
2325 Trace = no_trace_found
2326 ).
2327
2328 /**
2329 trace_to_op_terms(+ListOpIds,+CurID,-ListOpTerms)
2330
2331 Translates a list of transition ids to a list of terms op(TransId,OpName,SrcId,DestId).
2332 The list must represent a trace,
2333 i. e. the first transition must lead to the source state of the second one,
2334 the second transition to the source state of the third, etc.
2335 */
2336 trace_to_op_terms([],_,[]).
2337 trace_to_op_terms([OpID|T], SrcID, [op(OpID,Name,SrcID,Dest)|OpT]) :-
2338 transition(SrcID,Action,OpID,Dest),
2339 !,
2340 extract_op_name(Action,Name),
2341 trace_to_op_terms(T,Dest,OpT).
2342 trace_to_op_terms([skip|T], SrcID, [op(skip,skip,SrcID,SrcID)|OpT]) :-
2343 trace_to_op_terms(T,SrcID,OpT).
2344
2345 /**
2346 Takes a given predicate and finds a state in the state space that satisfies the predicate.
2347 A helper transition is then added to go to the goal state.
2348
2349 #### called by:
2350 * ProB 2.0: FindValidStateCommand
2351 */
2352 :- use_module(b_state_model_check,[b_set_up_valid_state_with_pred/4]).
2353 find_state_for_predicate(Predicate,UseInvariant,Result) :-
2354 (predicate_typecheck_for_eval(Predicate,TPredicate) ->
2355 find_state_for_predicate1(TPredicate,UseInvariant,Result)
2356 ;
2357 get_all_errors_with_span_info_and_reset(Errors),
2358 Result = errors(Errors)
2359 ).
2360 find_state_for_predicate1(Predicate,UseInvariant,Result) :-
2361 user_interruptable_call_det(clpfd_interface:catch_clpfd_overflow_call1(
2362 b_state_model_check:b_set_up_valid_state_with_pred(State,Predicate,
2363 UseInvariant,none)), % TODO: pass UseConstantsFromStateID
2364 InterruptResult),!,
2365 ( InterruptResult = interrupted ->
2366 Result = interrupted
2367 ; State = time_out ->
2368 Result = interrupted
2369 ;
2370 Result = state_found(Transition,StateId),
2371 % the following is incomplete if State contains constants; TODO: seperate constants
2372 % see tcltk_add_cbc_state which adds an intermediate constants state if necessary
2373 % TODO: we also need to change the state_found/2 result to return a list of transitions
2374 add_artificial_transition(root,find_valid_state,State,StateId,Transition)).
2375 find_state_for_predicate1(_Predicate,_,no_valid_state_found).
2376
2377 /**
2378 cbc_disprove(+Goal,+AllHypotheses,+SelectedHypotheses,+TimeoutFactor,-OutResult)
2379
2380 #### called by:
2381 * ProB Plugin (de.prob.eventb.disprover.core): DisproverCommand
2382 ues as Options: [use_smt_mode/true,use_clpfd_solver/true,use_chr_solver/CHR]; CHR enabled if available
2383 */
2384 cbc_disprove(Goal,AllHypotheses,SelectedHypotheses,TimeoutFactor,OutResult) :-
2385 disprove(Goal,AllHypotheses,SelectedHypotheses,TimeoutFactor,OutResult),
2386 % remove the warning regarding double check, in rodin it is shown in the proof tree anyway
2387 (get_error(warning(disprover_inconsistent_hypotheses),_) ; true).
2388
2389 /**
2390 cbc_disprove_counter_example_dot(+Goal,+Hypotheses,+Bindings,+Timeout,+DotFile)
2391
2392 Writes ProB's formula tree of Hypotheses => Goal, evaluated in a counter-example found by
2393 cbc_disprove/6, to a dot file. Bindings are the binding(Id,Value,PP) terms of its result
2394 (solution(Bindings) or solution_on_selected_hypotheses(Bindings)); the values of the other
2395 identifiers are found by solving the sequent again (Timeout in ms). Expects the disprover's
2396 context to be loaded, as for cbc_disprove/6.
2397
2398 #### called by:
2399 * ProB Plugin (de.prob.eventb.disprover.core): DisproverCommand, for the "Visualise" link of the counter-example notice
2400 */
2401 cbc_disprove_counter_example_dot(Goal,Hypotheses,Bindings,Timeout,DotFile) :-
2402 disprover_counter_example_dot(Goal,Hypotheses,Bindings,Timeout,DotFile).
2403
2404 /**
2405 cbc_disprover_statistics(-Total,-LastCall)
2406
2407 Statistics about the disprover's individual provers (e.g. wd_prover, setlog_prover and the
2408 constraint solver) and their results: lists of
2409 prover_stats(Prover,Result,NrCalls,timer(Runtime,TotalRuntime,Walltime)), times in ms.
2410 Total covers all calls since probcli started or since cbc_reset_disprover_statistics;
2411 LastCall only the last call of cbc_disprove/5 or cbc_disprove/6.
2412
2413 #### called by:
2414 * ProB Plugin (de.prob.eventb.disprover.core): DisproverCommand (after each cbc_disprove/6) and DisproverStatistics
2415 */
2416 cbc_disprover_statistics(Total,LastCall) :-
2417 get_prover_result_stats(Total,LastCall).
2418
2419 /**
2420 get_theory_mapping_targets(-Targets,-Defaults)
2421
2422 What can be written in a theory mapping file (.ptm) for a Rodin theory: Targets is a list of
2423 target(Tag,Arity,Kind,Category,Construct), one for each Tag that can be written in a line
2424 operator "Op" internal {Tag}, where Arity is the number of arguments Op must have (0, 1 or 2),
2425 Kind is expression or predicate, Category is b_operator, external_function, external_predicate,
2426 constant, aggregation or inductive_natural, and Construct is the construct ProB uses (for information).
2427 Defaults is a list of default(Op,Arity,Tag,ArgType): the tag ProB uses for an axiomatic operator Op
2428 with Arity arguments without a .ptm entry; ArgType is any, integer or real (the type the arguments
2429 need for this default). See bmachine_eventb:get_theory_mapping_targets/2.
2430
2431 #### called by:
2432 * ProB Plugin (de.prob.core): GetTheoryMappingTargetsCommand, to create .ptm files with suggestions
2433 */
2434 get_theory_mapping_targets(Targets,Defaults) :-
2435 bmachine_eventb:get_theory_mapping_targets(Targets,Defaults).
2436
2437 /**
2438 cbc_reset_disprover_statistics
2439
2440 Resets the statistics of cbc_disprover_statistics/2.
2441
2442 #### called by:
2443 * ProB Plugin (de.prob.eventb.disprover.core): DisproverStatistics
2444 */
2445 cbc_reset_disprover_statistics :-
2446 reset_prover_result_stats.
2447
2448 /**
2449 cbc_disprove(+Goal,+AllHypotheses,+SelectedHypotheses,+TimeoutFactor,-OutResult)
2450
2451 the same with explicit Options:
2452 */
2453 cbc_disprove(Goal,AllHypotheses,SelectedHypotheses,TimeoutFactor,Options,OutResult) :-
2454 % we do not have to add: [use_smt_mode/true,use_clpfd_solver/true,use_chr_solver/true],
2455 % for Rodin these prefs are set in DisproverCommand.java
2456 disprove_with_opts(Goal,AllHypotheses,SelectedHypotheses,TimeoutFactor,Options,OutResult),
2457 % remove the warning regarding double check, in rodin it is shown in the proof tree anyway
2458 (get_error(warning(disprover_inconsistent_hypotheses),_) ; true).
2459
2460 :- assert_must_succeed((cbc_solve_with_opts('PROB',[truncate(10)],
2461 equal(none,identifier(none,x),integer(none,10)),Identifiers,Result),
2462 Identifiers == [x],
2463 check_eqeq(Result,solution([binding(x,int(10),'10')])))).
2464
2465 /**
2466 cbc_solve_with_opts(+Solver,+Options,+Predicate,-Identifiers,-Result)
2467 */
2468 cbc_solve_with_opts(Solver,Options,Predicate,Identifiers,Result) :-
2469 maplist(prob2_interface:check_cbc_solve_opts,Options),
2470 cbc_solve_type(Solver,Options,Predicate,TPredicate),
2471 find_identifier_uses(TPredicate,[],Identifiers),
2472 (select(timeout_factor(TimeoutFactor),Options,Opts2) -> true ; TimeoutFactor=1,Opts2=Options),
2473 cbc_solve_typed(Solver,TPredicate,_,TimeoutFactor,Opts2,Result).
2474
2475 cbc_timed_solve_with_opts(Solver,Options,Predicate,Identifiers,Result,Milliseconds) :-
2476 maplist(prob2_interface:check_cbc_solve_opts,Options),
2477 cbc_solve_type(Solver,Options,Predicate,TPredicate),
2478 find_identifier_uses(TPredicate,[],Identifiers),
2479 (select(timeout_factor(TimeoutFactor),Options,Opts2) -> true ; TimeoutFactor=1,Opts2=Options),
2480 cbc_solve_timed(Solver,TPredicate,_,TimeoutFactor,Opts2,Result,Milliseconds).
2481
2482
2483 check_cbc_solve_opts(full_machine_state) :- !.
2484 check_cbc_solve_opts(solve_in_visited_state(ID)) :- !,atomic(ID).
2485 check_cbc_solve_opts(timeout_factor(Nr)) :- !,number(Nr).
2486 check_cbc_solve_opts(truncate(Nr)) :- !,number(Nr). % truncate pretty printing
2487 check_cbc_solve_opts(truncate) :- !. % truncate pretty printing
2488 check_cbc_solve_opts(force_evaluation) :- !. % force evaluation of symbolic results
2489 check_cbc_solve_opts(provide_stored_let_values) :- !.
2490 check_cbc_solve_opts(all_external_libraries) :- !.
2491 check_cbc_solve_opts(IO) :- add_internal_error('Illegal cbc_solve_with_opts option:',IO).
2492
2493
2494 :- use_module(cdclt_solver('cdclt_solver'), [cdclt_solve_predicate/3,cdclt_solve_predicate_in_state/4]).
2495 :- use_module(probsrc(specfile),[get_state_for_b_formula/3]).
2496 :- use_module(solver_interface, [solver_pp_bvalue/4]).
2497
2498 timed_solve_predicate(Predicate,State,TimeoutFactor,Options,Result,Time) :-
2499 statistics(walltime, [Start, _]),
2500 solve_predicate(Predicate,State,TimeoutFactor,Options,Result),
2501 statistics(walltime, [Stop,_]),
2502 Time is Stop - Start.
2503
2504 cbc_solve_timed('PROB',Predicate,State,TimeoutFactor,Options,Result,Time) :-
2505 timed_solve_predicate(Predicate,State,TimeoutFactor,['SMT','CLPFD'|Options],Result,Time).
2506 cbc_solve_timed('KODKOD',Predicate,State,TimeoutFactor,Options,Result,Time) :-
2507 timed_solve_predicate(Predicate,State,TimeoutFactor,['KODKOD','SMT','CLPFD'|Options],Result,Time).
2508 cbc_solve_timed('SMT_SUPPORTED_INTERPRETER',Predicate,State,TimeoutFactor,Options,Result,Time) :-
2509 timed_solve_predicate(Predicate,State,TimeoutFactor,
2510 ['SMT_SUPPORTED_INTERPRETER','SMT','CLPFD'|Options],Result,Time).
2511 cbc_solve_timed(SOLVER,Predicate,_StateID,_,Options,Result,Time) :-
2512 %TODO: why do we ignore _StateID and TimeoutFactor here?
2513 statistics(walltime, [Start, _]),
2514 (member(solve_in_visited_state(ID),Options)
2515 -> solve_in_state_aux(SOLVER,ID,Predicate,Result)
2516 ; solve_free_aux(SOLVER,Predicate,Result)
2517 ),
2518 statistics(walltime, [Stop,_]),
2519 Time is Stop - Start.
2520
2521 :- use_module(extension('satsolver/b2sat'), [solve_predicate_with_satsolver_free/4,
2522 solve_predicate_with_satsolver_in_state/4]).
2523 solve_in_state_aux('CDCLT',ID,Predicate,Result) :- !,
2524 get_state_for_b_formula(ID, Predicate, Store),
2525 cdclt_solve_predicate_in_state(Predicate, Store, _SolvedPredWdGuaranteed, CdcltResult),
2526 translate_cbc_cdclt_result(CdcltResult, Result).
2527 solve_in_state_aux('SAT',ID,Predicate,Result) :- !,
2528 solve_in_state_sat_aux(ID,Predicate,Result,[]).
2529 solve_in_state_aux('SATZ3',ID,Predicate,Result) :- !,
2530 solve_in_state_sat_aux(ID,Predicate,Result,[use_satsolver(z3)]).
2531 solve_in_state_aux(SOLVER,ID,Predicate,Result) :-
2532 recognised_smt_solver(SOLVER,InternalName),!,
2533 smt_solve_predicate_in_state(ID,InternalName,Predicate,_State,Result).
2534
2535 solve_in_state_sat_aux(ID,Predicate,Result,Opts) :- !,
2536 (ID=root -> solve_predicate_with_satsolver_free(Predicate,_,SatResult,Opts)
2537 ; get_state_for_b_formula(ID, Predicate, Store),
2538 solve_predicate_with_satsolver_in_state(Predicate,Store,SatResult,Opts)
2539 ),
2540 translate_cbc_cdclt_result(SatResult,Result).
2541
2542 solve_free_aux('CDCLT',Predicate,Result) :- !,
2543 cdclt_solve_predicate(Predicate, _SolvedPredWdGuaranteed, CdcltResult),
2544 translate_cbc_cdclt_result(CdcltResult, Result).
2545 solve_free_aux('SAT',Predicate,Result) :-
2546 solve_predicate_with_satsolver_free(Predicate,_,SatResult,[]),
2547 translate_cbc_cdclt_result(SatResult,Result).
2548 solve_free_aux('SATZ3',Predicate,Result) :-
2549 solve_predicate_with_satsolver_free(Predicate,_,SatResult,[use_satsolver(z3)]),
2550 translate_cbc_cdclt_result(SatResult,Result).
2551 solve_free_aux(SOLVER,Predicate,Result) :-
2552 recognised_smt_solver(SOLVER,InternalName),!,
2553 smt_solve_predicate(InternalName,Predicate,_State,Result).
2554
2555 cbc_solve_typed(Solver,Predicate,State,TimeoutFactor,Options,Result) :-
2556 cbc_solve_timed(Solver,Predicate,State,TimeoutFactor,Options,Result,_).
2557
2558 % As CDCL(T) does not pretty print its results, we need this translation,
2559 % as CbcSolveCommand expects the pretty print.
2560 % In case no solution was found, the original CDCL(T) result can be forwarded.
2561 translate_cbc_cdclt_result(solution(NonPPBindings), solution(Bindings)) :-
2562 !,
2563 findall(binding(Id,EValue,PPValue),
2564 (member(bind(Id,Value),NonPPBindings),
2565 (solver_pp_bvalue(Value,[],EValue,PPValue) -> true
2566 ; EValue=Value, PPValue='**pretty-print failed**')),
2567 Bindings).
2568 translate_cbc_cdclt_result(Result, Result).
2569
2570
2571
2572 recognised_smt_solver('Z3',z3).
2573 recognised_smt_solver('Z3CNS',z3cns).
2574 recognised_smt_solver('Z3AXM',z3axm).
2575 recognised_smt_solver('CVC4',cvc4).
2576
2577 :- use_module(preferences,[temporary_set_preference/3,reset_temporary_preference/2]).
2578 cbc_solve_type('KODKOD',Options,Pred,TPred) :- !,
2579 temporary_set_preference(use_solver_on_load,kodkod,C),
2580 call_cleanup(cbc_solve_type2(Options,Pred,TPred),
2581 reset_temporary_preference(use_solver_on_load,C)).
2582 cbc_solve_type(_,Options,Pred,TPred) :- cbc_solve_type2(Options,Pred,TPred).
2583 cbc_solve_type2(Options,Pred,TPred) :-
2584 !, get_eval_scope_with_opts(Options,Scope),
2585 b_type_open_predicate(no_quantifier,Pred,Scope,TPred,Errors),
2586 (Errors=[] -> true ; add_error_and_fail(cbc_solve_type, 'Type-Errors: ', Errors)).
2587
2588
2589 :- use_module(code2vec(code2vec),[leaf_paths/2]).
2590 ast_leaf_walks(B, Walks) :-
2591 cbc_solve_type2([], B, TypedB),
2592 leaf_paths(TypedB, Walks).
2593
2594 /**
2595 Takes a predicates and generates a pretty printed string
2596 */
2597 :- assert_must_succeed((pretty_print_predicate(equal(none,identifier(none,x),integer(none,1)),[],Result),
2598 check_eqeq(Result,'x = 1'))).
2599 :- assert_must_succeed((pretty_print_predicate(not_equal(none,identifier(none,x),integer(none,1)),[latex],Result),
2600 check_eqeq(Result,'\\mathit{x} \\neq 1'))).
2601 :- assert_must_succeed((pretty_print_predicate(not_equal(pos(2,-1,1,1,1,7),integer(pos(3,-1,1,1,1,2),1),
2602 integer(pos(4,-1,1,6,1,7),2)),[latex,nopt],PPString),
2603 check_eqeq(PPString,'1 \\neq 2' ))).
2604
2605 pretty_print_predicate(Pred,Options,PPString) :-
2606 select(nopt,Options,Opts2),
2607 !,
2608 temporary_set_preference(optimize_ast,false,CHNG1),
2609 call_cleanup(pretty_print_predicate(Pred,Opts2,PPString),
2610 reset_temporary_preference(optimize_ast,CHNG1)).
2611 pretty_print_predicate(Pred,Options,PPString) :-
2612 get_eval_scope_with_opts(Options,Scope),
2613 b_type_open_predicate(no_quantifier,Pred,Scope,TPred,Errors),
2614 (Errors=[] -> true ; add_error_and_fail(pretty_print_predicate, 'Type-Errors: ', Errors)),
2615 options_to_translation_mode(Options, Mode),
2616 with_translation_mode(Mode, translate_bexpression(TPred,PPString)).
2617
2618 options_to_translation_mode(Options, Mode) :- memberchk(latex, Options), !, Mode = latex.
2619 options_to_translation_mode(Options, Mode) :- memberchk(unicode, Options), !, Mode = unicode.
2620 options_to_translation_mode(_Options, ascii).
2621
2622 % Constraint-Based Test-case generation
2623 % TO DO: return values
2624 :- use_module(cbcsrc(sap),[cbc_gen_test_cases/5]).
2625 cbc_generate_test_cases(TargetPred,MaxDepth,OutputFile) :-
2626 % I am not sure whether we should call b_parse_machine_predicate(TargetPred,...) or not
2627 Events = all,
2628 cbc_gen_test_cases(Events,TargetPred,MaxDepth,OutputFile,_Uncovered).
2629
2630
2631
2632 :- use_module(cbcsrc(cbc_path_solver),[create_testcase_path/5]).
2633 /**
2634 prob2_find_test_path(+Events,+EndPredicate,+TimeoutMs,-ResultOpTerms)
2635
2636 example call | ?- prob2_interface:prob2_find_test_path([enter1],truth(unknown),200,R).
2637
2638 Result is either errors(Errors), timeout, interrupt, infeasible_path, or list of Operation IDs
2639 */
2640 prob2_find_test_path(Events,EndPredicate,TimeoutMs,ResultOpTerms) :-
2641 (predicate_typecheck_for_eval(EndPredicate,TPredicate) ->
2642 prob2_find_test_path_aux(Events,TPredicate,TimeoutMs,ResultOpTerms)
2643 ;
2644 get_all_errors_with_span_info_and_reset(Errors),
2645 ResultOpTerms = errors(Errors)
2646 ).
2647
2648 prob2_find_test_path_aux(Events,TPredicate,TimeoutMs,ResOperationIds) :-
2649 ( create_testcase_path(init,Events,TPredicate,TimeoutMs,Trace)
2650 -> (is_list(Trace) -> maplist(extract_opid,Trace,ResOperationIds)
2651 % Trace can be "timeout" or "interrupt", too
2652 ; ResOperationIds=Trace)
2653 ; ResOperationIds = infeasible_path).
2654
2655 extract_opid((TransId,OpTerm,StateId,DestId),op(TransId,Name,StateId,DestId)) :- extract_op_name(OpTerm,Name).
2656
2657 /* ------------------------- */
2658 /* Check CSP Assertion */
2659 /* ------------------------- */
2660
2661 /**
2662 check_csp_assertions(+Assertions,-Results,-ResultTraces)
2663
2664 Takes a list of assertions and produce a list of results and result traces.
2665
2666 TODO: We should modify the result traces so that they are useful for ProB 2.0. (or at least document what the result traces mean)
2667
2668 #### called by:
2669 * ProB 2.0: CSPAssertionsCommand
2670 */
2671 check_csp_assertions(Assertions,Results,ResultTraces) :-
2672 maplist(check_csp_assertion,Assertions,Results,ResultTraces).
2673
2674 check_csp_assertion(AssClause,Res,ResTrace1) :-
2675 read_from_codes(AssClause,Assertion),
2676 tcltk_interface:checkAssertion(Assertion,_PP,_Negated,Res,ResTrace),
2677 (ResTrace = no_counter_example -> ResTrace1 = []; ResTrace1=ResTrace).
2678
2679 /* ------------------------- */
2680 /* Preferences Interface */
2681 /* ------------------------- */
2682
2683 /**
2684 list_current_eclipse_preferences(-L)
2685
2686 Returns a list of all the preferences with their current values
2687
2688 #### called by:
2689 * ProB 2.0: GetCurrentPreferencesCommand
2690 */
2691 list_current_eclipse_preferences(L) :-
2692 findall(preference(A,B),find_eclipse_preference(A,B),L).
2693
2694 find_eclipse_preference(A,B) :-
2695 list_all_eclipse_preferences(X),
2696 member(preference(A,_,_,_,_),X),
2697 get_eclipse_preference(A,B).
2698
2699 /**
2700 Returns the current value of a specified preference.
2701
2702 #### called by:
2703 * ProB 2.0: GetPreferenceCommand
2704 */
2705 get_eclipse_preference(PrefS,PrefVal) :-
2706 if(eclipse_preference(PrefS,PS),
2707 get_preference(PS,PrefVal),
2708 add_unknown_preference_error_and_fail(get_eclipse_preference,PrefS)).
2709
2710 /**
2711 list_eclipse_preferences(-L)
2712
2713 Returns a list of all normal eclipse preferences as well as their information
2714 (i.e. type, description, category, and default value)
2715
2716 #### called by:
2717 * ProB Plugin: GetPreferencesCommand
2718 * ProB 2.0: GetDefaultPreferencesCommand
2719 */
2720 list_eclipse_preferences(L) :-
2721 findall(preference(A,B,C,D,E),
2722 (get_eclipse_preference_infos(A,B,C,D,E),
2723 \+ advanced_eclipse_preference(A,_)), L).
2724
2725 /**
2726 list_all_eclipse_preferences(-L)
2727
2728 also includes advanced eclipse preferences
2729 */
2730 list_all_eclipse_preferences(L) :-
2731 findall(preference(A,B,C,D,E),get_eclipse_preference_infos(A,B,C,D,E),L).
2732
2733 get_eclipse_preference_infos(PrefString,Type,Description,Category,DefaultValue) :-
2734 eclipse_preference(PrefString,PS),
2735 %\+ advanced_eclipse_preference(PrefString,PS), % we now want to show all preferences in ProB 2
2736 preference_val_type_list(PS,Type),
2737 preference_description(PS,Description),
2738 preference_category(PS,Category),
2739 preference_default_value(PS,DefaultValue).
2740
2741 /**
2742 set_eclipse_preference(+PrefS,+PrefVal)
2743
2744 Sets a preference
2745
2746 #### called by:
2747 * ProB Plugin: SetPreferenceCommand
2748 * ProB 2.0: SetPreferenceCommand
2749 */
2750 :- use_module(tools_strings, [convert_cli_arg/2]).
2751 set_eclipse_preference(PrefS,PrefVal) :-
2752 convert_cli_arg(PrefVal,Value),
2753 convert_pref_value(Value,CValue),
2754 ? (eclipse_preference(PrefS,P)
2755 -> safe_set_pref(P,CValue,Value)
2756 ; deprecated_eclipse_preference(PrefS,_,NewP,Mapping),
2757 ? member(CValue/NewVal,Mapping)
2758 -> add_message(set_eclipse_preference,'Deprecated preference: ',PrefS),
2759 safe_set_pref(NewP,NewVal,Value)
2760 ; obsolete_eclipse_preference(PrefS)
2761 -> add_warning(set_eclipse_preference,'Obsolete preference: ',PrefS) % just warn and continue
2762 ; add_unknown_preference_error_and_fail(set_eclipse_preference,PrefS)
2763 ).
2764
2765 safe_set_pref(P,CValue,Value) :-
2766 (set_preference(P,CValue)
2767 -> true
2768 ; ajoin(['Could not set preference ',P,' to: '],Msg),
2769 add_error(set_eclipse_preference,Msg,Value)
2770 ).
2771
2772 convert_pref_value('TRUE',V) :- !, V=true.
2773 convert_pref_value('FALSE',V) :- !, V=false.
2774 convert_pref_value(X,X).
2775
2776 :- use_module(tools_matching,[get_possible_preferences_matches_msg/2]).
2777 add_unknown_preference_error_and_fail(Source,PrefS) :-
2778 obsolete_eclipse_preference(PrefS),!,
2779 add_error_and_fail(Source,'Obsolete preference: ',PrefS).
2780 add_unknown_preference_error_and_fail(Source,PrefS) :-
2781 get_possible_preferences_matches_msg(PrefS,FuzzyMsg),!,
2782 ajoin(['Unknown preference: ',PrefS,'. Did you mean: '],Msg),
2783 add_error_and_fail(Source,Msg,FuzzyMsg).
2784 add_unknown_preference_error_and_fail(Source,PrefS) :-
2785 add_error_and_fail(Source,'Unknown preference: ',PrefS).
2786
2787 /* ------------------------- */
2788 /* Apply Graph reduction */
2789 /* ------------------------- */
2790
2791 /**
2792 get_signature_merge_state_space(+IgnoredEvents,-Space)
2793
2794 Takes a list of ignored events, and applies the signature merge algorithm
2795 from module `state_space_reduction` to the current state space.
2796
2797 #### called by:
2798 * ProB 2.0: ApplySignatureMergeCommand
2799 */
2800 get_signature_merge_state_space(IgnoredEvents,Space) :-
2801 reset_ignored_events,
2802 set_ignored_events(IgnoredEvents),
2803 compute_signature_merge,
2804 findall(node(NodeId,Count,Color,Labels),extract_node_info(NodeId,Count,Color,simple_list,Labels),Nodes),
2805 findall(trans(TransId,Src,Dest,Label,Style,Color),extract_trans_info(true,TransId,Src,Dest,Label,Style,Color),Trans),
2806 Space = [Nodes,Trans].
2807
2808 /**
2809 get_transition_diagram(+ParsedExpr,-Space)
2810
2811 Takes a list of ignored events, and calculates a transition diagram
2812 using module `state_space_reduction` for the current state space.
2813
2814 #### called by:
2815 * ProB 2.0: CalculateTransitionDiagramCommand
2816 */
2817 get_transition_diagram(ParsedExpr,Space) :-
2818 expression_typecheck_for_eval(ParsedExpr,TypedExpr),
2819 compute_transition_diagram(TypedExpr),
2820 findall(node(NodeId,Count,Color,Labels),extract_node_info(NodeId,Count,Color,gen_label,Labels),Nodes),
2821 findall(trans(TransId,Src,Dest,Label,Style,Color),extract_trans_info(false,TransId,Src,Dest,Label,Style,Color),Trans),
2822 Space = [Nodes,Trans].
2823
2824 /**
2825 prob2_get_equivalence_class_states(+ClassId,+Limit,-StateIds,-Total)
2826
2827 Returns the ids of the states (at most Limit, in the order in which they were added
2828 to the state space) in the equivalence class ClassId of the last state space reduction,
2829 i.e., of the last Signature Merge or State Space Expression Projection graph,
2830 whose nodes are named by their class ids. Total is the number of states in the class.
2831
2832 #### called by:
2833 * ProB Rodin Plugin: GetEquivalenceClassStatesCommand (double-click in the ProB Graph view)
2834 */
2835 :- use_module(tools_lists,[take_at_most/3]).
2836 prob2_get_equivalence_class_states(ClassId,Limit,StateIds,Total) :-
2837 findall(ID,state_space_reduction:equivalence_class(ID,ClassId),All),
2838 length(All,Total),
2839 take_at_most(Limit,All,StateIds).
2840
2841 write_dotty_transition_diagram(Expression,Filename) :-
2842 write_dotty_for_expr(transition_diagram,Expression,Filename).
2843
2844 write_dotty_signature_merge(IgnoredEvents,Filename) :-
2845 write_signature_merge_to_dotfile(IgnoredEvents,Filename).
2846
2847 write_dotty_state_space(Filename) :-
2848 write_dotty(state_space,Filename).
2849
2850 :- use_module(extrasrc(meta_interface),[is_dot_command/1, call_dot_command/3]).
2851 % find out which commands only require a filename:
2852 is_dotty_command(Command) :- is_dot_command(Command).
2853 % call commands which generate a dot file (without requiring further arguments, such as an expression)
2854 write_dotty(Command,Filename) :- OptionalArgs=[],
2855 call_dot_command(Command,Filename,OptionalArgs).
2856
2857
2858 :- use_module(extrasrc(meta_interface),[is_dot_command_for_expr/1, call_dot_command_for_expr/4]).
2859 % find out which commands only require an expression and a filename:
2860 is_dotty_command_for_expr(Command) :- is_dot_command_for_expr(Command).
2861 % call commands which generate a dot file from an expression:
2862 write_dotty_for_expr(Command,Expr,Filename) :- OptionalArgs=[],
2863 call_dot_command_for_expr(Command,Expr,Filename,OptionalArgs).
2864
2865
2866 :- use_module(extrasrc(meta_interface),[is_plantuml_command/1, call_plantuml_command/3]).
2867 :- use_module(extrasrc(meta_interface),[is_plantuml_command_for_expr/1, call_plantuml_command_for_expr/4]).
2868 :- use_module(extrasrc(meta_interface),[command_unavailable/2]).
2869
2870 % --------------------------------------------------------
2871 % New preferred API for calling DOT / TABLE commands in ProB2 JFX:
2872 % get_dot_commands_in_state/2 and call_dot_command_in_state/4
2873 % get_planuml_commands_in_state/2 and call_plantuml_command_in_state/4
2874 % get_table_commands_in_state/2 and call_table_command_in_state/4
2875
2876 get_commands_in_state(Category,StateID,List) :-
2877 tcltk_interface:tcltk_try_goto_node_with_id(StateID),
2878 findall(command(Command,Name,Description,NumberOfFormulaArgs,RelevantEclipsePrefs,AdditionalInfo,AvailMsg),
2879 (is_a_command(Category,Command,Name,Description,NumberOfFormulaArgs,RelevantPrefs,AdditionalInfo),
2880 maplist(convert_pref,RelevantPrefs,RelevantEclipsePrefs),
2881 (command_unavailable(Command,AvailMsg) -> true ; AvailMsg = available)),
2882 List).
2883 get_commands_with_trace(Category,TransIDs,List) :-
2884 try_set_trace_by_transition_ids(TransIDs),
2885 findall(command(Command,Name,Description,NumberOfFormulaArgs,RelevantEclipsePrefs,AdditionalInfo,AvailMsg),
2886 (is_a_command(Category,Command,Name,Description,NumberOfFormulaArgs,RelevantPrefs,AdditionalInfo),
2887 maplist(convert_pref,RelevantPrefs,RelevantEclipsePrefs),
2888 (command_unavailable(Command,AvailMsg) -> true ; AvailMsg = available)),
2889 List).
2890
2891 % example call: prob2_interface:get_dot_commands_in_state(1,List).
2892 get_dot_commands_in_state(StateID,List) :- get_commands_in_state(dot,StateID,List).
2893 get_dot_commands_with_trace(TransIDs,List) :- get_commands_with_trace(dot,TransIDs,List).
2894 % example call: prob2_interface:get_plantuml_commands_in_state(1,List).
2895 get_plantuml_commands_in_state(StateID,List) :- get_commands_in_state(plantuml,StateID,List).
2896 get_plantuml_commands_with_trace(TransIDs,List) :- get_commands_with_trace(plantuml,TransIDs,List).
2897 % example call: prob2_interface:get_table_commands_in_state(1,List).
2898 get_table_commands_in_state(StateID,List) :- get_commands_in_state(table,StateID,List).
2899 get_table_commands_with_trace(TransIDs,List) :- get_commands_with_trace(table,TransIDs,List).
2900
2901 convert_pref(Pref,Res) :- eclipse_preference(ECLIPSEPREF,Pref),!,Res=ECLIPSEPREF.
2902 convert_pref(P,P) :- preference_default_value(P,_),!.
2903 convert_pref(P,P) :- print(unknown_preference(P)),nl.
2904
2905 :- use_module(extrasrc(meta_interface),[is_dot_command/6, is_plantuml_command/6, is_table_command/6]).
2906 is_a_command(dot,Command,Name,Description,NumberOfFormulaArgs,RelevantPreferences,AdditionalInfo) :-
2907 is_dot_command(Command,Name,Description,NumberOfFormulaArgs,RelevantPreferences,AdditionalInfo).
2908 is_a_command(plantuml,Command,Name,Description,NumberOfFormulaArgs,RelevantPreferences,AdditionalInfo) :-
2909 is_plantuml_command(Command,Name,Description,NumberOfFormulaArgs,RelevantPreferences,AdditionalInfo).
2910 is_a_command(table,Command,Name,Description,NumberOfFormulaArgs,RelevantPreferences,AdditionalInfo) :-
2911 is_table_command(Command,Name,Description,NumberOfFormulaArgs,RelevantPreferences,AdditionalInfo).
2912
2913
2914 call_dot_command_in_state(StateID,Command,Formulas,DotFile) :-
2915 tcltk_interface:tcltk_try_goto_node_with_id(StateID),
2916 call_dot_command_for_dotfile(Command,Formulas,DotFile).
2917 call_dot_command_with_trace(TransIDs,Command,Formulas,DotFile) :-
2918 try_set_trace_by_transition_ids(TransIDs),
2919 call_dot_command_for_dotfile(Command,Formulas,DotFile).
2920
2921 % call a dot command for generating a DotFile; used by call_dot_command_in_state
2922 call_dot_command_for_dotfile(Command,[],DotFile) :-
2923 is_dot_command(Command), !, OptionalArgs=[],
2924 call_dot_command(Command,DotFile,OptionalArgs).
2925 call_dot_command_for_dotfile(Command,[Expr],DotFile) :-
2926 is_dot_command_for_expr(Command), !, OptionalArgs=[],
2927 call_dot_command_for_expr(Command,Expr,DotFile,OptionalArgs).
2928 call_dot_command_for_dotfile(Command,Formulas,DotFile) :-
2929 add_internal_error('Illegal dot call: ',call_dot_command_for_dotfile(Command,Formulas,DotFile)),
2930 fail.
2931
2932
2933 call_plantuml_command_in_state(StateID,Command,Formulas,UmlFile) :-
2934 tcltk_interface:tcltk_try_goto_node_with_id(StateID),
2935 call_plantuml_command_for_pumlfile(Command,Formulas,UmlFile).
2936 call_plantuml_command_with_trace(TransIDs,Command,Formulas,UmlFile) :-
2937 try_set_trace_by_transition_ids(TransIDs),
2938 call_plantuml_command_for_pumlfile(Command,Formulas,UmlFile).
2939
2940 % call a plantuml command for generating a UmlFile; used by call_plantuml_command_in_state
2941 call_plantuml_command_for_pumlfile(Command,[],UmlFile) :-
2942 is_plantuml_command(Command), !, OptionalArgs=[],
2943 call_plantuml_command(Command,UmlFile,OptionalArgs).
2944 call_plantuml_command_for_pumlfile(Command,[Expr],UmlFile) :-
2945 is_plantuml_command_for_expr(Command), !, OptionalArgs=[],
2946 call_plantuml_command_for_expr(Command,Expr,UmlFile,OptionalArgs).
2947 call_plantuml_command_for_pumlfile(Command,Formulas,UmlFile) :-
2948 add_internal_error('Illegal plantuml call: ',call_dot_command_for_pumlfile(Command,Formulas,UmlFile)),
2949 fail.
2950
2951 % example call: prob2_interface:call_table_command_in_state(1,expr_as_table,[integer(pos,1)],Table).
2952 :- use_module(extrasrc(meta_interface),[call_command/5]).
2953 call_table_command_in_state(StateID,Command,Formulas,TableResult) :-
2954 tcltk_interface:tcltk_try_goto_node_with_id(StateID),
2955 append(Formulas,[TableResult],ActualArgs),
2956 OptionalArgs=[],
2957 debug_println(9,call_command(table,Command,_,ActualArgs,OptionalArgs)),
2958 call_command(table,Command,_,ActualArgs,OptionalArgs), debug_println(9,result(TableResult)),
2959 !.
2960 call_table_command_in_state(StateID,Command,Formulas,TableResult) :-
2961 add_error(call_table_command_in_state,'Table command failed:',call_table_command_in_state(StateID,Command,Formulas,TableResult)),
2962 TableResult = list([list(['ERROR OCCURED'])]).
2963
2964 call_table_command_with_trace(TransIDs,Command,Formulas,TableResult) :-
2965 try_set_trace_by_transition_ids(TransIDs),
2966 append(Formulas,[TableResult],ActualArgs),
2967 OptionalArgs=[],
2968 debug_println(9,call_command(table,Command,_,ActualArgs,OptionalArgs)),
2969 call_command(table,Command,_,ActualArgs,OptionalArgs), debug_println(9,result(TableResult)),
2970 !.
2971 call_table_command_with_trace(TransIDs,Command,Formulas,TableResult) :-
2972 add_error(call_table_command_with_trace,'Table command failed:',call_table_command_with_trace(TransIDs,Command,Formulas,TableResult)),
2973 TableResult = list([list(['ERROR OCCURED'])]).
2974
2975
2976 /**
2977 write_dot_for_state_viz(+StateId, +Filename)
2978
2979 Writes a dot representation of the given state to the specified file.
2980
2981 */
2982 write_dot_for_state_viz(StateId, Filename) :-
2983 get_state(StateId, State),
2984 print_cstate_graph(State, Filename).
2985
2986 /**
2987 extract_node_info(+NodeId,-Count,-Color,+LabelGenerator,-Labels)
2988
2989 Generates information about the nodes found during state space reduction
2990
2991 #### Generated Information:
2992 * Count - number of concrete states combined in the abstract state
2993 * Color - the color used to represent this state type in a visualization
2994 * Labels - determine the labels that should appear on a node in a visualization
2995 */
2996 extract_node_info(NodeId,Count,Color,LabelGenerator,Labels) :-
2997 get_reduced_node(AbsState,Count,Witness,NodeId),
2998 generate_node_color(NodeId,Witness,AbsState,Count,Color),
2999 generate_node_labels(LabelGenerator,AbsState,Labels).
3000
3001 /**
3002 extract_trans_info(+ShowSelfLoops,+TransId,-Src,-Dest,-Label,-Style,-Color)
3003
3004 Generates information about the transitions created during state space reduction
3005
3006 #### Generated Information:
3007 * Src - ID corresponding to the abstract state that is the source of the abstract transition with TransId
3008 * Dest - ID corresponding to the abstract state that is the destination of the abstract transition with TransId
3009 * Label - the label that should appear on a transition in a visualization
3010 * Style - the style that should be applied to a transition of this type in a visualization (e.g. dashed)
3011 * Color - the color used to represent a transition of this type in a visualization
3012 */
3013 extract_trans_info(ShowSelfLoops,TransId,Src,Dest,Label,Style,Color) :-
3014 reduced_trans(Src,AbsAction,Count,Dest,TransId),
3015 generate_transition_label(AbsAction,Count,Label),
3016 generate_transition_color_and_style(ShowSelfLoops,Src,AbsAction,Dest,Color,Style).
3017
3018
3019 /* ------------------ */
3020 /* Get Errors */
3021 /* ------------------ */
3022
3023 /**
3024 get_error_messages_with_span_info(-ListOfErrMsgTerms)
3025
3026 each error is of the form: error(ErrMsg,ErrType,ErrLocations)
3027 ErrMsg is an atom (aka string)
3028 ErrType is warning, internal_error or error
3029 ErrLocations is a list of terms error_span(Filename,StartLine,StartCol,EndLine,EndCol)
3030 Note: Filename is '' when not known
3031
3032 #### called by:
3033 * ProB 2.0: GetErrorItemsCommand
3034 */
3035 get_error_messages_with_span_info(ListOfErrMsgTerms) :-
3036 ignore_user_interrupt_det(get_all_errors_with_span_info_and_reset(ListOfErrMsgTerms)).
3037 % TODO: replace by this:
3038 % error(ErrMsg,ErrType,ErrLocations,GlobalContext,CallStack)
3039 %get_error_messages_with_span_and_contxt(ListOfErrMsgTerms) :-
3040 % ignore_user_interrupt_det(get_all_errors_with_span_and_context_and_reset(ListOfErrMsgTerms)).
3041
3042
3043 % ####################
3044
3045 /**
3046 generate_trace_until_condition_fulfilled(+CurState,+Condition,-Trace,-Result)
3047
3048 Animates randomly number of steps until a certain (LTL?) condition is fulfilled.
3049
3050 #### Called by:
3051 * ProB 2.0: ExecuteUntilCommand
3052
3053 #### Arguments
3054 * CurState - the ID of the current state
3055 * Condition - a condition that should be satisfied at some point (this come as parsed term from the ProB2)
3056 * Note: the condition is checked on the entire trace from CurState; not at each individual new state
3057 i.e., one should use "F e(Op)" rather than "e(Op)" if one wants to reach a state with Op enabled
3058
3059 #### Generated Information:
3060 * Trace - a list of triples representing a trace in the state space of the model being analysed
3061 * Result - the result found: ltl_found, typeerror, max_nr_of_steps_reached, deadlock
3062 */
3063 generate_trace_until_condition_fulfilled(CurState,Condition,Trace,Result) :-
3064 typecheck_temporal_formula(Condition,TypeCheckedCondition,Status),
3065 %TODO: provide option in ProB2 to choose between no_loop and ltl_state_property
3066 ( Status=ok -> find_trace_until_ltl(CurState,random,TypeCheckedCondition,no_loop,100000,Trace, Result)
3067 %FIXME: turn maximal number of steps into an argument?
3068 ; reset_errors, % Reset errors. We don't want to throw a ProBError on the Java side because the result is capsuled in Result.
3069 Result=typeerror, Trace=[]).
3070
3071 % Strategy = first or random or explore_open(Strategy) (determines how transition is chosen)
3072 % LTL_Check_Type = no_loop (check formula on entire trace) or ltl_state_property (check formula on last state of trace)
3073 find_trace_until_ltl(StateId,Strategy,Ltl,LTL_Check_Type,MaxSteps,OpTripleResultTrace, Result) :-
3074 (MaxSteps =< 0
3075 -> add_error(find_trace,'Number of maximum animation steps should be a positive integer. The number of steps which was given is ',MaxSteps)
3076 ; true),
3077 set_current_state(StateId), !, % can be backtracked
3078 % negate -> counterexample is the trace we are looking for
3079 preprocess_formula(Ltl,Ltl2),
3080 find_trace_aux(StateId,Strategy,not(Ltl2),LTL_Check_Type,0,MaxSteps,ResultTrace,ResultTrace,Names,Result),
3081 gen_op_triples(ResultTrace,Names,OpTripleResultTrace).
3082 %(gen_op_triples(ResultTrace,OpTripleResultTrace) -> print(ok(OpTripleResultTrace,result(Result))),nl
3083 % ; add_error_and_fail(prob2_interface,'trace not correctly generated',ResultTrace)).
3084
3085 find_trace_aux(CurID,_,Condition,Type,_N,_Max,StateTransitionHistory,[],[],RESULT) :-
3086 %write(checking_ltl_formula(CurID,StateTransitionHistory)),nl,
3087 (Type = ltl_state_property % only check state property requiring no trace; just current state
3088 -> evaluate_ltl_state_property(Condition,CurID,EvResult)
3089 ; evaluate_ltl_formula(Condition,StateTransitionHistory,Type,ltl:check_ap,ltl:callback_tp,EvResult)
3090 ),
3091 EvResult = false,
3092 !,
3093 RESULT=ltl_found.
3094 find_trace_aux(CurID,Strategy,Condition,Type,N,Max,StateTransitionHistory,STTail,Names,RESULT) :-
3095 tcltk_interface:tcltk_compute_options(CurID,ActionsAndIDs),
3096 ( N=Max
3097 -> debug_println(9,'Maximum number of animation steps reached.'),
3098 Names = [],
3099 RESULT = maximum_nr_of_steps_reached
3100 ; pick_action(Strategy,ActionsAndIDs,ActionId,Name,DstID) % pick action; first or random could be chosen by option
3101 -> debug_println(9,performing_action(ActionId,from_to(CurID,DstID),opts(ActionsAndIDs))),
3102 STTail = [strans(CurID,ActionId)|STTail2],
3103 Names = [Name|Names2],
3104 N1 is N+1,
3105 find_trace_aux(DstID,Strategy,Condition,Type,N1,Max,StateTransitionHistory,STTail2,Names2,RESULT)
3106 ; STTail=[], Names = [], RESULT = deadlock
3107 ).
3108
3109 gen_op_triples([],[],[]).
3110 gen_op_triples([strans(CurID,ActionId)],[Name],[op(ActionId,Name,CurID,DstID)]) :- !,
3111 transition(CurID,_,ActionId,DstID).
3112 gen_op_triples([strans(CurID,ActionId),strans(DstID,ActId)|T],[Name|NameT],[op(ActionId,Name,CurID,DstID)|Rest]) :-
3113 gen_op_triples([strans(DstID,ActId)|T],NameT,Rest).
3114
3115 :- use_module(library(random)).
3116 :- use_module(library(lists)).
3117 pick_action(first,[(ActionId,Term,DstID)|_], ActionId, Name, DstID) :- !,
3118 extract_op_name(Term,Name).
3119 pick_action(random,Options,ActionId, Name, DstID) :- !,
3120 length(Options,Len),
3121 L1 is Len+1,
3122 random(1,L1,RanChoice),
3123 debug_println(9,random(RanChoice,Len)),
3124 nth1(RanChoice,Options,(ActionId,ActionAsTerm,DstID)),
3125 extract_op_name(ActionAsTerm,Name).
3126 pick_action(explore_open(Strategy2),Options,ActionId, Name, DstID) :- !, % Try Explore New Nodes
3127 (exclude(is_already_explored,Options,Options2), Options2 = [_|_] -> true
3128 ; Options2 = Options), % all successor states already explored
3129 pick_action(Strategy2,Options2,ActionId, Name, DstID).
3130 pick_action(Strategy,Options,ActionId, Name, DstID) :- !,
3131 add_internal_error('Unknown strategy: ',pick_action(Strategy,Options,ActionId, Name, DstID)),
3132 pick_action(random,Options,ActionId, Name, DstID).
3133
3134 :- use_module(probsrc(state_space),[not_all_transitions_added/1]).
3135 is_already_explored((_ActionIDd,_Term,NextId)) :- \+ not_all_transitions_added(NextId).
3136 % TODO: min_out_degree heuristic, avoid self_loops; merge code with tcltk_random_perform2?
3137
3138
3139 % -------------------------------------
3140
3141 /**
3142 execute_model(+CurStateID,+MaxNrSteps,-TransitionInfo,-ExecutedSteps,-Result)
3143
3144 an execution engine with minimal overhead: states are not stored in visited_expression database, only first enabled operation is taken
3145 */
3146
3147 execute_model(CurStateID,MaxNrSteps,TransitionInfo,ExecutedSteps,Result) :-
3148 execute_model(CurStateID,MaxNrSteps,[],TransitionInfo,ExecutedSteps,Result).
3149
3150 /**
3151 execute_model(+CurStateID,+MaxNrSteps,+Options,-TransitionInfo,-ExecutedSteps,-Result)
3152
3153 Options can contain continue_after_errors, timeout(MS)
3154 Result is either maximum_nr_of_steps_reached, deadlock, error, internal_error, time_out
3155 */
3156 execute_model(CurStateID,MaxNrSteps,Options,TransitionInfo,ExecutedSteps,Result) :-
3157 temporary_set_preference(operation_reuse_setting,false,ChangeOccured),
3158 (ChangeOccured=true
3159 -> add_debug_message(execute_model,'Disabling OPERATION_REUSE preference for execution from state: ',CurStateID) ; true),
3160 call_cleanup(execute_model_aux(CurStateID,MaxNrSteps,Options,TransitionInfo,ExecutedSteps,Result),
3161 reset_temporary_preference(operation_reuse_setting,ChangeOccured)).
3162
3163 execute_model_aux(CurStateID,MaxNrSteps,Options,TransitionInfo,ExecutedSteps,Result) :-
3164 visited_expression(CurStateID,CurState0),
3165 prepare_state_for_specfile_trans(CurState0,CurStateID,CurState),
3166 % TODO: we still need to ensure that the individual steps below do not repack constants
3167 execute_model_steps(0,CurState,CurStateID,MaxNrSteps,Options,'$none',[],NewState,ExecutedSteps,LastAction,Transitions,Result),
3168 (ExecutedSteps>0
3169 -> (ExecutedSteps=1, LastAction=act(_ActionName,ActTerm)
3170 -> true % use real action name and term
3171 ; %ActionName='EXECUTE',
3172 ActTerm='$JUMP'('EXECUTE'(ExecutedSteps))),
3173 (memberchk(return_trace,Options)
3174 -> TransitionInfo = Transitions
3175 ; add_artificial_transition(CurStateID,ActTerm,NewState,ToID,Transition),
3176 debug_println(4,added_transition_for_execute(ExecutedSteps,ToID)),
3177 TransitionInfo = [Transition])
3178 ; TransitionInfo = none).
3179
3180 execute_model_steps(StepNr,CurState,_CurStateID,MaxNrSteps,_Options,PrevAction,PrevTrans,NewState,ExecutedSteps,LastAction,Transitions,Result) :-
3181 StepNr >= MaxNrSteps,!,
3182 NewState=CurState,
3183 ExecutedSteps=StepNr,
3184 LastAction=PrevAction,
3185 Transitions=PrevTrans,
3186 Result=maximum_nr_of_steps_reached.
3187 execute_model_steps(StepNr,CurState,CurStateID,MaxNrSteps,Options,PrevAction,PrevTrans,NewState,ExecutedSteps,LastAction,Transitions,Result) :-
3188 cli_trans_aux(StepNr,CurState,Options,ActionName,ActTerm,State2,ErrorRes),
3189 !,
3190 debug_println(20,execute(StepNr,ActionName)),
3191 S1 is StepNr+1,
3192 (nonvar(ErrorRes)
3193 -> Result=ErrorRes, ExecutedSteps=StepNr, NewState=CurState, LastAction=PrevAction
3194 ; PrevAction2=act(ActionName,ActTerm),
3195 (memberchk(return_trace,Options)
3196 -> (transition(CurStateID,ActTerm,TransID,ToID)
3197 -> Transition = op(TransID,ActionName,CurStateID,ToID)
3198 ; add_artificial_transition(CurStateID,ActTerm,State2,ToID,Transition),
3199 debug_println(4,added_transition_for_execute(ExecutedSteps,ToID))
3200 ),
3201 append(PrevTrans,[Transition],PrevTrans2)
3202 ; PrevTrans2 = []),
3203 execute_model_steps(S1,State2,ToID,MaxNrSteps,Options,PrevAction2,PrevTrans2,NewState,ExecutedSteps,LastAction,Transitions,Result)).
3204 execute_model_steps(Steps,CurState,_CurStateID,_,_Options,PrevAction,Transitions,CurState,Steps,PrevAction,Transitions,deadlock).
3205
3206 :- use_module(specfile,[specfile_possible_trans_name_for_successors/2,prepare_state_for_specfile_trans/3,
3207 specfile_trans_or_partial_trans/7]).
3208 :- use_module(error_manager,[throw_enumeration_warnings_in_current_scope/0, add_internal_error/2, error_occurred_in_error_scope/0]).
3209 :- use_module(tools_meta,[safe_time_out/3]).
3210
3211 % TO DO: use same optimisation as in -execute in prob_cli.pl (get_possible_next_operation_for_execute)
3212 cli_trans_aux(StepNr,CurState,Options,ActionName,Act,NewState,ErrorRes) :-
3213 specfile_possible_trans_name_for_successors(CurState,ActionName),
3214 catch_enumeration_warning_exceptions(
3215 (throw_enumeration_warnings_in_current_scope,
3216 (member(timeout(MS),Options) ->
3217 safe_time_out(specfile_trans_or_partial_trans(CurState,ActionName,Act,NewState,_TransInfo1,Residue,_),MS,TR)
3218 ; specfile_trans_or_partial_trans(CurState,ActionName,Act,NewState,_TransInfo2,Residue,_) % no time-out !
3219 ),
3220 (TR==time_out
3221 -> add_error(execute,'Timeout occured during execute after step: ',StepNr),ErrorRes=time_out
3222 ; error_occurred_in_error_scope ->
3223 (member(continue_after_errors,Options) -> true
3224 ; add_error(execute,'Error occured during execute after step: ',StepNr),ErrorRes=error)
3225 ; true)
3226 ),
3227 (add_error(virtual_time_out_execute,'Virtual TIME-OUT occured during execute after step: ',StepNr),
3228 ActionName = '*** VIRTUAL_TIME_OUT ***', Act=ActionName,
3229 ErrorRes=time_out)
3230 ),
3231 (Residue=[] -> true
3232 ; add_internal_error('Residue during execute after step: ',StepNr:Residue),
3233 (nonvar(ErrorRes) -> true ; ErrorRes=internal_error)).
3234
3235 % -------------------------------------
3236
3237 % computes a unsat core
3238 :- use_module(tools,[start_ms_timer/1, stop_ms_walltimer_with_msg/2]).
3239 get_unsat_core_with_fixed_conjuncts(Pred,FixedPreds,CoreOut) :-
3240 typecheck_pred_for_unsat_core(Pred,TypedPred),
3241 maplist(typecheck_pred_for_unsat_core,FixedPreds,TypedFixedPreds),
3242 conjunct_predicates(TypedFixedPreds,Conj),
3243 format('Computing an unsat core~n',[]), start_ms_timer(Timer),
3244 unsat_chr_core_with_fixed_conjuncts_auto_time_limit(TypedPred,Conj,2000,Core),
3245 stop_ms_walltimer_with_msg(Timer,'Computed unsat core'),
3246 translate_bexpression(Core,CoreOut).
3247
3248 % computes the unsat core of minimal size:
3249 get_minimum_unsat_core_with_fixed_conjuncts(Pred,FixedPreds,CoreOut) :-
3250 typecheck_pred_for_unsat_core(Pred,TypedPred),
3251 maplist(typecheck_pred_for_unsat_core,FixedPreds,TypedFixedPreds),
3252 conjunct_predicates(TypedFixedPreds,Conj),
3253 format('Computing the minimal unsat core~n',[]),
3254 minimum_unsat_core_with_fixed_conjuncts(TypedPred,Conj,Core),
3255 translate_bexpression(Core,CoreOut).
3256
3257 typecheck_pred_for_unsat_core(PIn,POut) :-
3258 predicate_typecheck_for_eval(PIn,TExpr),
3259 (get_texpr_expr(TExpr,exists(_,POut)) -> true
3260 ; format(user_error,'Predicate for unsat core is not existentially quantified~n',[]),
3261 POut = TExpr).
3262
3263 /**
3264 Access information about the current version of the ProB core.
3265
3266 #### called by:
3267 * ProB 2.0: GetInternalRepresentationPrettyPrintCommand
3268 */
3269 :- use_module(specfile,[get_internal_representation/1]).
3270 get_pretty_print(PP) :-
3271 get_internal_representation(PPC),
3272 atom_codes(PP,PPC).
3273
3274 get_pretty_print_unicode(PP) :-
3275 with_translation_mode(unicode,get_pretty_print(PP)).
3276
3277 :- use_module(specfile, [get_internal_representation/4]).
3278 :- use_module(translate, [set_print_type_infos/1]).
3279 :- use_module(bmachine, [b_get_eventb_machine_as_classicalb_codes/3]).
3280 /**
3281 Pretty-print the machine's internal representation in B syntax.
3282
3283 #### called by:
3284 * ProB 2.0: GetInternalRepresentationCommand
3285 prob2_interface:get_machine_internal_representation([translation_mode(atelierb)],PP).
3286 */
3287 get_machine_internal_representation(Options, PP) :-
3288 (selectchk(translation_mode(TransMode), Options, Options1) -> true ; TransMode = ascii, Options1 = Options),
3289 (selectchk(type_infos(TypeInfos), Options1, Options2) -> true ; TypeInfos = none, Options2 = Options1),
3290 Options2 == [],
3291 ((TransMode=atelierb ; TransMode=atelierb_pp) -> AdditionalInfo=false, UnsetMinorMode = true
3292 ; AdditionalInfo=true, UnsetMinorMode = false),
3293 (animation_minor_mode(eventb), TransMode=atelierb
3294 -> with_translation_mode(TransMode, b_get_eventb_machine_as_classicalb_codes(_,AdditionalInfo,PPC))
3295 % above will set type infos to true !
3296 ; with_translation_mode(TransMode, get_internal_representation(PPC, AdditionalInfo, UnsetMinorMode, TypeInfos))
3297 ),
3298 atom_codes(PP, PPC).
3299
3300
3301
3302 % Gets a names of the given operations
3303 unpack_operation(ListOfOperation, NamesOfOperations) :-
3304 unpack_operation_aux(ListOfOperation, NamesOfOperations).
3305 unpack_operation_aux([b(operation(Name, _, _, _))|T], [Name|T1]):-
3306 unpack_operation_aux(T, T1).
3307 unpack_operation_aux([], []).
3308
3309 :- use_module(bmachine, [b_get_machine_operation/4, b_get_machine_operation_for_animation/4,
3310 b_safe_get_initialisation_from_machine/2]).
3311 get_operations_and_names(Ops, Names) :-
3312 findall(b(operation(Name, OutputParameters, InputParameter, Body)),
3313 %b_get_machine_operation(Name, OutputParameters, InputParameter, Body),
3314 b_get_machine_op_for_anim_with_otype(Name, OutputParameters, InputParameter, Body, _),
3315 AllOperations),
3316 unpack_operation(AllOperations, AllNames),
3317 (b_safe_get_initialisation_from_machine(Body, _)
3318 -> Ops = [b(initialisation(Body))|AllOperations], Names = ['$initialise_machine'|AllNames]
3319 ; Ops = AllOperations, Names = AllNames
3320 ).
3321
3322
3323 :- use_module(symbolic_model_checker(predicate_handling),[prime_predicate/2]).
3324 get_primed_predicate(Pred,PrimedPredOut) :-
3325 predicate_typecheck_for_eval(Pred,POutT),
3326 prime_predicate(POutT,PrimedPred),
3327 translate_bexpression(PrimedPred,PrimedPredOut).
3328
3329 % Version of get_primed_predicate/2 which does not introduce an existential quantifier.
3330 get_nonquantifying_primed_predicate(Pred,PrimedPredOut) :-
3331 temporary_set_preference(optimize_ast,false,CHNG1),
3332 call_cleanup(get_nonquantifying_primed_predicate_2(Pred,PrimedPredOut),
3333 reset_temporary_preference(optimize_ast,CHNG1)).
3334
3335 get_nonquantifying_primed_predicate_2(Pred, PrimedPredOut) :-
3336 get_eval_scope(Scope),
3337 (\+ bmachine:b_machine_is_loaded ->
3338 bmachine:b_set_empty_machine % Ensure a machine is loaded someway or another.
3339 ; true
3340 ),
3341 b_type_open_predicate(no_quantifier, Pred, Scope, Typed, Errors),
3342 (Errors=[] -> true ; add_error_and_fail(get_primed_predicate, 'Type-Errors: ', Errors)),
3343 prime_predicate(Typed, PrimedPred),
3344 translate_bexpression(PrimedPred,PrimedPredOut).
3345
3346
3347 :- use_module(extrasrc(weakest_preconditions),[weakest_precondition/3]).
3348 :- use_module(preferences, [call_with_preference/3]).
3349 get_weakest_precondition(OpName,Pred,WPOut) :-
3350 % TODO: call with preference can be removed once ProB 2 reads ASTs instead of reparsing
3351 call_with_preference(get_weakest_precondition_aux(OpName,Pred,WPOut),translate_ids_to_parseable_format,true).
3352 get_weakest_precondition_aux(OpName,Pred,WPOut) :-
3353 b_get_machine_operation(OpName,_Results,_Parameters,OpBody),
3354 predicate_typecheck_for_eval(Pred,POutT),
3355 weakest_precondition(OpBody,POutT,WP),
3356 translate_bexpression(WP,WPOut).
3357
3358 :- use_module(extrasrc(before_after_predicates),[before_after_predicate_for_operation/2]).
3359 before_after_predicate(OpName,PredicateOut) :-
3360 call_with_preference(before_after_predicate_aux(OpName,PredicateOut),translate_ids_to_parseable_format,true).
3361 before_after_predicate_aux(OpName,PredicateOut) :-
3362 before_after_predicate_for_operation(OpName,Predicate),
3363 translate_bexpression(Predicate,PredicateOut).
3364
3365 /** Synthesis Commands:
3366 *
3367 #### b_synthesis:start_synthesis_from_ui/13 called by:
3368 * ProB 2.0: BSynthesisCommand
3369 */
3370 start_synthesis_from_ui_(SynthesisMode,AdaptMachineCode,SolverTimeOut,Library,DoNotUseConstants,Solver,ConsiderIfVarNames,Operation,SynthesisType,Positive,Negative,NewMachineAtom,Distinguishing) :-
3371 start_synthesis_from_ui(SynthesisMode,AdaptMachineCode,SolverTimeOut,Library,DoNotUseConstants,Solver,ConsiderIfVarNames,Operation,SynthesisType,Positive,Negative,NewMachineAtom,Distinguishing).
3372
3373 /*
3374 #### b_synthesis:start_synthesis_single_operation_from_ui/11 called by:
3375 * BSynthesis: StartSynthesisCommand
3376 */
3377 start_synthesis_single_operation_from_ui_(SolverTimeOut,Operations,Library,DoNotUseConstants,Solver,Operation,action,Positive,Negative,CacheOperationTuple,Distinguishing) :-
3378 start_synthesis_single_operation_from_ui(SolverTimeOut,Operations,Library,DoNotUseConstants,Solver,Operation,action,Positive,Negative,CacheOperationTuple,Distinguishing).
3379
3380 /*
3381 #### b_synthesis:reset_synthesis_context/0 called by:
3382 * ProB 2.0: ResetBSynthesisCommand
3383 */
3384 reset_synthesis_context_ :- reset_synthesis_context.
3385
3386 /*
3387 #### synthesis_util:get_invariant_violating_vars_from_examples/3 called by:
3388 * BSynthesis: GetViolatingVarsFromExamples
3389 */
3390 get_invariant_violating_vars_from_examples_(Positive,Negative,ViolatingVarNames) :-
3391 get_invariant_violating_vars_from_examples(Positive,Negative,ViolatingVarNames).
3392
3393 /*
3394 #### synthesis_util:get_valid_and_invalid_equality_predicates_for_operation/6 called by:
3395 * BSynthesis: VisualizeOperationCommand
3396 */
3397 get_valid_and_invalid_equality_predicates_for_operation_(OperationName,ValidAmount,InvalidAmount,ValidPrettyEqualityTuples,InvalidPrettyEqualities,IgnoredIDs) :-
3398 get_valid_and_invalid_equality_predicates_for_operation(OperationName,ValidAmount,InvalidAmount,ValidPrettyEqualityTuples,InvalidPrettyEqualities,IgnoredIDs).
3399
3400 /*
3401 #### synthesis_util:get_valid_and_invalid_equality_predicates_for_invariants/4 called by:
3402 * BSynthesis: VisualizeInvariantsCommand
3403 */
3404 get_valid_and_invalid_equality_predicates_for_invariants_(ValidAmount,InvalidAmount,ValidPrettyEqualities,InvalidPrettyEqualities) :-
3405 get_valid_and_invalid_equality_predicates_for_invariants(ValidAmount,InvalidAmount,ValidPrettyEqualities,InvalidPrettyEqualities).
3406
3407 /*
3408 #### synthesis_util:adapt_machine_code_for_operations/2 called by:
3409 * BSynthesis: AdaptMachineCodeForOperationsCommand
3410 */
3411 adapt_machine_code_for_operations_(Operations,NewMachineAtom) :-
3412 adapt_machine_code_for_operations(Operations,NewMachineAtom).
3413
3414 /*
3415 #### predicate_data_generator:generate_synthesis_data_from_predicate_untyped_/5 called by:
3416 * BSynthesisDataGenerator: SynthesisDataFromPredicateCommand
3417 */
3418 generate_synthesis_data_from_predicate_untyped_(MachinePath, AugmentRecords, SolverTimeoutMs, UntypedPredAst, AugmentedSetOfData) :-
3419 generate_synthesis_data_from_predicate_untyped(MachinePath, AugmentRecords, SolverTimeoutMs, UntypedPredAst, AugmentedSetOfData).
3420
3421 /*
3422 #### operation_data_generator:generate_operation_data_from_machine_path_/4 called by:
3423 * BSynthesisDataGenerator: SynthesisDataFromOperationCommand
3424 */
3425 generate_operation_data_from_machine_path_(MachinePath, AugmentRecords, SolverTimeoutMs, OperationData) :-
3426 generate_operation_data_from_machine_path(MachinePath, AugmentRecords, SolverTimeoutMs, OperationData).
3427
3428 /*
3429 #### operation_data_generator:generate_data_from_machine_operation_/6 called by:
3430 * BSynthesisDataGenerator: SynthesisDataFromOperationCommand
3431 */
3432 generate_data_from_machine_operation_(OperationName, Augmentations, SolverTimeoutMs, AbsoluteFilePath, MachineName, OperationData) :-
3433 generate_data_from_machine_operation(OperationName, Augmentations, SolverTimeoutMs, AbsoluteFilePath, MachineName, OperationData).
3434
3435 /*
3436 #### called by:
3437 * ProB 2.0: GetMachineOperationNamesCommand
3438 */
3439 :- use_module(probcspsrc(haskell_csp),[channel/2]).
3440
3441 csp_channel_or_start('start_cspm_MAIN').
3442 csp_channel_or_start('start_cspm'). % TO DO: do we also need to support print channel ?
3443 csp_channel_or_start(Name) :- channel(Name,_).
3444
3445 get_machine_operation_names(MachineOperationNames) :- b_or_z_mode,!,
3446 findall(MachineOperationName,b_is_operation_name(MachineOperationName),MachineOperationNames).
3447 get_machine_operation_names(ChannelNames) :- csp_mode,!,
3448 findall(Name, csp_channel_or_start(Name),ChannelNames).
3449 get_machine_operation_names([]).
3450
3451 :- use_module(probsrc(bsyntaxtree), [get_texpr_id/2]).
3452 :- use_module(probsrc(bmachine),[b_get_operation_non_det_modifies/2, b_get_operation_normalized_read_write_info/3]).
3453 % get list of operation info terms of the form
3454 % operation_info(Name,ResultNames,ParameterNames,TopLevel,OType)
3455 % where ResultNames and ParameterNames are list of atomic names
3456 % TopeLevel is true if the operation is a top-level operation for animation/model checking
3457 % OType is classic, csp or eventb_operation %was eventb_operation(ChangeSet,ParaValues,Operation)
3458 get_machine_operation_infos(MachineOperationInfos) :- b_or_z_mode,!,
3459 % TODO: ensure that we do not need to consider preference(show_eventb_any_arguments,EVENTB)
3460 % TODO: examine what happens for CSP||B
3461 findall(operation_info(Name,ResultNames,ParameterNames,TopLevel,OTypeF,Read,Modified,NonDetModifies),
3462 (b_get_machine_op_for_anim_with_otype(Name, Results, AnimParameters,_, OType),
3463 maplist(get_texpr_id,Results,ResultNames),
3464 maplist(get_texpr_id,AnimParameters,ParameterNames),
3465 functor(OType,OTypeF,_),
3466 % TO DO: obtain machine file or machine name
3467 (b_top_level_operation(Name) -> TopLevel = true ; TopLevel=false),
3468 (b_get_operation_normalized_read_write_info(Name,OpRead,Modified)
3469 -> exclude(op_id,OpRead,Read)
3470 % exclude query operations called in expressions (allow_operation_calls_in_expr);
3471 %ProB2 Java cannot deal with it and raises exception for non-atomic identifiers
3472 ; Read=unknown,Modified=unknown
3473 ),
3474 (b_get_operation_non_det_modifies(Name,NonDetModifies) -> true ; NonDetModifies=unknown)
3475 ),
3476 MachineOperationInfos).
3477 get_machine_operation_infos(ChannelInfos) :- csp_mode,!,
3478 findall(operation_info(Name,[],[],true,csp,[],[],[]), csp_channel_or_start(Name),ChannelInfos).
3479 get_machine_operation_infos(Infos) :- xtl_mode,!,
3480 findall(operation_info(Name,[],ParaNames,true,xtl,[],[],[]),
3481 xtl_interface:xtl_transition_parameters(Name,ParaNames),
3482 Infos).
3483 get_machine_operation_infos([]).
3484
3485 % get the operation for animation (possibly lifting ANY identifiers to paramaters) and returning OType
3486 b_get_machine_op_for_anim_with_otype(Name, Results, AnimParameters, AnimBody, OType) :-
3487 b_get_machine_operation(Name, _Results, _RealParameters,_RealBody,OType,_OpPos),
3488 b_get_machine_operation_for_animation(Name, Results, AnimParameters, AnimBody).
3489
3490 :- use_module(library(lists)).
3491 %%Same as untyped
3492 get_machine_operation_infos_typed(MachineOperationInfos) :- b_or_z_mode,!,
3493 % TODO: ensure that we do not need to consider preference(show_eventb_any_arguments,EVENTB)
3494 % TODO: examine what happens for CSP||B
3495 findall(operation_info(Name,ResultNames,ParameterNames,TopLevel,OTypeF,Read,Modified,NonDetModifies, TypeMap),
3496 (b_get_machine_op_for_anim_with_otype(Name, Results, AnimParameters,_, OType),
3497
3498 maplist(get_texpr_id,Results,ResultNames),
3499 get_texpr_types(Results,ResultTypes),
3500 keys_and_values(ResultMap, ResultNames, ResultTypes),
3501 maplist(get_texpr_id,AnimParameters,ParameterNames),
3502 get_texpr_types(AnimParameters,ParameterTypes),
3503 keys_and_values(ParameterMap, ParameterNames, ParameterTypes),
3504
3505 functor(OType,OTypeF,_),
3506 % TO DO: obtain machine file or machine name
3507 (b_top_level_operation(Name) -> TopLevel = true ; TopLevel=false),
3508 (b_get_operation_normalized_read_write_info(Name,OpRead,Modified)
3509 -> exclude(op_id,OpRead,Read),
3510 get_constants_type(OpRead, ConstReadType),
3511 get_variable_type(OpRead, VarReadType), % TO DO: ids appear multiple times in TypeMap if read and written
3512 get_variable_type(Modified, ModifiedType),
3513 append([ConstReadType, VarReadType, ModifiedType], VarMap)
3514 % exclude query operations called in expressions (allow_operation_calls_in_expr);
3515 %ProB2 Java cannot deal with it and raises exception for non-atomic identifiers
3516 ; Read=unknown,Modified=unknown,
3517 VarMap = []
3518 ),
3519 (b_get_operation_non_det_modifies(Name,NonDetModifies)
3520 -> maplist(b_is_variable, NonDetModifies, NonDetModifiesType),
3521 keys_and_values(NonDetModifiedMap, NonDetModifies, NonDetModifiesType)
3522 ; NonDetModifies=unknown,
3523 NonDetModifiedMap = []
3524 ),
3525 append([ResultMap, ParameterMap, VarMap, NonDetModifiedMap], TypeMap)
3526 ),
3527 MachineOperationInfos).
3528 get_machine_operation_infos_typed(ChannelInfos) :- csp_mode,!,
3529 findall(operation_info(Name,[],[],true,csp,[],[],[],[]), csp_channel_or_start(Name),ChannelInfos).
3530 get_machine_operation_infos_typed([]).
3531
3532 %% note exclude return the elements where the predicate is not succesful
3533 get_constants_type(ConstList, Map) :-
3534 exclude(b_is_variable, ConstList, Filtered),
3535 maplist(b_is_constant, Filtered, Types),
3536 keys_and_values(Map, Filtered, Types).
3537
3538 get_variable_type(VarList, Map) :-
3539 exclude(b_is_constant, VarList, Filtered),
3540 maplist(b_is_variable, Filtered, Types),
3541 keys_and_values(Map, Filtered, Types).
3542
3543 op_id(op(_)).
3544
3545
3546 :- use_module(bmachine,[b_filenumber/4, get_machine_identifiers/2, get_machine_identifiers_with_pp_type/2]).
3547
3548 get_all_spec_identifiers(SortedAllIDs) :-
3549 get_spec_identifiers2(AllIDs),
3550 sort(AllIDs,SortedAllIDs).
3551
3552 :- use_module(probcspsrc(haskell_csp),[get_cspm_identifier/2]).
3553 get_spec_identifiers2(AllIDs) :- b_or_z_mode, !,
3554 findall(ID,get_machine_identifiers_with_pp_type(_,ID),LIds), append(LIds,AllIDs).
3555 get_spec_identifiers2(AllIDs) :- csp_mode,!,
3556 findall([ID,''],get_cspm_identifier(_,ID),AllIDs).
3557 get_spec_identifiers2([]).
3558
3559 % get a list of all machine files: TO DO: extend for CSP, Alloy, TLA...
3560 get_machine_files(Files) :-
3561 findall(b_file(Name,Extension,Filename),b_filenumber(Name,Extension,_,Filename), Files).
3562 % TODO: add .cfg file for TLA+ if it exists
3563
3564
3565 % a predicate to obtain possible identifier completions for current machine
3566 % the list contains entries like: completion(`alignment-baseline`,SVG attribute)
3567 :- use_module(tools_matching,[fuzzy_match_codes_lower_case/2, codes_to_lower_case/2, get_current_expr_keywords/1,
3568 get_current_keywords/1, get_all_svg_attributes/1,
3569 is_svg_color_name/1, is_svg_template/2,
3570 is_dot_color_name/1,get_all_dot_attributes/1]).
3571 get_possible_completions(ID,_Options,Completions) :-
3572 special_id_match_pattern(ID,Category,IDSuffix),!, % treat things like svg$stro -> complete to stroke without $svg
3573 get_possible_completions(IDSuffix,[keywords(Category),lower_case],Completions).
3574 get_possible_completions(ID,Options,Completions) :-
3575 get_match_ids(Options,SortedAllIDs),
3576 atom_codes(ID,IDCodes0),
3577 (member(lower_case,Options) -> codes_to_lower_case(IDCodes0,IDCodes), Opt=lower_case
3578 ; Opt=case_sensitive, IDCodes = IDCodes0),
3579 findall([Target,Type,Kind],(member([Target,Type,Kind],SortedAllIDs),atom_codes(Target,TargetCodes),
3580 match(Opt,IDCodes,TargetCodes)),Completions0),
3581 (member(latex_to_unicode,Options),
3582 atom_concat('\\',Latex,ID),
3583 latex_to_unicode(Latex,Unicode)
3584 -> ord_union([[Unicode,Latex,unicode]],Completions0,Completions1)
3585 ; Completions1=Completions0
3586 ),
3587 (member(ascii_to_unicode,Options),
3588 ascii_to_unicode(ID,Unicode2)
3589 -> ord_union([[Unicode2,ID,unicode]],Completions1,Completions2)
3590 ; Completions2=Completions1
3591 ),
3592 maplist(completion_add_backquotes_if_required,Completions2,Completions). % only in classical_b_mode?
3593
3594 special_id_match_pattern(ID,Category,IDSuffix) :- atom_codes(ID,Codes),
3595 category_pattern(Pattern,Category),
3596 append(Pattern,SuffixCodes,Codes),
3597 atom_codes(IDSuffix,SuffixCodes).
3598
3599 category_pattern("$",special_categories_only). % list of patterns below:
3600 category_pattern("col$",svg_colors_only).
3601 category_pattern("col_dot$",dot_colors_only).
3602 category_pattern("dot$",dot_only).
3603 category_pattern("svg$",svg_only).
3604 category_pattern("rec_svg$",svg_templates_only).
3605 category_pattern("tex$",latex_only).
3606 category_pattern("str$",strings_only).
3607 category_pattern("qstr$",quoted_strings_only).
3608 % TODO: maybe find better pattern svg:: and support other categories like dot, ext, ...
3609
3610 get_all_special_categories(L) :- findall(ID, (category_pattern(Cs,_),atom_codes(ID,Cs)),L).
3611
3612 % this is not very efficient;
3613 % general check for all completions is not sufficient and leads to incorrect backquotes, e.g., for pragmas: `@desc` or latex: `\alpha`
3614 % backquote check only for svg attributes and identifiers
3615 completion_add_backquotes_if_required([Completion,Type,Kind],BQCompletion) :-
3616 ((Kind = svg; Kind = spec_id),
3617 translate:id_requires_escaping(Completion)
3618 -> tools:ajoin(['`',Completion,'`'],BQC), BQCompletion = completion(BQC, Type)
3619 ; Kind = quoted_string % Note: in principle dot and svg colours are also used as strings
3620 -> tools:ajoin(['"',Completion,'"'],BQC), BQCompletion = completion(BQC, Type) % TODO: B Escaping required??
3621 ; BQCompletion = completion(Completion,Type)).
3622
3623
3624 :- use_module(tools_lists,[common_prefix_atom/2]).
3625 % Kind is either expr, latex or all
3626 get_possible_completion(ID,Kind,Completion) :-
3627 get_possible_completions(ID,[keywords(Kind)],Completions0),
3628 maplist(ignore_type,Completions0,Completions),
3629 (select(ID,Completions,C2), C2 \= []
3630 -> true % find a longer prefix in case ID is valid, so that we can find longer and longer completions in the UI
3631 ; C2=Completions),
3632 common_prefix_atom(C2,Completion).
3633 % if Completion=ID we could return the first completion or cycle through them
3634
3635 ignore_type(completion(Id,_),Id).
3636
3637 match(case_sensitive,Pattern,TargetCodes) :- !, prefix(TargetCodes,Pattern).
3638 match(lower_case,Pattern,TargetCodes) :- codes_to_lower_case(TargetCodes,TC2), prefix(TC2,Pattern).
3639
3640 get_possible_fuzzy_matches(ID,FuzzyMatches) :-
3641 get_match_ids([keywords(expr)],SortedAllIDs),
3642 atom_codes(ID,IDCodes),
3643 findall(Target,(member([Target,_,_],SortedAllIDs),atom_codes(Target,TargetCodes),
3644 fuzzy_match_codes_lower_case(IDCodes,TargetCodes)),FuzzyMatches).
3645
3646 :- use_module(library(ordsets),[ord_union/3]).
3647 :- use_module(translate,[get_latex_keywords/1, get_latex_keywords_with_backslash/1, ascii_to_unicode/2, latex_to_unicode/2]).
3648 get_match_ids(Options,Ids) :-
3649 get_match_ids2(Options,Keywords,Kind),
3650 maplist(add_id_type_kind(Kind),Keywords,Ids).
3651
3652 :- use_module(btypechecker,[machine_string/1]).
3653 % provides list [Id, Type, Kind]; Kind: latex, svg, dot, expr, all, spec_id, unicode
3654 get_match_ids2(Options,Ids,special) :- member(keywords(special_categories_only),Options),!,
3655 get_all_special_categories(Ids). % svg only
3656 get_match_ids2(Options,Ids,latex) :- member(keywords(latex_only),Options),!,
3657 get_latex_keywords(Ids). % latex only, without leading backslash
3658 get_match_ids2(Options,Ids,svg) :- member(keywords(svg_only),Options),!,
3659 get_all_svg_attributes(Ids). % svg only
3660 get_match_ids2(Options,Ids,dot) :- member(keywords(dot_only),Options),!,
3661 get_all_dot_attributes(Ids).
3662 get_match_ids2(Options,Ids,svg_color) :- member(keywords(svg_colors_only),Options),!,
3663 findall(Id,is_svg_color_name(Id),Ids).
3664 get_match_ids2(Options,Ids,dot_color) :- member(keywords(dot_colors_only),Options),!,
3665 findall(Id,is_dot_color_name(Id),Ids).
3666 get_match_ids2(Options,Ids,svg_template) :- member(keywords(svg_templates_only),Options),!,
3667 findall(Id,is_svg_template(_Kind,Id),Ids).
3668 get_match_ids2(Options,Ids,string) :- member(keywords(strings_only),Options),!,
3669 get_all_strings(Ids).
3670 get_match_ids2(Options,Ids,quoted_string) :- member(keywords(quoted_strings_only),Options),!,
3671 get_all_strings(Ids).
3672 get_match_ids2(Options,Ids,Kind) :- select(keywords(Kind),Options,Options2),!,
3673 get_match_ids(Options2,SortedAllIDs), % already adds kinds!
3674 (Kind=latex -> get_latex_keywords_with_backslash(Keywords)
3675 ; Kind=expr -> get_current_expr_keywords(Keywords)
3676 ; Kind=all -> get_current_keywords(Keywords)
3677 ; Kind=svg -> get_all_svg_attributes(Keywords)
3678 ; Kind=string -> get_all_strings(Keywords)
3679 ; add_internal_error('Unknown ids kind:',get_match_ids2(Options,Ids,Kind)), Keywords=[], Kind=unknown
3680 ),
3681 ord_union(SortedAllIDs,Keywords,Ids).
3682 get_match_ids2(_,SortedAllIDs,spec_id) :- get_all_spec_identifiers(SortedAllIDs).
3683 get_all_strings(SIDs) :- findall(Id,machine_string(Id),Ids), sort(Ids,SIDs).
3684
3685 add_id_type_kind(Kind,Id,IdType) :-
3686 (Kind=latex -> KindInfo = 'LaTeX'
3687 ; Kind=svg -> KindInfo = 'SVG attribute'
3688 ; Kind=svg_color -> KindInfo = 'SVG color'
3689 ; Kind=svg_template -> KindInfo = 'VisB SVG object'
3690 ; Kind=string -> KindInfo = 'STRING'
3691 ; Kind=quoted_string -> KindInfo = 'STRING'
3692 ; Kind=dot -> KindInfo = 'dot attribute'
3693 ; Kind=dot_color -> KindInfo = 'dot color'
3694 ; KindInfo = ''),
3695 (Id = [Id0,Type] -> IdType = [Id0,Type,Kind]
3696 ; Id \= [_,_,_] -> IdType = [Id,KindInfo,Kind]
3697 ; IdType = Id).
3698
3699 % -----------------------
3700
3701 :- use_module(bmachine_static_checks, [extended_static_check_machine/0]).
3702 :- use_module(visbsrc(visb_visualiser),[extended_static_check_default_visb_file/0]).
3703 :- use_module(extrasrc(simb_parser),[extended_static_check_default_simb_file/0]).
3704 /**
3705 prob2_extended_static_check(-Problems)
3706 */
3707 prob2_extended_static_check(Problems) :-
3708 extended_static_check_machine,
3709 extended_static_check_default_visb_file, % maybe we should make this optional
3710 extended_static_check_default_simb_file, % ditto
3711 get_all_errors_with_span_info_and_reset(Problems).
3712
3713 :- use_module(wdsrc(well_def_analyser), [analyse_wd_for_machine/3]).
3714 /**
3715 prob2_check_well_definedness(-NrDischarged,-NrTotal)
3716 */
3717 prob2_check_well_definedness(NrDischarged,NrTotal) :-
3718 analyse_wd_for_machine(NrDischarged,NrTotal,_).
3719
3720
3721 :- use_module(extension('banditfuzz/welldef'), [ensure_wd/2]).
3722 :- use_module(probsrc(b_ast_cleanup), [clean_up_pred/3]).
3723 prob2_ensure_wd(Pred, Res) :-
3724 get_eval_scope(Scope),
3725 b_type_open_predicate(no_quantifier,Pred,Scope,TPred,Errors),
3726 (Errors=[] -> true ; add_error_and_fail(prob2_ensure_wd, 'Type-Errors: ', Errors)),
3727 clean_up_pred(TPred, [], PreCleaned),
3728 ensure_wd(PreCleaned, WdPred),
3729 clean_up_pred(WdPred, [], CleanWd),
3730 translate_bexpression(CleanWd,Res).
3731
3732
3733
3734
3735 % -----------
3736 :- use_module(visbsrc(visb_visualiser),[load_visb_file/1,
3737 load_visb_definitions_from_list_of_facts/2,
3738 get_visb_attributes_for_state/2,
3739 get_default_visb_file/2,
3740 get_visb_click_events/1, get_visb_hovers/1, get_visb_items/1,
3741 get_visb_svg_objects/1,
3742 perform_visb_click_event/4,
3743 visb_file_is_loaded/1,
3744 visb_file_is_loaded/3]).
3745 :- use_module(visbsrc(visb_html_export),[get_visb_default_svg_file_contents/1,
3746 generate_visb_html_for_history/2,
3747 generate_visb_html_for_history_with_vars/1,
3748 generate_visb_html_for_current_state/2,
3749 generate_visb_html/3,
3750 generate_visb_html_codes_for_states/3]).
3751
3752 % load a VisB JSon file: this needs to be re-loaded everytime a new model is loaded or re-loaded
3753 prob2_load_visb_file(JSonFile) :-
3754 load_visb_file(JSonFile).
3755
3756 prob2_load_visb_definitions_from_list_of_facts(DefFilePath, ListOfFacts) :-
3757 load_visb_definitions_from_list_of_facts(DefFilePath, ListOfFacts).
3758
3759 % Check whether a non-empty VisB visualization is currently loaded, and if so, return its path.
3760 % This predicate doesn't fail, even when no VisB visualization is loaded or it is empty.
3761 prob2_get_loaded_visb_file(Res) :- AllowEmpty=false,
3762 (visb_file_is_loaded(JsonFile,_Svg,AllowEmpty) -> Res = json_file(JsonFile) ; Res = none).
3763
3764 % return current loaded JSON and SVG file; fail if no VisB file loaded
3765 prob2_visb_file_loaded(JsonFile,SvgFile) :- AllowEmpty=true,
3766 visb_file_is_loaded(JsonFile,SvgFile,AllowEmpty).
3767
3768 % for a given state Id (number) this returns a list with the following entries:
3769 % set_attr(SVGId,Attr,Value) -> the attribute Attr of the SVG object with the id SVGId should be set to Value
3770 prob2_visb_attributes_for_state(StateID,List) :- %start_ms_timer(T1),
3771 set_current_state(StateID), % ensure external functions like ENABLED are evaluated in correct state
3772 get_visb_attributes_for_state(StateID,List).
3773 %, stop_ms_walltimer_with_msg(T1,visb_state(StateID)).
3774
3775 % this returns two lists with the following entries:
3776 % execute_event(SVGId,Event,Predicates): when clicking on SVG object with id SVGId one should execute
3777 % the B event Event with the given list of predicates
3778 % hover(OriginID,OtherID,Attr,EnterVal,ExitVal): when hovering over the SVG Object with id OriginID
3779 % the hover should set the attribute Attr of the object OtherID to the value EnterVal,
3780 % and reset it to ExitVal upon leaving
3781 % Currently hovers do not take the current state into account; this may change in future
3782 prob2_visb_click_events_and_hovers(Events,Hovers) :-
3783 get_visb_click_events(Events),
3784 get_visb_hovers(Hovers).
3785
3786 % try and perform a click; if successful returning a list of transition ids to be performed
3787 % if the visb_event is disabled it returns an empty list
3788 % if no visb_event is associated with SvgID it fails
3789 % MetaInfoList can contain infos about shiftKey, pageX, pageY infos of the click
3790 prob2_visb_perform_click(SvgID,MetaInfoList,StateId,Transitions) :-
3791 (perform_visb_click_event(SvgID,MetaInfoList,StateId,TransIDS)
3792 -> trace_to_op_terms(TransIDS,StateId,Transitions)
3793 ; add_message(prob2_interface,'VisB ID has no event: ',SvgID),
3794 Transitions=[]
3795 ).
3796
3797 % this returns a list with the following entries: visb_item(SvgID,Attr,FormulaText,Desc,PositionTerm)
3798 prob2_visb_items(Items) :-
3799 get_visb_items(Items).
3800
3801 prob2_read_visb_path_from_definitions(Path) :-
3802 get_default_visb_file(Path,_) -> true; Path = none.
3803
3804 prob2_visb_svg_objects(Objects) :- get_visb_svg_objects(Objects).
3805 % Note: transmits parentId relationship as attributes
3806
3807 prob2_visb_default_svg_file_contents(Atom) :-
3808 get_visb_default_svg_file_contents(Codes),
3809 atom_codes(Atom,Codes).
3810
3811 prob2_export_visb_html_for_history(TransIDS, File) :-
3812 try_set_trace_by_transition_ids(TransIDS),
3813 generate_visb_html_for_history_with_vars(File).
3814 prob2_export_visb_html_for_history(TransIDS,Options,File) :-
3815 try_set_trace_by_transition_ids(TransIDS),
3816 generate_visb_html_for_history(File,Options).
3817
3818 /**
3819 prob2_save_trace_file(+TransIDs,+Style,+Options,+File)
3820
3821 Saves the trace given by the transition ids (starting from the root) as a trace
3822 file, e.g. for Style = json a ProB2 JSON trace file (.prob2trace).
3823 The trace also becomes the animator's history.
3824 Options for json, e.g. model_file=Path (the model file stored in the metadata,
3825 by default the currently opened file) or description=Text.
3826
3827 #### called by:
3828 * ProB Rodin Plugin: SaveTraceCommand
3829 */
3830 prob2_save_trace_file(TransIDs,Style,File) :-
3831 prob2_save_trace_file(TransIDs,Style,[],File).
3832 prob2_save_trace_file(TransIDs,Style,Options,File) :-
3833 try_set_trace_by_transition_ids(TransIDs),
3834 b_trace_checking:tcltk_save_history_as_trace_file(Style,Options,File).
3835
3836 prob2_export_visb_for_current_state(File) :-
3837 generate_visb_html_for_current_state(File,[]).
3838 prob2_export_visb_html_for_states(StateIds,File,Options) :-
3839 generate_visb_html(StateIds,File,Options).
3840 prob2_get_visb_html_for_states(StateIds,Options,HTMLAtom) :-
3841 generate_visb_html_codes_for_states(StateIds,[id_namespace_prefix(auto)|Options],CodesList),
3842 atom_codes(HTMLAtom,CodesList).
3843
3844 :- use_module(probsrc(b_intelligent_trace_replay),[replay_json_trace_file/5, get_replay_table/4]).
3845 % replay a JSON trace file, Status can be perfect, imperfect, partial
3846 % TransitionIDList can be used to replay the trace from root
3847 % MatchInfoList is a list of replay_step(MatchInfo,ErrorList) term for all matches
3848 % MatchInfo can be perfect, params_and_results, parameters_only...
3849 prob2_replay_json_trace_file(File,ReplayStatus,Trace,MatchInfoList) :-
3850 replay_json_trace_file(File,_,ReplayStatus,TransIds,MatchInfoList),
3851 trace_to_op_terms(TransIds, root, Trace).
3852
3853 /**
3854 prob2_replay_json_trace_file_with_messages(+File,-ReplayStatus,-TransIds,-NrOfSteps,-Messages)
3855
3856 Replays a JSON trace file (.prob2trace) from the root.
3857 ReplayStatus is perfect, imperfect or partial, TransIds the ids of the replayed
3858 transitions (skip for a skipped step), NrOfSteps the number of steps in the file.
3859 Messages are the error and warning messages of the replay; they are returned
3860 instead of being left in the error manager, so that a partial replay still succeeds.
3861
3862 #### called by:
3863 * ProB Rodin Plugin: ReplayJsonTraceCommand
3864 */
3865 prob2_replay_json_trace_file_with_messages(File,ReplayStatus,TransIds,NrOfSteps,Messages) :-
3866 replay_json_trace_file(File,Trace,ReplayStatus,TransIds,_MatchInfoList),
3867 length(Trace,NrOfSteps),
3868 (error_manager:get_all_errors_and_reset(Messages) -> true ; Messages = []).
3869
3870 /**
3871 prob2_replay_json_trace_file_with_table(+File,-ReplayStatus,-TransIds,-NrOfSteps,-Messages,-Table)
3872
3873 Like prob2_replay_json_trace_file_with_messages/5, but also returns a table
3874 explaining how each step of the trace file was replayed: a list with one term
3875 row(Step,TraceFileTxt,ReplayedTxt,MatchInfo,Mismatches,Errors) per step, where
3876 MatchInfo is e.g. precise, params_and_results, keep_name or failed,
3877 Mismatches the identifiers whose values differ from the trace file
3878 and Errors the replay errors of the step.
3879
3880 #### called by:
3881 * ProB Rodin Plugin: ReplayJsonTraceCommand
3882 */
3883 prob2_replay_json_trace_file_with_table(File,ReplayStatus,TransIds,NrOfSteps,Messages,Table) :-
3884 replay_json_trace_file(File,Trace,ReplayStatus,TransIds,MatchInfoList),
3885 length(Trace,NrOfSteps),
3886 get_replay_table(Trace,TransIds,MatchInfoList,Table),
3887 (error_manager:get_all_errors_and_reset(Messages) -> true ; Messages = []).
3888
3889 :- use_module(probsrc(b_intelligent_trace_replay),
3890 [load_json_trace_file_for_ireplay/1,
3891 get_stored_json_replay_steps/1,
3892 replay_of_current_step_is_possible_with_trans/6,
3893 ireplay_fast_forward_with_trans/7]).
3894 % interactive trace replay:
3895 prob2_interactive_replay_json_trace_file(File,List) :-
3896 load_json_trace_file_for_ireplay(File),
3897 get_stored_json_replay_steps(List).
3898
3899 prob2_interactive_replay_status(MatchOption,CurStepNr,StateID,OpTerm,MatchInfo,Errors) :-
3900 replay_of_current_step_is_possible_with_trans(MatchOption,CurStepNr,StateID,OpTerm,MatchInfo,list(Errors)), !.
3901 prob2_interactive_replay_status(_,_,_,none,failed,[]).
3902
3903 prob2_interactive_replay_fast_forward(MatchOption,CurStepNr,StateID,NrSteps,Transitions,MatchInfos,Errors) :-
3904 ireplay_fast_forward_with_trans(MatchOption,CurStepNr,StateID,NrSteps,Transitions,MatchInfos,Errors).
3905
3906
3907 % used in prob_java for TLC4B option -constantssetup
3908 get_constants_predicate(Predicate,PredicateComplete) :-
3909 tcltk_interface:tcltk_get_constants_predicate(root,Predicate,PredicateComplete).
3910 get_constants_predicate(Predicate) :-
3911 get_constants_predicate(Predicate,_).
3912
3913 % get dest state id from a state trace file, e.g. <<name>>.tla.trace generated by TLC4B
3914 replay_state_trace_from_file(File,ID,DestID) :-
3915 (state_space:current_state_id(ID) -> true
3916 ; state_space:state_space_reset,
3917 (ID = root -> true
3918 ; tcltk_interface:find_shortest_trace_to_node(root,ID,_OpIDs,TraceIDs),
3919 try_set_trace_by_transition_ids(TraceIDs))), % allow replay of multiple TLC counter example traces in ProB2-UI; maybe there is a better solution?
3920 b_trace_checking:tcltk_check_state_sequence_from_file_state_id(File,ID,DestID).
3921
3922 prob2_save_html_history(File,TransitionIds) :- % for export of animation function visualisations
3923 try_set_trace_by_transition_ids(TransitionIds), % workaround: history not updated in XTL mode?!
3924 graphical_state_viewer_images:html_print_history(File). % default depth 3, maybe add as an option
3925
3926 :- use_module(rulesdslsrc(rule_validation), [generate_report/3]).
3927 prob2_export_rule_report(StateID,File,Options) :- generate_report(StateID,File,Options). % options: checktime(.)
3928
3929 prob2_export_state_as_machine(File,StateId,StringIds) :- % empty set: export all IDs
3930 external_functions:write_state_as_machine_string(File,StateId,StringIds).
3931
3932 :- use_module(tcltk_interface, [tcltk_run_ltsmin/5]).
3933 % do_ltsmin_modelchecking(+Backend, +Options, -Result)
3934 % LTSmin modelchecking
3935 %
3936 % Backend = sequential or symbolic
3937 % Options may contain:
3938 % nodead: Disable Deadlock Checking
3939 % noinv: Disable Invariant Checking
3940 % por: Enable Partial Order Reduction
3941 %
3942 % Result may be one of:
3943 % no_counter_example_found
3944 % counter_example_found(ErrorStateId)
3945 % model_checking_aborted
3946 do_ltsmin_modelchecking(Backend, Options, Result) :-
3947 (member(nodead, Options) -> NoDead=true ; NoDead=false),
3948 (member(noinv, Options) -> NoInv=true ; NoInv=false),
3949 (member(por, Options) -> UsePOR=true ; UsePOR=false),
3950 tcltk_run_ltsmin(Backend, NoDead, NoInv, UsePOR, Res),
3951 handle_ltsmin_result(Res, Result).
3952
3953 handle_ltsmin_result(counter_example_found, Result) :-
3954 !,
3955 % current state is error state, because the ltsmin runner replayed
3956 current_state_id(ErrorStateId),
3957 Result = counter_example_found(ErrorStateId).
3958 handle_ltsmin_result(Res, Result) :- !, Result = Res.