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