1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 %:- set_prolog_flag(source_info,on).
6 % comment in if you want source location, e.g., for exceptions,...
7 % you can also comment in a line in remove_debugging_calls in debugging_calls_te.pl to see location of nl/0
8 % (and ensure debugging_calls.pl is loaded below and in term_expansion hook is set in debugging_calls_te.pl)
9 % with ?- trace, leash(off). one can creep without entering return in the debugger; with leash([redo]) the debugger only stops at the Redo-Port. Use @<RETURN> to enter Prolog commands in the debugger.
10 % leash(exception) also useful
11 % Note: to run probcli from source for ProB2 change change probcli.sh: PROBCOMMAND=probproxy and start probsli -s 8888
12
13 :- module(prob_cli, [go_cli/0,
14 run_probcli/2, run_probcli_with_argv_string/1,
15 reset_cli/0, recognised_cli_option/4, recognised_option/2, go_proxy/0,
16 print_version/1, cli_print_statistics/1]).
17
18 :- set_prolog_flag(double_quotes, codes).
19
20 :- if(predicate_property(expects_dialect(_), _)).
21 :- use_module(swi_dialect_preload,[]). % avoid warnings from SWI's SICStus emulation libraries
22 :- expects_dialect(sicstus4).
23 :- endif.
24
25 :- multifile user:portray_message/2.
26 user:portray_message(informational, imported(_Nr,_M1,_M2)) :- !.
27 user:portray_message(informational, loading(_Nr,_,_File)) :- !.
28 %user:portray_message(informational, loaded(_Nr,compiled,_File,M,MS,_)) :- !, format('~w ms for ~w~n',[MS,M]).
29 user:portray_message(informational, loaded(_Nr,_CompiledLoaded,_File,_Module,_TimeMS,_Bytes)) :- !.
30 user:portray_message(informational, foreign_resource(_Nr,_Status,_File,_Mod)) :- !.
31 user:portray_message(informational, chr_banner) :- !.
32 %user:portray_message(informational, halt) :- !.
33 %user:portray_message(informational, prompt(off,0,user,off,off,off)) :- !.
34 %user:portray_message(informational, M) :- !, write(M),nl,nl.
35
36
37 :- meta_predicate if_option_set(-,0).
38 :- meta_predicate if_option_set(-,0,0).
39 :- meta_predicate if_options_set(-,0).
40 :- meta_predicate if_option_set_loaded(-,-,0).
41 :- meta_predicate ifm_option_set(-,0).
42 :- meta_predicate ifm_option_set(-,-,0).
43 :- meta_predicate ifm_option_set_loaded(-,-,0).
44
45
46 % patch for SICStus 4.3.3 performance issue
47 % sprm_14972_patch.pl BEGIN
48 :- if((current_prolog_flag(dialect, sicstus),
49 current_prolog_flag(version_data, sicstus(4,3,3,_,_)))).
50 prolog:wf_call_like_arg(A, B, C, D, E, F, G, H, I, _) :-
51 prolog:wellformed_body_iso(A, B, C, D, E, F, G, H, I, quiet),
52 !.
53 prolog:wf_call_like_arg(A, B, C, A, D, _, E, _, _, _) :-
54 F=E:A,
55 prolog:condense_layout(B, G),
56 prolog:comp_layout2(B, G, B, H),
57 C=call(F),
58 prolog:comp_layout1(B, H, D).
59 :- endif.
60 % sprm_14972_patch.pl END
61
62
63 %:- include('self_check_off.pl').
64
65 :- use_module(module_information).
66 :- module_info(group,cli).
67 :- module_info(description,'ProB start file in cli mode.').
68
69 %:- use_module(debugging_calls).
70 %:- register_debugging_calls([pp_mnf(*), pp_cll(*), mnf(*), mnf(-,*), det_call(*)]).
71 %:- disable_debugging_calls.
72
73 :- use_module(prob_startup, [startup_prob/0, stop_prob/0]).
74 %:- use_module(pathes,[set_search_pathes/0]). % called first to set_compile_time_search_pathes
75 :- use_module(tools,[string_concatenate/3,arg_is_number/2, print_memory_used_wo_gc/1, print_memory_used_wo_gc/0,
76 split_atom/3, get_options/5, get_elapsed_walltime/2,
77 start_ms_timer/1, stop_ms_timer/1, stop_ms_timer/2, stop_ms_timer_with_msg/2]).
78 :- use_module(tools_printing,[print_error/1,format_with_colour/4, format_with_colour_nl/4]).
79 :- use_module(tools_strings,[atom_split/4,convert_atom_to_number/2]).
80 :- use_module(tools_meta,[safe_time_out/3]).
81 :- use_module(tools_lists,[count_occurences/2]).
82 :- use_module(covsrc(hit_profiler),[add_to_profile_stats/2]).
83
84 :- use_module(preferences).
85 :- set_prob_application_type(probcli). %
86
87 :- use_module(library(lists)).
88 :- use_module(library(file_systems),[file_exists/1]).
89 :- use_module(library(system)).
90 :- use_module(library(codesio)).
91 :- use_module(library(between),[between/3]).
92 :- use_module(library(terms),[term_hash/2]).
93 :- use_module(library(random),[random/3, setrand/1]).
94
95 :- use_module(self_check,[disable_interaction_on_errors/0,
96 perform_self_check/2,turn_off_run_time_type_checks/0,turn_on_run_time_type_checks/0]).
97 :- use_module(debug).
98 :- use_module(error_manager).
99 :- use_module(translate,[pretty_type/2]).
100 :- use_module(tools,[safe_absolute_file_name/2, safe_absolute_file_name/3, convert_ms_time_to_string/2]).
101 :- use_module(extension('counter/counter'),
102 [counter_init/0, new_counter/1, get_counter/2, inc_counter/1, inc_counter/2, reset_counter/1]).
103 :- use_module(state_space,[current_expression/2, portray_history/0]).
104
105
106 :- dynamic junit_mode/1.
107 :- use_module(junit_tests, [set_junit_dir/1, set_junit_test_suite_prefix/1, create_and_print_junit_result/4]).
108
109 :- use_module(b_trace_checking,[check_default_trace_for_specfile/1, tcltk_check_state_sequence_from_file/1,
110 tcltk_check_sequence_from_file/3, get_default_trace_file/3,
111 tcltk_save_history_as_trace_file/2,tcltk_save_history_as_trace_file/3]).
112 :- use_module(eventhandling,[store_virtual_event/1]).
113 :- use_module(bmachine,[b_set_initial_machine/0]).
114 :- use_module(specfile).
115 :- use_module(test_typechecker,[run_typecheck_testcase/2]).
116 :- use_module(basic_unit_tests). % basic unit tests
117 :- use_module(bsyntaxtree,[size_of_conjunction/2, get_texpr_id/2, get_texpr_description/2,
118 conjunction_to_list/2,
119 get_texpr_label/2, predicate_components/2, get_texpr_pos/2]).
120 :- use_module(bmachine,[b_write_machine_representation_to_file/3,
121 full_b_machine/1, b_write_eventb_machine_to_classicalb_to_file/1]).
122 :- use_module(state_space,[current_state_id/1, get_state_space_stats/4, compute_full_state_space_hash/1]).
123 :- use_module(xtl_interface,[set_cspm_main_process/1]).
124 :- use_module(extrasrc(meta_interface),[is_dot_command/1, call_dot_command_with_engine/4,
125 is_dot_command_for_expr/1,call_dot_command_with_engine_for_expr/5,
126 is_plantuml_command/1, is_plantuml_command_for_expr/1,
127 is_table_command/1, is_table_command_for_expr/1,
128 call_plantuml_command/2, call_plantuml_command_for_expr/4,
129 call_command/5, is_table_command/6,
130 write_table_to_text_file/2, write_table_to_csv_file/3,
131 command_description/3]).
132 :- use_module(kodkodsrc(kodkod_test),[test_kodkod/1, compare_kodkod_performance/2]).
133 :- use_module(kodkodsrc(predicate_analysis),[test_predicate_analysis/0]).
134 :- use_module(b_show_history,[write_history_to_file/2,write_values_to_file/1,
135 write_all_values_to_dir/1,write_history_to_user_output/1]).
136 :- use_module(cbcsrc(sap), [write_all_deadlocking_paths_to_xml/1, test_generation_by_xml_description/1]).
137 :- use_module(smtlib_solver(smtlib2_cli),[smtlib2_file/2, get_smtlib2_result_infos/1]).
138 :- use_module(disproversrc(disprover_test_runner), [run_disprover_on_all_pos/1,
139 load_po_file/1,print_disprover_stats/0, set_disprover_timeout/1,
140 set_disprover_options/1, reset_disprover_timeout/0]).
141 :- use_module(extrasrc(latex_processor), [process_latex_file/2]).
142 :- use_module(probltlsrc(ltl),[ltl_check_assertions/2,ltl_model_check/4]).
143 :- use_module(probltlsrc(ctl),[ctl_model_check/4]).
144
145 :- use_module(logger).
146 :- use_module(extension('zmq/master/master'),[start_master/8]).
147 :- use_module(extension('zmq/worker/worker'),[start_worker/5]).
148 :- use_module(extension('ltsmin/ltsmin'),
149 [start_ltsmin/4,ltsmin_init/3,ltsmin_loop/1,ltsmin_teardown/2,ltsmin_generate_ltlfile/2]).
150 :- use_module(extrasrc(coverage_statistics),[compute_the_coverage/5]).
151 :- use_module(value_persistance, [set_storage_directory/2, print_value_persistance_stats/0,
152 delete_cache_files_for_machine/1, delete_cache_files/0,
153 ignore_value_persistance_cache_for/1,
154 get_value_persistance_stats/1, show_cache_file_contents/1]).
155 :- use_module(prob_socketserver,[start_prob_socketserver/2]).
156 :- use_module(tcltk_interface).
157 %:- compile(gui_tcltk).
158 :- use_module(eclipse_interface).
159 :- use_module(prob2_interface,[start_animation/0, is_initialised_state/1, reset_animator/0,
160 set_eclipse_preference/2, update_preferences_from_spec/1,
161 load_cspm_spec_from_cspm_file/1, load_xtl_spec_from_prolog_file/1]).
162 :- use_module(external_functions,[print_external_function_instantiation_profile/0,
163 consult_new_external_function_library/1,
164 reload_external_libraries/0,
165 reset_argv/0,set_argv_from_list/1,set_argv_from_atom/1]).
166
167 start_probcli_timer(timer(T1,WT1)) :-
168 statistics(runtime,[T1,_]),
169 statistics(walltime,[WT1,_]).
170 stop_probcli_debug_timer(Timer,Msg) :-
171 (debug_mode(on) -> stop_probcli_timer(Timer,Msg),print_memory_used_wo_gc,nl ; true).
172 stop_probcli_timer(timer(T1,WT1),Msg) :- stop_probcli_timer(timer(T1,WT1),Msg,_).
173 stop_probcli_timer(timer(T1,WT1),Msg,WTotTime) :-
174 statistics(runtime,[T2,_]), TotTime is T2-T1,
175 statistics(walltime,[WT2,_]), WTotTime is WT2-WT1,
176 convert_ms_time_to_string(WT2,WTString),
177 format('~w ~w ms walltime (~w ms runtime), since start: ~w~n',[Msg,WTotTime,TotTime,WTString]),
178 !.
179 stop_probcli_timer(Timer,Msg,_) :- add_internal_error('Illegal timer call: ',stop_probcli_timer(Timer,Msg)).
180 print_total_probcli_timer :-
181 statistics(runtime,[T2,_]),
182 statistics(walltime,[WT2,_]),
183 format('Since start of probcli: ~w ms walltime (~w ms runtime)~n',[WT2,T2]).
184 get_probcli_elapsed_walltime(timer(_,WT1),WTotTime) :-
185 statistics(walltime,[WT2,_]), WTotTime is WT2-WT1.
186 get_probcli_elapsed_runtime(timer(RT1,_),RTotTime) :-
187 statistics(runtime,[RT2,_]), RTotTime is RT2-RT1.
188
189 :- meta_predicate timeout_call(0,-,-).
190 timeout_call(Call,NOW,PP) :- option(timeout(TO)),!,
191 statistics(runtime,[T1,_]),
192 safe_time_out(Call,TO,Res),
193 statistics(runtime,[T2,_]), Runtime is T2-T1,
194 formatsilent('Runtime for ~w: ~w ms~n',[PP,Runtime]),
195 (Res=time_out -> print('*** Timeout occurred: '), print(TO),nl,
196 print('*** Call: '), print(Call),nl,
197 nl,
198 writeln_log(timeout_occurred(NOW,Call))
199 ; true).
200 timeout_call(Call,_NOW,PP) :-
201 statistics(runtime,[T1,_]),
202 call(Call),
203 statistics(runtime,[T2,_]), Runtime is T2-T1,
204 formatsilent('Runtime for ~w: ~w ms~n',[PP,Runtime]).
205
206 set_junit_mode(X) :-
207 set_junit_dir(X),
208 retractall(junit_mode(_)),
209 statistics(runtime,[Start,_]),
210 assertz(junit_mode(Start)).
211
212 go_proxy :-
213 catch( run_probcli(['-s','8888'],[proxy]), halt(ExitCode),
214 ( nl,write('CLI halt prevented, exit code '),write(ExitCode),nl) ).
215
216 go_cli :-
217 % set_prob_application_type(probcli) is already done at compile_time
218 current_prolog_flag(argv,ArgV),
219 run_probcli_with_junit_check(ArgV).
220
221 initialise_cli :- counter_init,
222 new_counter(cli_execute_inits),
223 new_counter(cli_errors), new_counter(cli_warnings),
224 new_counter(cli_expected_errors),
225 new_counter(eval_string_nr).
226
227 % called from test_runner.pl:
228 reset_cli :-
229 announce_event(clear_specification),
230 announce_event(reset_prob),
231 reset_cli_options,
232 reset_expected_error_occurred,
233 reset_optional_errors_or_warnings,
234 reset_counter(cli_errors), reset_counter(cli_warnings),
235 reset_counter(cli_expected_errors),
236 reset_counter(eval_string_nr),
237 retractall(accumulated_infos(_,_,_)),
238 retractall(merged_individual_file_infos(_,_,_)),
239 retractall(individual_file_infos(_,_,_)),
240 (file_loaded(_)
241 -> clear_loaded_machines, % TODO: also treat by reset_prob eventhandling?
242 retractall(file_loaded(_,_)),
243 retractall(loaded_main_file(_,_))
244 ; true).
245
246 reset_cli_options :- option_verbose,verbose_off,fail.
247 reset_cli_options :- option(set_gc_trace(_X)),set_gc_trace(off),fail.
248 reset_cli_options :- option(profiling_on),profiling_off,fail.
249 % TODO: are there more options to reset?
250 reset_cli_options.
251
252 run_probcli_with_junit_check(ArgV) :-
253 catch( run_probcli(ArgV,[junit]),
254 halt(ExitCode),
255 ( ExitCode = 0 ->
256 true
257 ; ( junit_mode(S) ->
258 statistics(runtime,[E,_]), T is E - S,
259 create_and_print_junit_result([],probcli,T,error([ExitCode]))
260 ; true),
261 throw(halt(ExitCode)))).
262
263
264 % a useful entry point for Jupyter to mimic probcli execution in notebooks
265 run_probcli_with_argv_string(ArgVAtom) :- split_argv_string(ArgVAtom,Atoms),
266 (Atoms = [probcli|Atoms2] -> true ; Atoms2=Atoms),
267 run_probcli(Atoms2,[run_probcli_with_argv_string]).
268
269 split_argv_string(ArgVAtom,Atoms) :- split_atom(ArgVAtom,[' '],Atoms). % TODO: treat quoting
270
271 run_probcli(ArgV,Context) :- % format(user_output,'~n* Starting probcli with argv: ~w~n~n',[ArgV]),
272 (catch(
273 run_probcli2(ArgV),
274 Exc,
275 process_exception(Exc,Context)
276 )
277 -> stop_prob
278 ; flush_output,
279 print_error('INTERNAL ERROR OCCURRED (run_probcli failed) !'),nl,
280 error_occurred(internal_error),
281 halt_exception(1)
282 ).
283
284 :- use_module(translate,[translate_error_term/2]).
285 %process_exception(Exception,_) :- write('Exception: '),write(Exception),nl,fail. % for debugging
286 process_exception(halt(A),_) :- !, throw(halt(A)).
287 process_exception(unwind(halt(A)),_) :- !, throw(halt(A)). % SWI Prolog; other values for unwind are abort, thread_exit
288 process_exception('$aborted',_) :- !, throw('$aborted'). % thrown by SWI-Prolog on abort by user
289 process_exception(user_interrupt_signal,Context) :- !,
290 %add_error(probcli,'probcli interrupted by user (CTRL-C)').
291 statistics(walltime,[WStart,_]),
292 format_with_colour_nl(user_error,[red],'~nprobcli interrupted by user (CTRL-C), total walltime ~w ms',[WStart]),
293 (member(test_runner,Context)
294 -> throw(user_interrupt_signal) % will be caught by test_runner
295 ; error_occurred_with_msg(user_interrupt_signal,'probcli interrupted by user (CTRL-C)')
296 ).
297 process_exception(Exc,_) :-
298 (translate_error_term(Exc,S)
299 -> format_error_with_nl('Uncaught exception in probcli: ~w',[S])
300 ; true),
301 error_occurred(internal_error(exception(Exc))),fail.
302
303 no_command_issued :- \+ command_option(_).
304 command_option(X) :- option(X), \+ not_command_option(X).
305 not_command_option(verbose(_)).
306 not_command_option(profiling_on).
307 not_command_option(set_pref(_,_)).
308 not_command_option(set_preference_group(_,_)).
309 not_command_option(set_card(_,_)).
310 not_command_option(set_argv(_)).
311 not_command_option(silent).
312 not_command_option(strict_raise_error).
313 not_command_option(no_color).
314
315 probcli_startup :-
316 %print_total_probcli_timer,
317 startup_prob, % % startup_prob will already call init_preferences
318 %myheap_init,
319 initialise_cli.
320
321 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
322 :- if(environ(prob_logging_mode,true)).
323 cli_set_options(ArgV,RemArgV) :-
324 cli_init_options(['-ll'|ArgV],RemArgV). %% adds -ll to have an automatically logging probcli to /tmp/prob_cli_debug.log
325 :- else.
326 cli_set_options(ArgV,RemArgV) :- cli_init_options(ArgV,RemArgV).
327 :- endif.
328
329 %:- use_module(extension('myheap/myheap')).
330 run_probcli2(ArgV) :- %print(probcli_startup),nl_time,
331 treat_important_options_beforehand(ArgV),
332 probcli_startup,
333 reset_argv,
334 cli_set_options(ArgV,RemArgV), % recognise command-line options
335 %% cli_set_options(['-vv','-version'|ArgV],RemArgV), %% comment in to have an automatically verbose probcli
336 maplist(prob_cli:check_atom_looks_like_file,RemArgV),
337 (option(prolog_trace) -> error_manager:safe_trace ; true),
338 !,
339 run_probcli3(ArgV,RemArgV).
340
341 % treat important options beforehand, e.g., to enable debug prints straight-away, e.g., before probcli_startup
342 treat_important_options_beforehand(ArgV) :-
343 ? member(Opt,ArgV),recognised_option(Opt,RecognisedOpt),treat_important_option(RecognisedOpt),fail.
344 treat_important_options_beforehand(_).
345
346 treat_important_option(verbose(Nr)) :- verbose(Nr).
347 treat_important_option(set_gc_trace(X)) :- set_gc_trace(X).
348 treat_important_option(profiling_on) :- profiling_on.
349
350
351 run_probcli3(ArgV,RemArgV) :-
352 ( RemArgV=[File],no_command_issued,
353 get_filename_extension(File,Ext),
354 \+ do_not_execute_automatically(Ext)
355 % then assume we want to do -execute_all:
356 -> assert_option(execute(2147483647,false,current_state(1)))
357 ; true),
358 if_option_set(set_application_type(PAT),set_prob_application_type(PAT)),
359 if_option_set(test_mode,set_random_seed_to_deterministic_start_seed, set_new_random_seed),
360 ifm_option_set(verbose(VN),
361 verbose(VN), %tcltk_turn_debugging_on(5)),
362 tcltk_turn_debugging_off),
363 % TODO: reset the next three to default values if no flags present, in case we use them for tests:
364 if_option_set(set_gc_trace(GCT),set_gc_trace(GCT)),
365 if_option_set(set_gc_margin(GCM),set_gc_margin(GCM)),
366 if_option_set(set_gc_on_off(GCO),set_gc_on_off(GCO)),
367 if_option_set(profiling_on,profiling_on),
368 debug_print(9,'Command Line Arguments: '),debug_println(9,ArgV),
369 (debug_level_active_for(5) -> print_options ; true),
370 debug_print(6,'Command Line File Args: '),debug_println(6,RemArgV),
371 debug_flush_output,
372 if_option_set(cache_storage(StorageDir,SetStorMode), set_storage_directory(StorageDir,SetStorMode)),
373 if_option_set(parsercp(ParserLoc),
374 (add_message(parsercp,'Command -parcercp PATH deprecated, use -p JAVA_PARSER_PATH PATH',''),
375 set_preference(path_to_java_parser,ParserLoc))
376 ),
377 if_option_set(parserport(ParserPort),
378 connect_to_external_console_parser_on_port(ParserPort)),
379 generate_time_stamp(Datime,NOW),
380 if_option_set(log(LogF,Mode),
381 cli_start_logging(LogF,Mode,NOW,Datime,RemArgV)),
382 if_option_set(runtimechecking,
383 turn_on_run_time_type_checks,
384 turn_off_run_time_type_checks),
385 if_option_set(junit(JUX),
386 set_junit_mode(JUX)),
387 if_option_set(junit_test_suite(JUnitTestSuite),
388 set_junit_test_suite_prefix(JUnitTestSuite)),
389 set_prefs,
390 (option_verbose, (option(set_prefs_from_file(_)) ; option(set_preference_group(_,_))),
391 get_non_default_preferences(list(NDPrefs))
392 -> format('Non-default preferences:~n',[]),print_list(NDPrefs),nl ; true),
393 set_optional_errors,
394 check_unavailable_options,
395 cli_show_help(ArgV,RemArgV),
396 if_option_set(set_argv(ArgVStr),
397 set_argv(ArgVStr)),
398 if_option_set(selfcheck(_,_),
399 cli_start_selfcheck),
400 if_option_set(typechecker_test(Filename),
401 (run_typecheck_testcase(Filename,typesok) -> halt_prob(NOW,0); halt_prob(NOW,1))),
402 ifm_option_set(install_prob_lib(LIBTOINSTALL,INSTALLOPTS), install_prob_lib(LIBTOINSTALL,INSTALLOPTS)),
403 ifm_option_set(load_prob_external_library(PrologModuleFile), load_prob_external_library(PrologModuleFile)),
404 if_options_set(print_version(VERSIONKIND), print_version(VERSIONKIND)),
405 if_option_set(check_java_version, check_java_version),
406 (debug_level_active_for(5) -> print_preferences ; true),
407 if_option_set(zmq_worker(Identifier), zmq_start_worker(Identifier, NOW)),
408 %if_option_set(zmq_worker2(MasterIP, Port, ProxyID, Logfile), zmq_start_worker(MasterIP,Port,ProxyID,Logfile,NOW)),
409 % process remaining arguments as files to load
410 % some utility commands which do not require main file:
411 ifm_option_set(indent_b_file_to_file(PPBFILE0,OUTFILE,OPTS),
412 indent_b_file_to_file(PPBFILE0,OUTFILE,OPTS)), % utility to format B file
413 ifm_option_set(pretty_print_prolog_file(PPFILE0,OUTFILE),
414 pretty_print_prolog_file(PPFILE0,OUTFILE)), % utility to print Prolog file
415 debug_println(6,processing(RemArgV)),
416 cli_load_files(RemArgV,NOW), % all CLI arguments which are not understood are supposed to be files to be treated
417 debug_println(19,finished_loading(RemArgV)),
418 if_option_set(socket(Port,Loopback),
419 cli_start_socketserver(Port,Loopback)),
420 % check_all_expected_errors_occurred(NOW), % is now checked for each file; socket_server should not generate errors ?
421 debug_println(20,'% probcli execution finished'),
422 cli_print_junit_results,
423 debug_println(20,'% Stored Junit results'),
424 stop_xml_probcli_run(NOW),
425 debug_println(20,'% ProB Finished').
426
427 % finish logxml file by writing total number of errors and warnings
428 stop_xml_probcli_run(NOW) :-
429 get_counter(cli_errors,CErrs), get_counter(cli_warnings,CWarns), get_counter(cli_expected_errors,EErrs),
430 writeln_log_time(prob_finished(NOW,CErrs,CWarns)),
431 (EErrs>0
432 -> write_xml_element_to_log('probcli-errors',[errors/CErrs,warnings/CWarns,expected_errors/EErrs])
433 ; write_xml_element_to_log('probcli-errors',[errors/CErrs,warnings/CWarns])
434 ),
435 ((CErrs>0 ; CWarns>0) -> format(user_error,'! Total Errors: ~w, Warnings:~w~n',[CErrs,CWarns]) ; true),
436 stop_xml_group_in_log('probcli-run'). % Generating this tag means probcli ran to completion without segfault,...
437
438 % check if a cli argument looks like a proper filename
439 :- public check_file_arg/2. % is actually called when parsing options
440 check_file_arg(File,Command) :- normalise_option_atom(File,NF),
441 recognised_option(NF,_,_,_),!,
442 ajoin(['Command-line file argument for ', Command, ' looks like another probcli command: '],Msg),
443 add_warning(probcli,Msg,File).
444 check_file_arg(File,Command) :-
445 tools:check_filename_arg(File,Command).
446
447 % check if a remaining argument looks suspicious (e.g., like an unknown command)
448 check_atom_looks_like_file(Number) :- number(Number),!,
449 add_warning(probcli,'Command-line argument is a number (expected file name or probcli command): ',Number).
450 check_atom_looks_like_file(File) :- atom(File), !, atom_codes(File,Codes),
451 check_codes_look_like_file(Codes,File).
452 check_atom_looks_like_file(Arg) :-
453 add_warning(probcli,'Command-line argument is a compound term (expected file name or probcli command): ',Arg).
454 check_codes_look_like_file(Codes,Arg) :-
455 check_codes_resembles_command(Codes,Arg),!.
456 check_codes_look_like_file([D|T],Arg) :- is_digit_code(D),
457 (T=[] -> true
458 ; T = [D2|_], is_digit_code(D2),
459 nonmember(0'/,T), nonmember(0'.,T) % detect things like 01_Jan/a.mch
460 ),
461 !,
462 add_message(probcli,'Command-line argument looks like a number: ',Arg).
463 check_codes_look_like_file(_,_).
464
465 is_digit_code(D) :- D >= 0'0, D =< 0'9.
466
467 check_codes_resembles_command([45|_],Arg) :- !,
468 (get_possible_fuzzy_match_options(Arg,FuzzyMatches),
469 FuzzyMatches \= []
470 -> (FuzzyMatches=[FM]
471 -> ajoin(['Command-line argument ', Arg, ' looks like a probcli command! Did you mean: '],Msg),
472 add_warning(probcli,Msg,FM)
473 ; ajoin(['Command-line argument ', Arg, ' looks like a probcli command! Did you mean any of: '],Msg),
474 add_warning(probcli,Msg,FuzzyMatches)
475 )
476 ; get_possible_options_completion_msg(Arg,Completions)
477 -> ajoin(['Command-line argument ', Arg, ' looks like a probcli command! Did you mean: '],Msg),
478 add_warning(probcli,Msg,Completions)
479 ; add_message(probcli,'Command-line argument looks like an unknown probcli command: ',Arg)).
480
481 :- use_module(extrasrc(refinement_checker),[valid_failures_model/2]).
482 check_failures_mode(Shortcut,FailuresModel) :- valid_failures_model(FailuresModel,Shortcut),!.
483 check_failures_mode(Shortcut,trace) :-
484 add_warning(probcli,'Unrecognised refinement model flag (must be F, FD, T, R, RD, SF, V, VD; using default trace model T): ',Shortcut).
485
486 % ----------
487
488 cli_init_options(ArgV,RemArgV) :- %print(argv(ArgV)),nl,
489 append(ProBArgV,['--'|BArgV],ArgV),!, % pass arguments after -- to B via external_functions
490 cli_init_options2(ProBArgV,RemArgV),
491 debug_println(20,set_argv_from_list(BArgV)),
492 set_argv_from_list(BArgV).
493 cli_init_options(ArgV,RemArgV) :- cli_init_options2(ArgV,RemArgV).
494 cli_init_options2(ArgV,RemArgV) :-
495 reset_options,
496 %%assertz(option(log('/tmp/ProBLog.log'))), print('LOGGING'),nl, %% coment in to build a version of probcli that automatically logs
497 ( get_options(ArgV,recognised_cli_option,Options,RemArgV,throw(halt(1))) ->
498 assert_all_options(Options)
499 ;
500 print_error(get_options_failed(ArgV)),definite_error_occurred).
501 cli_show_help(ArgV,RemArgV) :-
502 ( (option(help) ; ArgV=[]) ->
503 print_help, (RemArgV=[] -> halt_exception ; true)
504 ; true).
505 cli_start_logging(F,Mode,NOW,Datime,RemArgV) :-
506 debug_print(20,'%logging to: '), debug_println(20,F),
507 set_log_file(F), set_logging_mode(Mode),
508 start_xml_group_in_log('probcli-run'),
509 writeln_log(start_logging(NOW,F)),
510 version(V1,V2,V3,Suffix), revision(Rev), lastchangeddate(LCD),
511 writeln_log(version(NOW,V1,V2,V3,Suffix,Rev,LCD)), % still used by log_analyser
512 current_prolog_flag(version,PV),
513 write_xml_element_to_log(version,[major/V1,minor/V2,patch/V3,suffix/Suffix,revision/Rev,lastchanged/LCD,prolog/PV]),
514 findall(Opt, option(Opt), Options),
515 write_prolog_term_as_xml_to_log(options(NOW,Options)),
516 write_prolog_term_as_xml_to_log(files(NOW,RemArgV)), %
517 datime(Datime,DateRecord),
518 writeln_log(date(NOW,DateRecord)),
519 (DateRecord=datime(Yr,Mon,Day,Hr,Min,Sec)
520 -> write_xml_element_to_log(date,[year/Yr,month/Mon,day/Day,hour/Hr,minutes/Min,seconds/Sec]) ; true).
521
522 cli_start_selfcheck :-
523 %clear_loaded_machines_wo_errors,
524 b_set_initial_machine,
525 set_animation_mode(b),
526 store_virtual_event(clear_specification), % TO DO: try and get rid of the need for this
527 start_animation,
528 option(selfcheck(ModuleCombo,Opts)),
529 (atom(ModuleCombo),
530 atom_split(Module,':',TestNrA,ModuleCombo)
531 -> convert_atom_to_number(TestNrA,TestNr),
532 Opts2=[run_only_nr(TestNr)|Opts]
533 ; Module=ModuleCombo, Opts2=Opts
534 ),
535 (option_silent_set -> Opts3=[silent|Opts2] ; option_verbose -> Opts3=[verbose|Opts2] ; Opts3=Opts2),
536 (perform_self_check(Module,Opts3) -> true ; error_occurred(selfcheck)),
537 fail.
538 cli_start_selfcheck.
539
540
541 :- dynamic file_loaded/2.
542 file_loaded(Status) :- file_loaded(Status,_File).
543
544
545 cli_load_files([],NOW) :- % no files are provided
546 !,
547 ( options_allow_start_without_file
548 -> debug_format(19,'Using empty machine to process probcli command~n',[]),
549 cli_set_empty_machine
550 ; we_did_something -> true
551 ; print('No file to process'),nl),
552 writeln_log_time(start_processing_empty_machine(NOW)),
553 start_xml_feature(process_file,filename,'$EMPTY_MACHINE',FINFO),
554 cli_process_loaded_file(NOW,'$EMPTY_MACHINE'),
555 check_all_expected_errors_occurred(NOW), % check that all expected errors occurred; below they will be checked for each file
556 stop_xml_feature(process_file,FINFO),
557 print_accumulated_infos_if_necessary.
558 cli_load_files(RemArgV,NOW) :-
559 cli_load_files2(RemArgV,NOW,0).
560
561 print_accumulated_infos_if_necessary :-
562 (option(benchmark_info_csv_output(_,_,_)) -> print_accumulated_infos(0) ; true).
563
564 cli_set_empty_machine :- % TO DO: do this more properly here and for initialise_required
565 set_animation_mode(b),
566 bmachine:b_set_empty_machine,
567 assertz(file_loaded(true,'$$empty_machine')).
568
569 empty_machine_loaded :- file_loaded(true,'$$empty_machine').
570
571
572 options_allow_start_without_file :- option(run_benchmark(_,_,_)).
573 options_allow_start_without_file :- option(eval_repl(_)).
574 options_allow_start_without_file :- option(eval_string_or_file(_,_,_,_,_)).
575 options_allow_start_without_file :- option(check_log(_)).
576 options_allow_start_without_file :- option(process_latex_file(_,_)).
577 options_allow_start_without_file :- option(socket(_,_)).
578
579 we_did_something :- option(print_version(_)).
580 we_did_something :- option(check_java_version).
581 we_did_something :- option(check_parser_version).
582 we_did_something :- option(install_prob_lib(_,_)).
583 we_did_something :- option(indent_b_file_to_file(_,_,_)).
584 we_did_something :- option(pretty_print_prolog_file(_,_)).
585
586 option_only_works_for_single_file(zmq_assertion(_Identifier)).
587 option_only_works_for_single_file(zmq_master(_Identifier)).
588
589 clear_loaded_files :-
590 (file_loaded(_) -> clear_loaded_machines_wo_errors ; true).
591
592 % called if we have at least one file
593 cli_load_files2([],_,NrFilesProcessed) :- !,
594 debug_println(19,finished_procesing_all_files(NrFilesProcessed)),
595 print_accumulated_infos(NrFilesProcessed). % print summary of all runs for different files
596 cli_load_files2([F1,F2|T],NOW,_NrFilesProcessed) :-
597 option(Option),
598 option_only_works_for_single_file(Option),!,
599 add_error(probcli,'The following option can only be used for a single file: ',Option),
600 add_error(probcli,'Multiple files provided: ',[F1,F2|T]),
601 halt_prob(NOW,0).
602 cli_load_files2(RemArgV,NOW,NrFilesProcessed) :-
603 %print_total_probcli_timer,
604 clear_loaded_files,
605 retractall(file_loaded(_,_)),
606 RemArgV = [MainFile0|Rest],!,
607 N1 is NrFilesProcessed+1,
608 cli_load_files3(MainFile0,Rest,NOW,N1).
609 cli_load_files3(MainFile0,Rest,NOW,NrOfFile) :-
610 safe_absolute_file_name(MainFile0,MainFile,[access(none)]), % converts Windows slash into Unix slash,...
611 if_option_set(file_info,print_file_info(MainFile)),
612 ((Rest=[_|_] ; NrOfFile>1)
613 -> length(Rest,RLen), Tot is NrOfFile+RLen,
614 format('~n~n% Processing file ~w/~w: ~w~n',[NrOfFile,Tot,MainFile]) % was formatsilent
615 ; true),
616 start_ms_timer(ProcessFileTimer),
617 start_xml_feature(process_file,filename,MainFile,FINFO),
618 ( file_exists(MainFile) ->
619 debug_println(6,file_exists(MainFile)),
620 ( load_main_file(MainFile,NOW,Already_FullyProcessed) ->
621 (Already_FullyProcessed==true
622 -> true
623 ; assertz(file_loaded(true,MainFile)),
624 trimcore_if_useful(Rest),
625 writeln_log_time(start_processing(NOW)),
626 start_probcli_timer(Timer),
627 catch((cli_process_loaded_file(NOW,MainFile)
628 -> stop_probcli_debug_timer(Timer,'% Finished processing file after')
629 ; print_error('Processing or loading file failed: '), print_error(MainFile),
630 start_repl_even_after_failure(true)
631 ),
632 user_interrupt_signal, % catch CTRL-C by user but give chance to enter REPL
633 start_repl_even_after_failure(throw(user_interrupt_signal))
634 ),
635 writeln_log_time(finished_processing(NOW))
636 )
637 ;
638 assertz(file_loaded(error,MainFile)),
639 (expected_error(load_main_file)
640 -> formatsilent('Loading specification ~w not successful (as expected)~n',[MainFile])
641 ; format_error_with_nl('Loading specification ~w failed',[MainFile])),
642 writeln_log_time(loading_failed(NOW,MainFile)),
643 error_occurred(load_main_file)
644 %start_repl_even_after_failure (true): TODO: fix issues with bmachine not precompiled and counter extension
645 ),
646 nls,
647 ifm_option_set(indent_main_b_file(PPFILE0),
648 indent_main_b_file(PPFILE0)),
649 ifm_option_set(pretty_print_prolog_file(PPFILE0),
650 pretty_print_prolog_file(PPFILE0))
651 ; % not file_exists
652 nl, assertz(file_loaded(error,MainFile)),
653 (number(MainFile0)
654 -> add_error(load_main_file,'Command-line argument is a number which is not associated with a command and does not exist as file: ',MainFile0)
655 ; atom_codes(MainFile0,[45|_]) % starts with a dash - : probably an illegal command-line option
656 -> add_error(load_main_file,'Specified option or file does not exist: ',MainFile0)
657 ; get_filename_extension(MainFile,Ext), \+ known_spec_file_extension(Ext,_)
658 -> (Ext = '' -> EMsg = 'Specified file does not exist and has no file extension:'
659 ; ajoin(['Specified file does not exist and has an unrecognised file extension ".',Ext,'" :'], EMsg)
660 ),
661 add_error(load_main_file,EMsg,MainFile)
662 ; add_error(load_main_file,'Specified file does not exist:',MainFile)
663 )
664 ),
665 check_all_expected_errors_occurred(NOW),
666 get_elapsed_walltime(ProcessFileTimer,WT1), add_to_profile_stats(total_file_processing_walltime,WT1),
667 accumulate_default_infos,
668 stop_xml_feature(process_file,FINFO),
669
670 debug_println(19,reset_expected_error_occurred),
671 reset_expected_error_occurred, % reset for next file
672 debug_println(19,resetting_errors),
673 reset_errors,
674 debug_println(19,update_time_stamp),
675 NOW1 is NOW+1,
676 update_time_stamp(NOW1),
677 debug_println(19,remaining_files_to_process(Rest)),
678 cli_load_files2(Rest,NOW1,NrOfFile).
679
680 start_repl_even_after_failure(GoalIfNoRepl) :-
681 (option(eval_repl([]))
682 -> format_with_colour_nl(user_output,[blue],'Starting REPL, but ignoring any other commands',[]),
683 % TODO: check if setup_constants_fails and then suggest e.g. :core @PROPERTIES command
684 start_repl_if_required % can be useful to debug properties, e.g, one can fix an error and reload
685 ; call(GoalIfNoRepl)
686 ).
687
688 print_file_info(F) :-
689 print('Specification_File('), print(F), print(')'),nl.
690
691 :- use_module(probsrc(tools),[statistics_memory_used/1]).
692 trimcore_if_useful(_) :- option(release_java_parser),!, prob_trimcore.
693 % if user wants to release java parser, this is an indication that the .prob files are big and it can be good to free memory
694 trimcore_if_useful([]) :- % try and reduce Prologs memory consumption, see also PROLOGKEEPSIZE parameter
695 % a lot of memory can be consumed loading .prob file and doing machine construction
696 !,
697 (option(X), memory_intensive_option(X)
698 -> debug_format(9,'Not trimming memory usage because of memory intensive option: ~w~n',[X])
699 ; statistics_memory_used(M), M< 300000000 % less than 300 MB used
700 -> debug_format(9,'Not trimming memory usage because of memory used is already low: ~w~n',[M])
701 ; prob_trimcore
702 ).
703 trimcore_if_useful(_) :- debug_println(9,'Not trimming memory usage as there are still files to process').
704
705 prob_trimcore :- (option_verbose ; option(release_java_parser)),!,prob_trimcore_verbose.
706 prob_trimcore :- prob_trimcore_silent.
707
708 prob_trimcore_verbose :-
709 print('Memory used before trimming: '),print_memory_used_wo_gc,flush_output, nl_time,
710 prob_trimcore_silent,
711 print('Memory used after trimming : '),print_memory_used_wo_gc,flush_output, nl_time.
712 prob_trimcore_silent :-
713 garbage_collect, % is important, otherwise trimming may achieve very little
714 trimcore.
715
716 memory_intensive_option(cli_mc(_)).
717 memory_intensive_option(ltl_formula_model_check(_,_)).
718 memory_intensive_option(ctl_formula_model_check(_,_)).
719 memory_intensive_option(pctl_formula_model_check(_,_)).
720 memory_intensive_option(refinement_check(_,_,_)).
721 memory_intensive_option(generate_all_traces_until(_,_,_)).
722
723 % ---------------------
724
725 % process all the commands for a loaded file:
726 cli_process_loaded_file(NOW,MainFile) :-
727 (real_error_occurred -> print_error('% *** Errors occurred while loading ! ***'),nl,nl ; true),
728 get_errors, reset_errors,
729 if_option_set(kodkod_performance(KPFile,Iterations),
730 compare_kodkod_performance1(KPFile,Iterations,NOW)),
731 if_option_set(kodkod_comparision(MaxResiduePreds),
732 test_kodkod_and_exit(MaxResiduePreds,NOW)),
733 % if_option_set(add_csp_guide(CspGuide), tcltk_add_csp_file(CspGuide)), %% moved to later to ensure B machine is precompiled; allows e.g. type_check_csp_and_b to run
734
735 if_option_set(csp_main(MAINPROC),
736 set_cspm_main_process(MAINPROC)),
737
738 if_option_set(zmq_master(Identifier), zmq_start_master(invariant,Identifier)),
739 %if_option_set(zmq_master(IP, Logfile), zmq_start_master(invariant,200,-1,5000,0,IP,Logfile)),
740
741 ifm_option_set(check_machine_file_sha(FileToCheck,ExpectedSha1Hash),
742 check_machine_file_sha(FileToCheck,ExpectedSha1Hash)),
743 ifm_option_set(clear_value_persistance_cache(MachineToClear),
744 delete_cache_files_for_machine(MachineToClear)),
745 ifm_option_set(ignore_value_persistance_cache_for(MachineToIgnore),
746 ignore_value_persistance_cache_for(MachineToIgnore)),
747 ifm_option_set(clear_value_persistance_cache,
748 delete_cache_files),
749
750 % STARTING ANIMATION/MODEL CHECKING
751 cli_start_animation(NOW),
752
753 if_option_set_loaded(cli_core_properties(MaxCoreSize),cli_core_properties,
754 cli_core_properties(MaxCoreSize)),
755
756 if_option_set_loaded(default_trace_check,default_trace_check,
757 cli_start_default_trace_check(MainFile)),
758 if_option_set_loaded(trace_check(TrStyle,TraceFile,ChkMode),trace_check,
759 cli_start_trace_check(TrStyle,TraceFile,ChkMode)),
760
761 cli_process_loaded_file_afer_start_animation(NOW).
762
763 cli_process_loaded_file_afer_start_animation(NOW) :-
764 ifm_option_set(cli_print_machine_info(IKind),
765 cli_print_machine_info(IKind)),
766 ifm_option_set(pretty_print_internal_rep(PPFILE1,MachName1,TYPES1,ASCII1),
767 pretty_print_internal_rep(PPFILE1,MachName1,TYPES1,ASCII1)),
768 ifm_option_set(pretty_print_internal_rep_to_B(PPFILE3),
769 b_write_eventb_machine_to_classicalb_to_file(PPFILE3)),
770
771 if_option_set_loaded(state_trace(TraceFile),state_trace,
772 cli_start_trace_state_check(TraceFile)),
773
774 if_option_set(evaldot(EvalDotF),
775 set_eval_dot_file(EvalDotF)),
776
777 (initialise_required
778 -> check_loaded(initialise),
779 cli_start_initialisation(NOW),
780 writeln_log_time(initialised(NOW))
781 ; true),
782 if_option_set(check_abstract_constants,
783 check_abstract_constants),
784
785 if_option_set(zmq_assertion(Identifier),
786 zmq_start_master(assertion,Identifier)),
787
788 if_option_set(cli_lint,cli_lint(_)),
789 ifm_option_set_loaded(cli_lint(LintCheck),cli_lint,cli_lint(LintCheck)),
790 if_option_set(cli_wd_check(Disch,TotPos),cli_wd_check(Disch,TotPos)),
791 if_option_set(cli_wd_inv_proof(UnchangedNr,ProvenNr,TotPOsNr),cli_wd_inv_proof(UnchangedNr,ProvenNr,TotPOsNr)),
792 if_option_set(cli_start_mc_with_tlc,cli_start_mc_with_tlc),
793 if_option_set(cli_start_sym_mc_with_lts(LType),cli_start_sym_mc_with_lts(LType)),
794
795 if_option_set(cli_symbolic_model_check(Algorithm),cli_symbolic_model_check(Algorithm)),
796
797 if_option_set_loaded(cli_check_properties,check_properties,
798 cli_check_properties(NOW)),
799 ifm_option_set_loaded(cli_check_assertions(ALL,ReqInfos),check_assertions,
800 cli_check_assertions(ALL,ReqInfos,NOW)),
801 if_option_set(set_goal(GOAL),
802 cli_set_goal(GOAL)),
803 if_option_set(set_searchscope(SCOPE),
804 cli_set_searchscope(SCOPE)),
805 ifm_option_set_loaded(cli_mc(Nr,MCOpts),model_check,
806 cli_start_model_check(Nr,NOW,MCOpts)),
807 ifm_option_set_loaded(cli_simulate(File,Reps,Steps,SimOpts),simulate,
808 cli_simulate(File,Reps,Steps,SimOpts)),
809 ifm_option_set_loaded(cli_random_animate(Steps,ErrOnDeadlock),animate,
810 cli_random_animate(NOW,Steps,ErrOnDeadlock)),
811 ifm_option_set_loaded(execute(ESteps,ErrOnDeadlock,From),execute,
812 cli_execute(ESteps,ErrOnDeadlock,From)),
813 ifm_option_set_loaded(animate_until_ltl(LTLFormula,ExOption,ExpResult,ExpSteps),execute,
814 animate_until_ltl(LTLFormula,ExOption,ExpResult,ExpSteps)),
815 if_option_set_loaded(pa_check,predicate_analysis,
816 test_predicate_analysis),
817
818 cbc_check(NOW),
819
820 ifm_option_set_loaded(logxml_write_ids(Prefix,IDScope),logxml_write_ids,
821 logxml_write_ids(Prefix,IDScope)),
822
823 if_options_set(generate_read_write_matrix_csv(RWCsvFile),
824 generate_read_write_matrix(RWCsvFile)),
825 if_options_set(feasibility_analysis_csv(TimeOut,EnablingCsvFile),
826 do_feasibility_analysis(TimeOut,EnablingCsvFile)),
827 ifm_option_set_loaded(mcm_tests(ADepth1,AMaxS,ATarget1,Output1),mcm_test_cases,
828 mcm_test_case_generation(ADepth1,AMaxS,ATarget1,Output1)),
829 ifm_option_set_loaded(all_deadlocking_paths(File),all_deadlocking_paths,
830 write_all_deadlocking_paths_to_xml(File)),
831 ifm_option_set_loaded(cbc_tests(ADepth2,ATarget2,Output2),cb_test_cases,
832 cbc_test_case_generation(ADepth2,ATarget2,Output2)),
833 ifm_option_set_loaded(test_description(TestDescFile),cb_test_cases,
834 test_generation_by_xml_description(TestDescFile)),
835 if_options_set(csp_in_situ_refinement_check(RP,RType,RQ),
836 cli_csp_in_situ_refinement_check(RP,RType,RQ,NOW)),
837 if_options_set(csp_checkAssertion(Proc,Model,AssertionType),
838 cli_checkAssertion(Proc,Model,AssertionType,NOW)),
839 if_options_set(check_csp_assertion(Assertion),
840 cli_check_csp_assertion(Assertion,NOW)),
841 if_options_set(refinement_check(RefFile,FailuresModel,RefNrNodes),
842 cli_start_refinement_check(RefFile,FailuresModel,RefNrNodes,NOW)),
843 if_options_set(ctl_formula_model_check(CFormula,CExpected),
844 (timeout_call(cli_ctl_model_check(CFormula,init,CExpected,_),NOW,ctl_model_check) -> true; true)),
845 if_options_set(pctl_formula_model_check(PFormula,PExpected),
846 (timeout_call(cli_pctl_model_check(PFormula,init,PExpected,_),NOW,ctl_model_check) -> true; true)),
847 % TO DO print ctl/ltl statistics
848 if_options_set(csp_get_assertions,cli_csp_get_assertions),
849 if_options_set(eval_csp_expression(CspExpr),cli_eval_csp_expression(CspExpr)),
850 if_options_set(csp_translate_to_file(PlFile),cli_csp_translate_to_file(PlFile)),
851 if_options_set(get_coverage_information(CovFileName),cli_get_coverage_information(CovFileName)), %% TODO: replace
852 if_options_set(vacuity_check,cli_vacuity_check),
853 if_option_set_loaded(check_goal,check_goal,cli_check_goal),
854 if_option_set_loaded(animate,animate,
855 (interactive_animate_machine -> true ; true)),
856 if_option_set(ltsmin, start_ltsmin_srv('/tmp/ltsmin.probz', NOW)),
857 if_option_set(ltsmin2(EndpointPath), start_ltsmin_srv(EndpointPath, NOW)),
858 if_option_set(ltsmin_ltl_output(Path), ltsmin_ltl_output(Path, NOW)),
859 if_options_set(run_benchmark(Kind,Option,Path), run_benchmark(Kind,Option,Path)),
860 evaluate_from_commandline,
861 if_option_set_loaded(ltl_assertions,check_ltl_assertions,
862 (timeout_call(ltl_check_assertions,NOW,check_ltl_assertions) -> true; true)),
863 ifm_option_set_loaded(ltl_formula_model_check(LFormula,LExpected),check_ltl_assertions,
864 (option(cli_start_sym_mc_with_lts(_))-> true % we request LTSMin, do not start prob model check
865 ; timeout_call(cli_ltl_model_check(LFormula,init,LExpected,_),NOW,ltl_formula_model_check)
866 -> true; true)),
867 ifm_option_set_loaded(ltl_file(LtlFilename),check_ltl_file,
868 (ltl_check_file(LtlFilename) -> true; true)),
869 ifm_option_set_loaded(visb_history(VJSONFile,VHTMLFile,Options),visb,
870 cli_visb_history(VJSONFile,VHTMLFile,Options)),
871 ifm_option_set_loaded(history(HistoryFilename),history,
872 cli_print_history(HistoryFilename)),
873 ifm_option_set_loaded(print_values(ValuesFilename),sptxt,
874 cli_print_values(ValuesFilename)),
875 ifm_option_set_loaded(print_all_values(ValuesDirname),print_all_values,
876 cli_print_all_values(ValuesDirname)),
877 ifm_option_set_loaded(generate_all_traces_until(LTL_Stop_AsAtom,FilePrefix),generate_all_traces_until,
878 cli_generate_all_traces_until(LTL_Stop_AsAtom,FilePrefix)),
879 if_options_set(save_state_for_refinement(SaveRefF),
880 tcltk_save_specification_state_for_refinement(SaveRefF)),
881 if_options_set(rule_report(File),
882 rule_validation:generate_report(File)),
883 if_options_set(proof_export(Style,File),
884 sequent_prover_exports:export_proof_for_current_state(Style,File)),
885 if_options_set(dot_command(DCommand1,DotFile1,DotEngine1),
886 dot_command(DCommand1,DotFile1,DotEngine1)),
887 if_options_set(dot_command_for_expr(DECommand,Expr,DotFile,Opts,DotEngine),
888 dot_command_for_expr(DECommand,Expr,DotFile,Opts,DotEngine)),
889 if_options_set(plantuml_command(PCommand1,UmlFile1),
890 plantuml_command(PCommand1,UmlFile1)),
891 if_options_set(plantuml_command_for_expr(PECommand,Expr,UmlFile,Opts),
892 plantuml_command_for_expr(PECommand,Expr,UmlFile,Opts)),
893 if_options_set(csv_table_command(TECommand,TableFormulas,TableOptions,TableCSVFile),
894 csv_table_command(TECommand,TableFormulas,TableOptions,TableCSVFile)),
895 if_options_set(evaluate_expression_over_history_to_csv_file(HistExpr,HistDotFile),
896 tcltk_interface:evaluate_expression_over_history_to_csv_file(HistExpr,HistDotFile)),
897 if_options_set(enabling_analysis_csv(EnablingCsvFile),
898 do_enabling_analysis_csv(EnablingCsvFile,NOW)),
899 if_options_set(process_latex_file(LatexF1,LatexF2),
900 process_latex_file(LatexF1,LatexF2)),
901 ifm_option_set(coverage(Nodes,Operations,ShowEnabledInfo),
902 cli_show_coverage(Nodes,Operations,ShowEnabledInfo,NOW)),
903 ifm_option_set(check_statespace_hash(ExpectedHash,Kind),
904 cli_check_statespace_hash(ExpectedHash,Kind)),
905 ifm_option_set(check_op_cache(ExpectedC),
906 cli_check_op_cache(ExpectedC)),
907 ifm_option_set(coverage(ShowEnabledInfo),
908 cli_show_coverage(ShowEnabledInfo,NOW)),
909 if_option_set(save_state_space(StateFile),
910 save_state_space(StateFile)),
911 ifm_option_set(cli_print_statistics(SPARA),
912 cli_print_statistics(SPARA)),
913 if_option_set(show_cache(SCVM),
914 show_cache(SCVM)),
915 ifm_option_set(cli_cache_stats_check(CStats),cli_cache_stats_check(CStats)),
916 if_option_set(check_complete, check_complete),
917 if_option_set(check_complete_operation_coverage, check_complete_operation_coverage),
918 if_option_set(check_scc_for_ltl_formula(LtlFormulaSCC,SCC),cli_check_scc_for_ltl_formula(LtlFormulaSCC,SCC)).
919
920 % what needs to be done for files like .po files, where all processing is already done:
921 cli_process_options_for_alrady_fully_processed_file(_MainFile) :-
922 ifm_option_set(cli_print_statistics(SPARA),
923 cli_print_statistics(SPARA)).
924
925 show_cache(default) :- !,
926 (option_verbose -> show_cache(normal) ; show_cache(verbose)).
927 show_cache(Verbose) :- % -show_cache_verbose
928 show_cache_file_contents(Verbose).
929
930 cli_cache_stats_check(Expected) :-
931 get_value_persistance_stats(Stats),
932 check_required_infos(Expected,Stats,check_cache_stats).
933
934 % new profiler
935 %:- use_module('../extensions/profiler/profiler.pl').
936 %cli_print_statistics :- pen,nl,garbage_collect,statistics,nl,state_space:state_space_initialise_with_stats.
937
938 :- use_module(runtime_profiler,[print_runtime_profile/0]).
939 :- use_module(source_profiler,[print_source_profile/0]).
940 :- use_module(memoization,[print_memo_profile/0]).
941 :- use_module(state_packing,[print_state_packing_profile/0]).
942
943 % old profiler
944 :- use_module(covsrc(hit_profiler),[print_hit_profile_statistics/0]).
945 :- use_module(extrasrc(b_operation_cache),[print_op_cache_profile/0, reset_b_operation_cache_with_statistics/0]).
946 :- use_module(memoization,[reset_memo_with_statistics/0]).
947 :- use_module(disproversrc(disprover),[print_prover_result_stats/0]).
948 :- use_module(probsrc(tools),[print_mb/1]).
949 cli_print_statistics(hshow) :- !,
950 print_machine_topological_order.
951 cli_print_statistics(memory) :- !,
952 print_memory_statistics(user_output).
953 cli_print_statistics(value_persistance_stats) :- !,
954 print_value_persistance_stats.
955 cli_print_statistics(sicstus_profile) :- !,
956 format('SICStus Prolog PROFILE STATISTICS~n',[]),
957 sicstus_profile_statistics.
958 cli_print_statistics(disprover_profile) :- !,
959 print_prover_result_stats.
960 cli_print_statistics(prob_profile) :- !,
961 statistics(walltime,[WT,_]),
962 statistics(runtime,[RT,_]),
963 format('--------------------------~nPROB PROFILING INFORMATION after ~w ms walltime (~w ms runtime) ',[WT,RT]),
964 statistics_memory_used(M), print_mb(M),nl,
965 print_source_profile,
966 print_runtime_profile,
967 print_memo_profile,
968 print_state_packing_profile,
969 print_external_function_instantiation_profile,
970 (get_preference(operation_reuse_setting,false) -> true ; print_op_cache_profile). % relevant for test 2152 under SWI
971 cli_print_statistics(hit_profile) :- !,
972 (print_hit_profile_statistics -> true ; true). % mainly used by external functions
973 cli_print_statistics(op_cache_profile) :- !,
974 get_preference(try_operation_reuse,OR),
975 format('PROB OPERATION_REUSE (value:~w) STATISTICS~n',[OR]),
976 print_op_cache_profile.
977 cli_print_statistics(simb_profile) :- !,
978 print_simb_profile.
979 cli_print_statistics(full) :- format('PROB FULL STATISTICS~n',[]),
980 sicstus_profile_statistics,
981 garbage_collect,
982 statistics,
983 nl,
984 print_op_cache_profile,
985 print_prover_result_stats,
986 state_space:state_space_initialise_with_stats,
987 reset_memo_with_statistics,
988 reset_b_operation_cache_with_statistics.
989
990 print_memory_statistics(Stream) :-
991 garbage_collect,
992 write(Stream,'ProB memory used: '),
993 print_memory_used_wo_gc(Stream), nl(Stream), flush_output(Stream).
994
995 sicstus_profile_statistics :-
996 %(hit_profiler:print_hit_profile_statistics -> true ; true), % only used by external functions
997 (option(profiling_on)
998 -> catch(print_profile,
999 error(existence_error(_,_),_),
1000 print_red('SICStus Prolog Profiler can only be used when running from source'))
1001 ; true).
1002
1003
1004 :- use_module(state_space,[not_all_transitions_added/1, not_invariant_checked/1,
1005 not_interesting/1, get_operation_name_coverage_infos/4]).
1006 check_complete :-
1007 (tcltk_find_max_reached_node(Node1) ->
1008 add_error(check_complete,'Maximum number of transitions reached for at least one state: ',Node1) ; true),
1009 (not_all_transitions_added(Node2) ->
1010 add_error(check_complete,'At least one state was not examined: ',Node2) ; true),
1011 (not_invariant_checked(Node3) ->
1012 add_error(check_complete,'The invariant was not checked for at least one state: ',Node3) ; true),
1013 (not_interesting(Node4) ->
1014 add_message(check_complete,'At least one state was ignored (not satisfying the SCOPE predicate): ',Node4) ; true).
1015
1016 check_complete_operation_coverage :-
1017 (state_space: operation_name_not_yet_covered(OpName) ->
1018 add_error(check_complete_operation_coverage,'At least one operation is not covered: ', OpName)
1019 ; true).
1020
1021 show_operation_coverage_summary(NOW) :-
1022 get_operation_name_coverage_infos(PossibleNr,FeasibleNr,UncovNr,UncoveredList),
1023 writeln_log(uncovered_info(NOW,PossibleNr,UncoveredList)),
1024 (UncovNr=0 -> format(' All ~w possible operations have been covered',[PossibleNr]),nl
1025 ; (FeasibleNr=PossibleNr
1026 -> format(' The following ~w operations (out of ~w) were not covered:~n ~w~n',
1027 [UncovNr, PossibleNr,UncoveredList])
1028 ; INr is PossibleNr-FeasibleNr,
1029 format(' The following ~w operations (out of ~w with ~w infeasible) were not covered:~n ~w~n',
1030 [UncovNr, PossibleNr, INr,UncoveredList])
1031 )).
1032 show_initialisation_summary(NOW) :-
1033 findall(ID,state_space:is_concrete_constants_state_id(ID),L),
1034 length(L,Nr), N1 is Nr+1, % for root
1035 writeln_log(uninitialised_states(NOW,N1)),
1036 format(' Uninitialised states: ~w (root and constants only)~n',[N1]).
1037
1038 % ---------------------
1039
1040 animation_mode_does_not_support_animation(File) :-
1041 loaded_main_file(smt2,File).
1042 cli_start_animation(NOW) :-
1043 file_loaded(true,LoadedFile),
1044 \+ animation_mode_does_not_support_animation(LoadedFile),
1045 !,
1046 debug_println(20,'% Starting Animation'),
1047 writeln_log_time(start_animation(NOW)),
1048 start_probcli_timer(Timer1),
1049 start_animation_without_computing,
1050 stop_probcli_debug_timer(Timer1,'% Finished starting animation after'),
1051 if_option_set(add_csp_guide(CspGuide), tcltk_add_csp_file(CspGuide)),
1052
1053 xml_log_machine_statistics,
1054 getAllOperations(Ops),
1055 debug_print(20,'Operations: '), debug_println(20,Ops),
1056
1057 (we_need_only_static_assertions(ALL)
1058 -> debug_println(20,'% Projecting on static ASSERTIONS'),
1059 b_interpreter:set_projection_on_static_assertions(ALL) ; true),
1060
1061 (option(load_state(File))
1062 -> debug_println(20,'% Loading stored state from file'),
1063 state_space:tcltk_load_state(File)
1064 ; computeOperations_for_root_required ->
1065 debug_println(20,'% Searching for valid initial states'),
1066 start_probcli_timer(Timer2),
1067 cli_computeOperations(EO),
1068 stop_probcli_debug_timer(Timer2,'% Finished searching for valid initial states after'),
1069 debug_println(10,EO)
1070 ; debug_println(20,'% No initialisation required')
1071 ).
1072 cli_start_animation(_NOW).
1073
1074 start_animation_without_computing :-
1075 update_preferences_from_spec(ListOfPrefs),
1076 (ListOfPrefs=[] -> true ; write_prolog_term_as_xml_to_log(b_machine_preferences(ListOfPrefs))),
1077 set_prefs, % override SET_PREF in DEFINITIONS with values from command-line;
1078 start_animation,
1079 ifm_option_set(add_additional_property(PROP),
1080 cli_add_additional_property(PROP)),
1081 get_errors.
1082
1083 animate_until_ltl(LTLFormula,ExOption,ExpectedResult,ExpectedNrSteps) :-
1084 tcltk_animate_until(LTLFormula,ExOption,StepsExecuted,Result),
1085 formatsilent('Found trace of length ~w for LTL formula. Result: ~w ~n',[StepsExecuted,Result]),
1086 print_history_as_counter_example(false), % TODO: only print from current id before command
1087 (ExpectedResult=Result -> true % Result can be ltl_found, maximum_nr_of_steps_reached, deadlock
1088 ; add_error(animate_until_ltl,'Unexpected animation result: ',Result),
1089 error_occurred(animate_until_ltl)
1090 ),
1091 (ExpectedNrSteps=StepsExecuted -> true
1092 ; add_error(animate_until_ltl,'Unexpected number of animation steps: ',StepsExecuted),
1093 error_occurred(animate_until_ltl)
1094 ).
1095
1096 % ---------------------
1097
1098 % an execution engine with minimal overhead: states are not stored in visited_expression database, only first enabled operation is taken
1099
1100 cli_execute(Steps,ErrorOnDeadlock,FromWhere) :-
1101 temporary_set_preference(operation_reuse_setting,false,ChangeOccured),
1102 (ChangeOccured=true % operation reuse not compatible with cut used below after solution found
1103 -> add_debug_message(execute_model,'Disabling OPERATION_REUSE preference for -execute ',Steps) ; true),
1104 call_cleanup(cli_execute2(Steps,ErrorOnDeadlock,FromWhere),
1105 reset_temporary_preference(operation_reuse_setting,ChangeOccured)).
1106 cli_execute2(Steps,ErrorOnDeadlock,FromWhere) :-
1107 FromWhere=from_all_initial_states,!,
1108 % try out all initial states and from each of those perform deterministic execution
1109 start_ms_timer(Start),
1110 format('Running execute from all initial states~n',[]),
1111 reset_counter(cli_execute_inits),
1112 findall(Result,
1113 (cli_trans(root,Action,CurState,0,'$NO_OPERATION'), %print(Action),nl,
1114 (\+ functor(Action,'$setup_constants',_)
1115 -> inc_counter(cli_execute_inits,Nr),
1116 format('~nExecuting model from initial state ~w~n',[Nr]),
1117 (option(animate_stats) -> print_state_silent(CurState) ; true),
1118 (cli_execute_from(CurState,Steps,ErrorOnDeadlock,1,Result) -> true)
1119 ; format('~nInitialising state~n',[]), % we need to execute initialise_machine
1120 cli_trans(CurState,_ActionName,NewState,0,'$NO_OPERATION'),
1121 inc_counter(cli_execute_inits,Nr),
1122 format('~nExecuting model from initial state ~w with constants~n',[Nr]),
1123 (option(animate_stats) -> print_state_silent(NewState) ; true),
1124 (cli_execute_from(NewState,Steps,ErrorOnDeadlock,2,Result) -> true)
1125 )), Results),
1126 get_counter(cli_execute_inits,Nr),
1127 format('---------~nTotal runtime for all ~w executions:',[Nr]),nl,
1128 stop_ms_timer(Start),
1129 count_occurences(Results,Occs), format('Results: ~w~n',[Occs]).
1130 cli_execute2(Steps,ErrorOnDeadlock,current_state(Repetitions)) :-
1131 current_expression(ID,CurState),
1132 start_xml_feature(execute,max_steps,Steps,FINFO),
1133 start_ms_timer(Start),
1134 (between(1,Repetitions,RepNr),
1135 % with -strict option we will stop after first error found
1136 % for repetitions you should probably set RANDOMISE_OPERATION_ORDER and RANDOMISE_ENUMERATION_ORDER to TRUE
1137 debug_format(19,'Starting execute (~w/~w) from state ~w with maximum number of steps ~w~n',[RepNr,Repetitions,ID,Steps]),
1138 (cli_execute_from(CurState,Steps,ErrorOnDeadlock,1,_Result) -> fail ; fail)
1139 ; Repetitions>1 -> stop_ms_timer_with_msg(Start,'-execute-repeat')
1140 ; true),
1141 stop_xml_feature(execute,FINFO).
1142
1143 :- use_module(bmachine,[b_top_level_operation/1]).
1144 allow_filter_unused_constants :-
1145 b_or_z_mode,
1146 b_top_level_operation(_), % we can filter out unused constants, unless there are no operations in which case the user probably wants to see the constant values
1147 \+ options_can_eval_any_cst,
1148 \+ option(cache_storage(_,_)). % we do not know what constants other machines using the cache may use
1149
1150 options_can_eval_any_cst :- option(eval_repl(_)).
1151 options_can_eval_any_cst :- option(eval_string_or_file(_,_,_,_,_)).
1152 options_can_eval_any_cst :- option(dot_command(_,_,_)).
1153 options_can_eval_any_cst :- option(dot_command_for_expr(_,_,_,_,_)).
1154 options_can_eval_any_cst :- option(process_latex_file(_,_)).
1155 options_can_eval_any_cst :- option(logxml_write_ids(all,_)). % the user writes out constants (not just variables) to file: also do not filter
1156
1157 :- dynamic execute_timeout_occurred/0.
1158
1159 cli_execute_from(CurState,Steps,ErrorOnDeadlock,FirstStepNr,Result) :-
1160 clear_constant_pre_hash_cache, % constants may differ from previous run, e.g., for -execute_all_inits
1161 retractall(max_walltime(_,_,_)),
1162 retractall(execute_timeout_occurred),
1163 start_ms_timer(Start),
1164 (allow_filter_unused_constants -> temporary_set_preference(filter_unused_constants,true,CHNG) ; true),
1165 cli_execute_aux(FirstStepNr,Steps,CurState,_MEMO,ErrorOnDeadlock,'$NO_OPERATION',Result),
1166 (allow_filter_unused_constants -> reset_temporary_preference(filter_unused_constants,CHNG) ; true),
1167 (option_silent_set -> true ; stop_ms_timer_with_msg(Start,'-execute')),
1168 print_max_walltime.
1169
1170 :- use_module(tools_strings,[ajoin/2, ajoin_with_sep/3]).
1171 :- use_module(external_functions,[reset_side_effect_occurred/0, side_effect_occurred/1]).
1172 cli_execute_aux(Nr,Steps,CurState,_,_ErrorOnDeadlock,_LastActionName,Result) :- Nr>Steps,!,
1173 formatsilent('Stopping execution after ~w steps~n',[Steps]), Result = stopped,
1174 print_state_silent(CurState),
1175 cli_execute_add_virtual_transition(Steps,CurState,Result).
1176 cli_execute_aux(Nr,Steps,CurState0,MEMO,ErrorOnDeadlock,LastActionName,Result) :-
1177 (Nr mod 5000 =:= 0, \+option(animate_stats), \+option_silent_set
1178 -> (var(LastActionName) -> format('Step ~w~n',[Nr])
1179 ; format('Step ~w (after ~w)~n',[Nr,LastActionName])),
1180 (option_verbose -> print_state_silent(CurState0) ; true),
1181 %copy_term(CurState0,CurState), tools_printing:print_term_summary((CurState0)),nl,
1182 !,
1183 garbage_collect,
1184 !,
1185 print('Memory used: '),print_memory_used_wo_gc,flush_output,nl %nl_time
1186 ; true),
1187 prepare_state_for_specfile_trans(CurState0,unknown,MEMO,CurState), % ensure we memoize expanded constants in MEMO
1188 % avoid re-expanding constants in every state !
1189 % relevant e.g. for probcli -execute 20001 DataValidationTestSmallStep.mch -init
1190 (cli_invariant_ko(CurState,LastActionName,InvStatus,CliErr) -> % also recognises no_inv command
1191 N1 is Nr-1,
1192 ajoin(['INVARIANT ',InvStatus,' after ',N1,' steps (after ',LastActionName,').'],ErrMsg),
1193 format('~w~n',[ErrMsg]),!,
1194 print_state_silent(CurState),
1195 error_occurred_with_msg(CliErr,ErrMsg),
1196 Result=CliErr,
1197 cli_execute_add_virtual_transition(N1,CurState,Result,NewID),
1198 %(option_verbose -> b_interpreter:analyse_invariant_for_state(NewID) ; true)
1199 b_interpreter:analyse_invariant_for_state(NewID)
1200 ; cli_assertions_ko(CurState,LastActionName,AssRes) -> % also recognises no_inv command
1201 N1 is Nr-1,
1202 format('ASSERTIONS ~w after ~w steps (after ~w).~n',[AssRes,N1,LastActionName]),!,
1203 print_state_silent(CurState),
1204 error_occurred(assertion_violation), Result=assertion_violation,
1205 cli_execute_add_virtual_transition(N1,CurState,Result)
1206 ; cli_goal_found(CurState) -> % also recognizes no_goal command
1207 N1 is Nr-1,
1208 format('GOAL FOUND after ~w steps (after ~w).~n',[N1,LastActionName]),!,
1209 print_state_silent(CurState), Result=goal_found,
1210 cli_execute_add_virtual_transition(N1,CurState,Result)
1211 ; reset_side_effect_occurred,
1212 cli_trans(CurState,ActionName,NewState,Nr,LastActionName), % Compute new transition
1213 !,
1214 N1 is Nr+1,
1215 (NewState=CurState0, % could be expensive for large states; states are expanded ! % TO DO: look only at written variables ?!
1216 \+ side_effect_occurred(file)
1217 -> formatsilent('Infinite loop reached after ~w steps (looping on ~w).~n',[N1,ActionName]),
1218 Result=loop,
1219 print_state_silent(CurState),
1220 cli_execute_add_virtual_transition(N1,CurState,Result)
1221 ; cli_execute_aux(N1,Steps,NewState,MEMO,ErrorOnDeadlock,ActionName,Result))
1222 ).
1223 cli_execute_aux(Nr,_Steps,CurState,_,_ErrorOnDeadlock,LastActionName,Result) :- execute_timeout_occurred,!,
1224 N1 is Nr-1,
1225 formatsilent('Timeout occurred after ~w steps (after ~w).~n',[N1,LastActionName]),
1226 Result=time_out,
1227 print_state_silent(CurState),
1228 cli_execute_add_virtual_transition(N1,CurState,Result).
1229 cli_execute_aux(Nr,_Steps,CurState,_,ErrorOnDeadlock,LastActionName,Result) :- N1 is Nr-1,
1230 formatsilent('Deadlock reached after ~w steps (after ~w).~n',[N1,LastActionName]),
1231 Result=deadlock,
1232 (ErrorOnDeadlock=true,\+ option(no_deadlocks) -> error_occurred(deadlock) ; true),
1233 print_state_silent(CurState),
1234 cli_execute_add_virtual_transition(N1,CurState,Result).
1235
1236 check_nr_of_steps(Steps) :- option(execute_expect_steps(ExpSteps)),
1237 (Steps = ExpSteps -> formatsilent('The expected number of steps were executed: ~w~n',[Steps]),fail
1238 ; true),
1239 !,
1240 ajoin(['Unexpected number of steps ',Steps,', expected:'],Msg),
1241 add_error(cli_execute,Msg,ExpSteps).
1242 check_nr_of_steps(_).
1243
1244 cli_execute_add_virtual_transition(Steps,CurState,Result) :-
1245 cli_execute_add_virtual_transition(Steps,CurState,Result,_).
1246 cli_execute_add_virtual_transition(Steps,CurState,Result,ToID) :-
1247 current_state_id(CurID),
1248 write_xml_element_to_log(executed,[steps/Steps,result/Result]),
1249 (Steps=0 -> true
1250 ; some_command_requires_state_space % check whether storing is actually useful for any outstanding command
1251 -> (CurID=root
1252 -> tcltk_interface:tcltk_add_cbc_state(CurState,'$execute'(Steps)) % generate separate constants state
1253 ; tcltk_interface:tcltk_add_new_transition(CurID,'$execute'(Steps),ToID,CurState,[]),
1254 tcltk_goto_state('$execute'(Steps),ToID)
1255 ),
1256 debug_format(19,'Added transition ~w -> ~w to state space for ~w execution steps~n',[CurID,ToID,Steps])
1257 ; debug_format(19,'Not adding transition for -execute ~w steps; not required by other commands~n',[Steps])
1258 ),
1259 check_nr_of_steps(Steps).
1260
1261 some_command_requires_state_space :-
1262 option(X),
1263 \+ does_not_require_state_space(X),
1264 !.
1265 does_not_require_state_space(execute_expect_steps(_)).
1266 does_not_require_state_space(execute(_,_,_)).
1267 does_not_require_state_space(animate_stats).
1268 does_not_require_state_space(execute_monitoring).
1269 does_not_require_state_space(set_pref(_,_)).
1270 does_not_require_state_space(set_preference_group(_,_)).
1271 does_not_require_state_space(timeout(_)).
1272 does_not_require_state_space(verbose(_)).
1273 does_not_require_state_space(verbose_off).
1274 does_not_require_state_space(silent).
1275 does_not_require_state_space(force_no_silent).
1276 does_not_require_state_space(strict_raise_error).
1277 does_not_require_state_space(release_java_parser).
1278 does_not_require_state_space(fast_read_prob).
1279 does_not_require_state_space(file_info).
1280 does_not_require_state_space(print_version(_)).
1281 does_not_require_state_space(check_java_version).
1282 does_not_require_state_space(pretty_print_internal_rep(_,_,_,_)).
1283 does_not_require_state_space(expect_error(_)).
1284 does_not_require_state_space(optional_error(_)).
1285 does_not_require_state_space(no_deadlocks).
1286 does_not_require_state_space(no_invariant_violations).
1287 does_not_require_state_space(no_goal).
1288 does_not_require_state_space(no_assertion_violations).
1289 does_not_require_state_space(no_state_errors).
1290 does_not_require_state_space(no_counter_examples).
1291 does_not_require_state_space(no_color).
1292 % TODO: register more commands that do not require the state space
1293
1294 :- dynamic max_walltime/3.
1295 print_max_walltime :- (max_walltime(Action,Nr,WT),option_verbose
1296 -> format('% Maximum walltime ~w ms at step ~w for ~w.~n',[WT,Nr,Action]) ; true).
1297
1298 % will be used to compute a single successor
1299 % b_operation_cannot_modify_state
1300 cli_trans(CurState,ActionName,NewState,Nr,LastActionName) :-
1301 option(animate_stats),!, % provide statistics about the animation
1302 start_probcli_timer(Timer),
1303 cli_trans_aux(CurState,ActionName,Act,NewState,Nr,LastActionName),
1304 (option_verbose -> translate:translate_event(Act,TStr)
1305 ; translate:translate_event_with_limit(Act,100,TStr)),
1306 format('~w~5|: ~w~n',[Nr,TStr]),
1307 format(' ~5|',[]),stop_probcli_timer(Timer,' '),
1308 (option_verbose -> format(' ~5|',[]),print_memory_used_wo_gc,nl ; true),
1309 flush_output,
1310 get_probcli_elapsed_walltime(Timer,WallTime),
1311 get_probcli_elapsed_runtime(Timer,RunTime),
1312 accumulate_infos(animate_stats,[step-1,step_nr-Nr,runtime-RunTime,walltime-WallTime]),
1313 (max_walltime(_,_,MWT), MWT >= WallTime -> true
1314 ; retractall(max_walltime(_,_,_)),
1315 assertz(max_walltime(ActionName,Nr,WallTime))).
1316 cli_trans(CurState,ActionName,NewState,Nr,LastActionName) :-
1317 cli_trans_aux(CurState,ActionName,_,NewState,Nr,LastActionName).
1318
1319 cli_trans_aux(CurState,ActionName,Act,NewState,Nr,LastActionName) :-
1320 option(timeout(TO)),!,
1321 safe_time_out(cli_trans_aux2(CurState,ActionName,Act,NewState,LastActionName),TO,Res),
1322 (Res=time_out -> format_error_with_nl('! Timeout occurred while performing step ~w of execute: ~w ms',[Nr,TO]),
1323 % TO DO: try and obtain operation name in which time-out occured
1324 error_occurred(time_out,execute),
1325 assertz(execute_timeout_occurred),
1326 fail
1327 ; true).
1328 cli_trans_aux(CurState,ActionName,Act,NewState,_Nr,LastActionName) :-
1329 cli_trans_aux2(CurState,ActionName,Act,NewState,LastActionName).
1330
1331 cli_trans_aux2(CurState,ActionName,Act,NewState,LastActionName) :-
1332 catch_enumeration_warning_exceptions(
1333 (throw_enumeration_warnings_in_current_scope,
1334 cli_execute_trans(CurState,ActionName,Act,NewState,LastActionName), % no time-out !
1335 (error_occurred_in_error_scope -> ErrorEvent=true ; ErrorEvent=false)
1336 ),
1337 (error_occurred(virtual_time_out_execute),
1338 ActionName = '*** VIRTUAL_TIME_OUT ***', Act=ActionName,
1339 CurState=NewState) % this forces loop detection above; not very elegant way of signalling
1340 ),
1341 (ErrorEvent==true,option(strict_raise_error)
1342 -> print('*** ERROR OCCURED DURING EXECUTE ***'),nl, error_occurred(execute),fail
1343 ; true).
1344
1345 :- use_module(runtime_profiler,[profile_single_call/3]).
1346 :- use_module(specfile,[get_specification_description/2]).
1347 cli_execute_trans(CurState,ActionName,Act,NewState,LastActionName) :-
1348 statistics(runtime,[StartExecuteForState,_]),
1349 get_possible_next_operation_for_execute(CurState,LastActionName,ActionName),
1350 start_check_disabled(ActionName,StartActionTime),
1351 catch(
1352 profile_single_call(ActionName,
1353 unknown, % state Unknown
1354 specfile_trans_with_check(CurState,ActionName,Act,NewState,Residue) % no time-out !
1355 ),
1356 EXC,
1357 (translate_exception(EXC,EMSG),
1358 (nonvar(ActionName)
1359 -> get_specification_description(operation,OP),
1360 format_with_colour_nl(user_error,[red,bold],'~n*** ~w while executing ~w "~w"~n',[EMSG,OP,ActionName])
1361 ; get_specification_description(operations,OP),
1362 format_with_colour_nl(user_error,[red,bold],'~n*** ~w while computing ~w~n',[EMSG,OP])
1363 ),
1364 perform_feedback_options_after_exception,
1365 throw(EXC))),
1366 (Residue=[]
1367 -> check_trans_time(StartExecuteForState,StartActionTime,ActionName)
1368 ; error_occurred(cli_execute_residue(ActionName,Residue,Act))).
1369
1370 :- use_module(probsrc(value_persistance),[cache_is_activated/0]).
1371 :- use_module(probsrc(static_enabling_analysis),[static_cannot_enable/2,
1372 static_disables_itself/1, static_disabled_after/2]).
1373 % compute all possible next operations to try out in -execute, based on LastActionName
1374 % the predicate makes use of the fact that operations are tried in order
1375 get_possible_next_operation_for_execute(CurState,LastActionName,ActionName) :-
1376 get_preference(randomise_operation_order,false),
1377 get_preference(use_po,true), % PROOF_INFO: should we use a proper preference for use_po_for_execute ?
1378 b_or_z_mode,
1379 b_top_level_operation(LastActionName),
1380 % prevent trying ActionName which we know is infeasible according to previous LastActionName
1381 % we rely on the fact that execute tries the operations in order
1382 findall(AN,specfile_possible_trans_name_for_successors(CurState,AN),ANS),
1383 !,
1384 member_with_last(ActionName,ANS,LastActionName,FoundLast),
1385 (var(FoundLast)
1386 -> % ActionName occurs before LastActionName, this means
1387 % we did try this ActionName at the last execution step and it was not possible
1388 % format('** Checking operation ~w against ~w~n',[ActionName,LastActionName]),debug:nl_time,
1389 %Note: we could use result of cbc enabling analysis if it was performed
1390 (static_cannot_enable(LastActionName,ActionName)
1391 -> debug_format(9,'** Operation ~w cannot be enabled by ~w~n',[ActionName,LastActionName]),
1392 %print('- '),
1393 fail
1394 ; true
1395 )
1396 ; ActionName=LastActionName, static_disables_itself(ActionName)
1397 -> debug_format(9,'** Operation ~w cannot be enabled after itself~n',[ActionName]),
1398 fail
1399 ; cache_is_activated, % TODO: check if this more general case is worth it in general
1400 % for the cache we need to hash the operation's input values; which could be expensive
1401 static_disabled_after(LastActionName,ActionName)
1402 -> debug_format(9,'** Operation ~w cannot be enabled after ~w~n',[ActionName,LastActionName]),
1403 fail
1404 ; true % we did not try this ActionName at the last execution step
1405 ).
1406 get_possible_next_operation_for_execute(CurState,_LastActionName,ActionName) :-
1407 specfile_possible_trans_name_for_successors(CurState,ActionName).
1408
1409 % like member but instantiate FoundLast when we pass the element Last
1410 member_with_last(X,[H|T],Last,FoundLast) :-
1411 (H=Last -> !,FoundLast=true, member(X,[H|T]) ; X=H).
1412 member_with_last(X,[_|T],Last,FoundLast) :- member_with_last(X,T,Last,FoundLast).
1413
1414 :- use_module(probsrc(value_persistance),[start_cache_execute_modus/1,stop_cache_execute_modus/0,
1415 clear_constant_pre_hash_cache/0,
1416 add_new_transition_to_cache_from_expanded_state/4]).
1417 % also checks whether a setup_constants_inconsistent error should be raised:
1418 specfile_trans_with_check(CurState,ActionName,Act,NewState,Residue) :-
1419 start_cache_execute_modus(CacheInfo),
1420 if(specfile_trans_or_partial_trans(CurState,ActionName,Act,NewState,_TransInfo,Residue,Partial), % no time-out !
1421 (check_partial_trans(Partial,ActionName),
1422 (Partial=true -> true ; add_new_transition_to_cache_from_expanded_state(CurState,Act,NewState,CacheInfo)),
1423 stop_cache_execute_modus
1424 ),
1425 (stop_cache_execute_modus,
1426 check_deadlock_fail(ActionName) % add_deadlock_to_cache_from_expanded_state(CurState,ActionName)
1427 )
1428 ).
1429
1430 % check whether we should raise errors on deadlock in -execute:
1431 check_deadlock_fail('$setup_constants') :- !, error_occurred(setup_constants_inconsistent),fail.
1432
1433 % check whether we should raise errors due to partial transitions in -execute:
1434 check_partial_trans(true,'$setup_constants') :- !, error_occurred(setup_constants_inconsistent).
1435 check_partial_trans(true,ActionName) :- !, format('Unknown partial transition: ~w~n',[ActionName]),
1436 error_occurred(setup_constants_inconsistent).
1437 check_partial_trans(_,_).
1438
1439 % check if we did not spend too much time on disabled operations and print warning if we do
1440 check_trans_time(StartExecuteForState,StartActionTime,ActionName) :-
1441 option(execute_monitoring),
1442 statistics(runtime,[CurrentTime,_]),
1443 Delta1 is StartActionTime-StartExecuteForState,
1444 Delta2 is CurrentTime-StartActionTime,
1445 Delta1 > 100, Delta1 > Delta2,
1446 !,
1447 format_with_colour(user_output,[blue],'~n ~5|: WARNING from -execute_monitor: ~w ms for disabled operations and ~w ms for operation ~w itself~n',[Delta1,Delta2,ActionName]).
1448 check_trans_time(_,_,_).
1449
1450 % check if we did not spend too much time on a single disabled operations and print warning if we do
1451 start_check_disabled(ActionName,StartActionTime) :- option(execute_monitoring),!,
1452 statistics(runtime,[StartActionTime,_]),
1453 (true
1454 ; statistics(runtime,[EndActionTime,_]),
1455 Delta is EndActionTime - StartActionTime,
1456 Delta > 50,
1457 format_with_colour(user_output,[blue],'~n ~5|: WARNING from -execute_monitor: ~w ms for disabled operation ~w~n',[Delta,ActionName]),
1458 fail
1459 ).
1460 start_check_disabled(_,0).
1461
1462 translate_exception(user_interrupt_signal,'User-Interrupt (CTRL-C)').
1463 translate_exception(enumeration_warning(_,_,_,_,_),'Enumeration Warning').
1464 translate_exception(E,E).
1465
1466 :- use_module(bmachine,[b_machine_has_constants/0]).
1467 print_state_silent(_) :- option_silent_set,!.
1468 print_state_silent(CurState) :- \+ b_or_z_mode, !, translate:print_state(CurState), nl.
1469 print_state_silent(CurState) :- (option_verbose;\+ b_machine_has_constants),!,
1470 translate:print_bstate_limited(CurState,1000,-1),nl.
1471 print_state_silent(CurState) :- remove_constants(CurState,VarState),
1472 % only print variables
1473 format('VARIABLES (use -v to see constants or -silent to suppress output):~n',[]),
1474 translate:print_bstate_limited(VarState,1000,-1),nl.
1475
1476 :- use_module(bmachine,[b_is_constant/1]).
1477 is_constant_binding(bind(C,_)) :- b_is_constant(C).
1478 remove_constants(const_and_vars(_,Vars),Res) :- !,Res=Vars.
1479 remove_constants([H|T],Res) :- !,exclude(prob_cli:is_constant_binding,[H|T],Res).
1480 remove_constants(root,Res) :- !,Res=[].
1481 remove_constants(concrete_constants(_),Res) :- !, Res=[].
1482 remove_constants(X,X).
1483
1484 % write vars to xml log file if they start with a given prefix
1485 logxml_write_ids(variables,Prefix) :- !,
1486 current_expression(_,CurState),
1487 remove_constants(CurState,VarState),
1488 % TO DO: store also final state in xml_log
1489 write_bstate_to_log(VarState,Prefix).
1490 logxml_write_ids(_,Prefix) :- !,
1491 current_expression(_,CurState),
1492 expand_const_and_vars_to_full_store(CurState,EState),
1493 write_bstate_to_log(EState,Prefix).
1494
1495 :- use_module(bmachine,[b_get_invariant_from_machine/1, b_specialized_invariant_for_op/2, b_machine_has_constants/0]).
1496 cli_invariant_ko(_,_,_,_) :- option(no_invariant_violations),!,fail. % user asks not to check it
1497 cli_invariant_ko(_,_,_,_) :- get_preference(do_invariant_checking,false),!,fail. % user asks not to check it via preference
1498 cli_invariant_ko(CurState,LastActionName,ResInvStatus,CliError) :-
1499 profile_single_call('INVARIANT',unknown,cli_invariant_ko2(CurState,LastActionName,ResInvStatus,CliError)).
1500 cli_invariant_ko2(CurState,LastActionName,ResInvStatus,CliError) :-
1501 state_corresponds_to_initialised_b_machine(CurState,BState),!,
1502 start_probcli_timer(InvTimer),
1503 (b_specialized_invariant_for_op(LastActionName,Invariant) -> true
1504 %, print('Specialized invariant: '),translate:print_bexpr(Invariant),nl
1505 ; b_get_invariant_from_machine(Invariant)),
1506 cli_test_pred(BState,'INVARIANT',Invariant,ResInvStatus),
1507 stop_probcli_debug_timer(InvTimer,'Finished invariant checking after'),
1508 ResInvStatus \= 'TRUE',
1509 (ResInvStatus == 'FALSE' -> CliError = invariant_violation
1510 ; ResInvStatus == 'UNKNOWN' -> CliError = invariant_unknown
1511 ; ResInvStatus == 'TIME-OUT' -> CliError = invariant_time_out
1512 ; format_error_with_nl('Unexpected invariant status: ~w',[ResInvStatus]),
1513 CliError= invariant_unknown).
1514 %cli_invariant_ko(_,_,_,_) :- fail. % not yet initialised
1515
1516 :- use_module(b_interpreter,[b_test_boolean_expression_for_ground_state/4]).
1517 cli_test_pred(BState,PredKind,Pred) :- cli_test_pred(BState,PredKind,Pred,'TRUE').
1518 % comment in following clause to get more precise location for exceptions/virtual timeouts:
1519 %cli_test_pred(BState,PredKind,Pred,Res) :- option_verbose, bsyntaxtree:decompose_conjunct(Pred,A,B),!,
1520 % cli_test_pred(BState,PredKind,A,ResA), (ResA = 'TRUE' -> cli_test_pred(BState,PredKind,B,Res) ; Res = ResA).
1521 cli_test_pred(BState,PredKind,Pred,Res) :- option(timeout(TO)),!,
1522 debug_format(9,'Testing ~w with time-out ~w~n',[PredKind,TO]),
1523 safe_time_out(cli_test_pred2(BState,PredKind,Pred,Res), TO, TRes),
1524 (Res=time_out -> TRes='TIME-OUT' ; true).
1525 cli_test_pred(BState,PredKind,Pred,Res) :-
1526 debug_format(9,'Checking ~w without a time-out~n',[PredKind]),
1527 cli_test_pred2(BState,PredKind,Pred,Res).
1528 cli_test_pred2(BState,PredKind,Pred,Res) :-
1529 % currently does not do a time-out: % b_interpreter calls: time_out_with_enum_warning_one_solution_no_new_error_scope
1530 catch(
1531 on_enumeration_warning(b_test_boolean_expression_for_ground_state(Pred,[],BState,PredKind ), (
1532 add_error(cli_test_pred,'Enumeration warning while testing',PredKind,Pred),
1533 cli_print_pred_info(Pred),
1534 Res='UNKNOWN')
1535 ),
1536 E,
1537 (
1538 ajoin(['VIRTUAL TIME-OUT or exception while testing ',PredKind,': '],Msg),
1539 add_error(cli_test_pred,Msg,E,Pred), % E can also be user_interrupt_signal
1540 cli_print_pred_info(Pred),
1541 Res='UNKNOWN'
1542 )
1543 ),
1544 !,
1545 (var(Res) -> Res = 'TRUE' ; true).
1546 cli_test_pred2(_BState,_PredKind,_Pred,'FALSE').
1547
1548 cli_print_pred_info(Pred) :- get_texpr_label(Pred,Label),
1549 format('Label = ~w~n',[Label]),fail.
1550 cli_print_pred_info(Pred) :- get_texpr_description(Pred,Desc),
1551 format('Description = ~w~n',[Desc]),fail.
1552 %cli_print_pred_info(Pred) :- bsyntaxtree:get_texpr_pos(Pred,Pos), Pos \= none, translate_span(Pos,Str),
1553 % format('Location = ~w~n',[Str]),fail.
1554 cli_print_pred_info(Pred) :-
1555 option_verbose,
1556 write('Predicate: '), translate:nested_print_bexpr(Pred),nl.
1557
1558 :- use_module(bmachine,[get_assertions_from_machine/2]).
1559 % TO DO: also check static assertions
1560 cli_assertions_ko(_,_,_) :- option(no_assertion_violations),!,fail. % user asks not to check it
1561 cli_assertions_ko(CurState,_LastActionName,Res) :-
1562 state_corresponds_to_initialised_b_machine(CurState,BState),
1563 get_assertions_from_machine(dynamic,Assertions), % TO DO: do something similar to b_specialized_invariant_for_op
1564 !,
1565 profile_single_call('ASSERTIONS',unknown,cli_assertions_ko2(BState,Assertions,Res)).
1566
1567
1568 cli_assertions_ko2(BState,Assertions,Res) :-
1569 start_probcli_timer(AssTimer),
1570 %nl,nl,print(check),nl,maplist(translate:print_bexpr,Assertions),nl,
1571 (member(Ass,Assertions),
1572 cli_test_pred(BState,'ASSERTION',Ass,Res),
1573 Res \= 'TRUE' -> true
1574 ; Res = 'TRUE'
1575 ),
1576 stop_probcli_debug_timer(AssTimer,'Finished checking assertions after'),
1577 Res \= 'TRUE'.
1578
1579
1580 :- use_module(bmachine,[b_get_machine_goal/1]).
1581 cli_goal_found(_):- option(no_goal),!,fail.
1582 cli_goal_found(CurState) :-
1583 b_get_machine_goal(Goal),
1584 state_corresponds_to_initialised_b_machine(CurState,BState),
1585 profile_single_call('GOAL',unknown,cli_goal_found2(Goal,BState)).
1586 cli_goal_found2(Goal,BState) :-
1587 b_test_boolean_expression_for_ground_state(Goal,[],BState,'GOAL').
1588
1589
1590 :- use_module(extrasrc(simb_parser),[load_simb_file/1]).
1591 :- use_module(extrasrc(simb_simulator),[run_simb_simulation/2, print_simb_profile/0]).
1592 % SimB simulation
1593 cli_simulate(File,Repetitions,Steps,SimOpts) :-
1594 load_simb_file(File),!,
1595 findall(O,get_simb_option(O),SimOpts2,SimOpts),
1596 debug_format(19,'Simulate max. ~w steps with options ~w~n',[Steps,SimOpts2]),
1597 run_simb_simulations(Repetitions,Steps,SimOpts2).
1598 run_simb_simulations(Reps,_,_) :- Reps<1, !.
1599 run_simb_simulations(Reps,Steps,SimOpts) :-
1600 run_simb_simulation(Steps,SimOpts),!,
1601 R1 is Reps-1,
1602 run_simb_simulations(R1,Steps,SimOpts).
1603
1604 :- use_module(probltlsrc(ltl_tools),[temporal_parser/3]).
1605 get_simb_option(O) :- option(simb_option(O)).
1606 get_simb_option(ltl_stop_condition(LtlStopFormula)) :-
1607 option(simb_ltl_stop_condition(LTL_Stop_AsAtom)),
1608 temporal_parser(LTL_Stop_AsAtom,ltl,LtlStopFormula).
1609
1610 % random animation
1611 :- public cli_random_animate/2. % for repl to use -animate command
1612 cli_random_animate(Steps,Err) :- probcli_time_stamp(NOW),
1613 cli_random_animate(NOW,Steps,Err).
1614 cli_random_animate(_NOW,Steps,ErrorOnDeadlock) :-
1615 start_xml_feature(random_animate,max_steps,Steps,FINFO),
1616 start_ms_timer(Start),
1617 perform_random_steps(Steps,ErrorOnDeadlock),
1618 (option_silent_set -> true ; stop_ms_timer_with_msg(Start,'-animate')),
1619 %tcltk_save_history_as_trace_file(prolog,user),
1620 stop_xml_feature(random_animate,FINFO).
1621
1622 :- use_module(bmachine,[b_get_assertions/3]).
1623 we_need_only_static_assertions(ALL) :- specfile:b_or_z_mode,
1624 (option(cli_check_assertions(main,_)) -> ALL=main
1625 ; option(cli_check_assertions(ALL,_))),
1626 % we do an assertion check
1627 \+ ((option(A), option_requires_all_properties(A))),
1628 b_get_assertions(ALL,dynamic,[]). % the assertions do not reference variables
1629
1630 % do we need all properties/constants of the machine, or only certain ones (e.g., static)
1631 option_requires_all_properties(cli_mc(_,_)).
1632 option_requires_all_properties(cli_check_properties). % we may want to check all properties
1633 option_requires_all_properties(cli_core_properties(_)).
1634 option_requires_all_properties(cli_random_animate(_)).
1635 option_requires_all_properties(default_trace_check).
1636 option_requires_all_properties(trace_check(_,_,_)).
1637 option_requires_all_properties(state_trace(_)).
1638 option_requires_all_properties(mcm_tests(_,_,_,_)).
1639 option_requires_all_properties(cbc_tests(_,_,_)).
1640 option_requires_all_properties(animate).
1641 option_requires_all_properties(initialise). % INITIALISATION may access constants
1642 option_requires_all_properties(eval_repl(_)).
1643 option_requires_all_properties(eval_string_or_file(_,_,_,_,_)).
1644 option_requires_all_properties(ltl_assertions).
1645 option_requires_all_properties(ltl_file(_)).
1646 option_requires_all_properties(refinement_check(_,_,_)).
1647 option_requires_all_properties(cli_start_mc_with_tlc).
1648 option_requires_all_properties(cli_symbolic_model_check(_)).
1649 option_requires_all_properties(process_latex_file(_,_)).
1650 option_requires_all_properties(cli_wd_check(_,_)).
1651 option_requires_all_properties(cli_lint(_)).
1652 option_requires_all_properties(visb_history(_,_,_)).
1653
1654 :- use_module(b_intelligent_trace_replay,[replay_json_trace_file/2]).
1655 :- public default_trace_check/0.
1656 default_trace_check :- loaded_main_file(_,MainFile),
1657 cli_start_default_trace_check(MainFile).
1658 cli_start_default_trace_check(MainFile) :-
1659 debug_println(20,'% Starting Default Trace Check: '),
1660 (check_default_trace_for_specfile(MainFile) -> true ; error_occurred(trace_check)).
1661
1662 default_json_trace_save :-
1663 loaded_main_file(_,MainFile),
1664 get_default_trace_file(MainFile,'.prob2trace',HistFile),
1665 format('Saving history to JSON ProB2-UI default trace file: ~w~n',[HistFile]),
1666 tcltk_save_history_as_trace_file(json,HistFile).
1667 cli_start_trace_check(json,File,default_trace_replay) :- !,
1668 replay_json_trace_file(File,Status),
1669 (Status=perfect -> true
1670 ; Status = imperfect -> add_warning(trace_replay,'Imperfect JSON trace replay:',Status)
1671 ; add_error(trace_replay,'Failed JSON trace replay:',Status)
1672 ).
1673 cli_start_trace_check(Style,File,Mode) :-
1674 debug_format(20,'% Starting Trace Check (~w:~w): ~w~n',[Style,Mode,File]),
1675 (tcltk_check_sequence_from_file(Style,File,Mode) -> true ; error_occurred(trace_check)).
1676 cli_start_trace_state_check(File) :-
1677 debug_println(20,'% Starting Trace Check: '),
1678 (tcltk_check_state_sequence_from_file(File) -> true ; error_occurred(state_trace)).
1679
1680 % is it necessary to compute enabled operations for root state
1681 computeOperations_for_root_required :- initialise_required.
1682 computeOperations_for_root_required :- option(default_trace_check).
1683 computeOperations_for_root_required :- option(trace_check(_,_,_)).
1684 computeOperations_for_root_required :- option(state_trace(_)).
1685 computeOperations_for_root_required :- option(ltl_assertions).
1686 computeOperations_for_root_required :- option(cli_random_animate(_,_)).
1687 computeOperations_for_root_required :- option(socket(_,_)).
1688 computeOperations_for_root_required :- option(cli_mc(_,_)).
1689 computeOperations_for_root_required :- option(ltl_file(_)).
1690 computeOperations_for_root_required :- option(ltl_formula_model_check(_,_)).
1691 computeOperations_for_root_required :- option(ctl_formula_model_check(_,_)).
1692 computeOperations_for_root_required :- option(pctl_formula_model_check(_,_)).
1693 computeOperations_for_root_required :- option(refinement_check(_,_,_)).
1694 computeOperations_for_root_required :- option(csp_in_situ_refinement_check(_,_)).
1695 computeOperations_for_root_required :- option(csp_checkAssertion(_,_)).
1696 computeOperations_for_root_required :- option(mcm_tests(_,_,_,_)).
1697 computeOperations_for_root_required :- option(mcm_cover(_)).
1698
1699 % is an initialisation mandatory:
1700 initialise_required :- option(initialise), \+ empty_machine_loaded.
1701 initialise_required :- \+ option(default_trace_check), \+ option(trace_check(_,_,_)), \+ option(state_trace(_)),
1702 \+ option(load_state(_)),
1703 \+ empty_machine_loaded,
1704 \+ (option(execute(Nr,_,_)), Nr>=2), % execute will also initialise machine
1705 init_req2.
1706 init_req2 :- option(cli_check_properties).
1707 init_req2 :- option(zmq_assertion(_)).
1708 init_req2 :- option(cli_check_assertions(_,_)).
1709 init_req2 :- option(process_latex_file(_,_)).
1710 init_req2 :- option(eval_string_or_file(_,_,_,_,_)). % ensure that we initialise/precompile empty machine in case no main file specified; currently no longer required
1711 init_req2 :- option(check_abstract_constants).
1712 init_req2 :- option(visb_click(_)).
1713 init_req2 :- option(dot_command_for_expr(Cat,_,_,_,_)),
1714 nonmember(Cat,[transition_diagram,expression_coverage]). % see test 1033, option also works with empty state space
1715 %init_req2 :- option(csv_table_command(Cat,_,_,_)), ...
1716
1717 :- public initialise/0. % for REPL
1718 initialise :- probcli_time_stamp(NOW),cli_start_initialisation(NOW).
1719
1720 cli_start_initialisation(NOW) :-
1721 debug_println(20,'% Performing INITIALISATION: '),
1722 (perform_random_initialisation -> true ;
1723 writeln_log_time(cli_start_initialisation_failed(NOW)),
1724 fail).
1725
1726 :- use_module(wdsrc(well_def_analyser),[analyse_wd_for_machine/4]).
1727 :- public cli_wd_check/2. % for REPL
1728 cli_wd_check(ExpectedDis,ExpectedTot) :-
1729 (option(timeout(TO)) -> true ; TO=5000), % this is global_time_out option
1730 (option_silent_set -> Opts=[discharge_po,ignore_wd_infos,reorder_conjuncts]
1731 ; Opts=[create_not_discharged_msg(warning),discharge_po,ignore_wd_infos,reorder_conjuncts]),
1732 statistics(walltime,[W1,_]),
1733 safe_time_out(analyse_wd_for_machine(NrDischarged,NrTot,_Res,Opts),TO,Res),
1734 statistics(walltime,[W2,_]), WT is W2-W1,
1735 (Res=time_out -> accumulate_infos(wd_check,[timeout-1,walltime-WT]), % discharged and total are unknown
1736 add_error(cli_wd_check,'TIME-OUT in WD Analysis (use -global_time_out X to increase it)')
1737 ; format(user_output,'WD Analysis Result: discharged ~w / ~w',[NrDischarged,NrTot]),
1738 (NrTot >0
1739 -> Perc is 100*NrDischarged/NrTot,
1740 (NrDischarged=NrTot -> Col=[green,bold] ; Col=[red])
1741 ; Perc = 100, Col=[]),
1742 format_with_colour(user_output,Col,' (~2f %)~n',[Perc]),
1743 WDInfos = [discharged-NrDischarged,timeout-0,total-NrTot,walltime-WT],
1744 accumulate_infos(wd_check,WDInfos),
1745 (ExpectedDis==ExpectedTot, ExpectedTot = NrTot -> true ; true), % for -wd-check-all: bind ExpectedDis
1746 check_required_infos([discharged-ExpectedDis,total-ExpectedTot],WDInfos,cli_wd_check)
1747 ).
1748 :- use_module(wdsrc(well_def_analyser),[analyse_invariants_for_machine/5]).
1749 cli_wd_inv_proof(UnchangedNr,ProvenNr,TotPOsNr) :-
1750 (option(timeout(TO)) -> true ; TO=5000),
1751 Options=[],
1752 statistics(walltime,[W1,_]),
1753 safe_time_out(analyse_invariants_for_machine(UnchangedNr,ProvenNr,UnProvenNr,TotPOsNr,Options),TO,Res),
1754 statistics(walltime,[W2,_]), WT is W2-W1,
1755 (Res=time_out -> accumulate_infos(wd_inv_proof,[timeout-1,walltime-WT]), % discharged and total are unknown
1756 add_error(cli_wd_check,'TIME-OUT in WD Invariant Proving (use -global_time_out X to increase it)')
1757 ;
1758 (TotPOsNr>0 -> Perc is (UnchangedNr+ProvenNr)*100/ TotPOsNr ; Perc = 100.0),
1759 format('Proof summary for ~w Invariant POs (~2f % discharged): ~w unchanged, ~w proven, ~w unproven~n',
1760 [TotPOsNr,Perc,UnchangedNr,ProvenNr,UnProvenNr]),
1761 WDInfos = [proven-ProvenNr,timeout-0,total-TotPOsNr,unchanged-UnchangedNr,unproven-UnProvenNr,walltime-WT],
1762 accumulate_infos(wd_inv_proof,WDInfos)
1763 ).
1764
1765
1766 :- use_module(bmachine_static_checks,[extended_static_check_machine/1]).
1767 :- use_module(visbsrc(visb_visualiser),[extended_static_check_default_visb_file/0]).
1768 :- use_module(extrasrc(simb_parser),[extended_static_check_default_simb_file/0]).
1769 % perform some additional static checks
1770 :- public cli_lint/0. % for REPL
1771 cli_lint(Check) :-
1772 extended_static_check_machine(Check),
1773 (unavailable_extension(visb_extension,_) -> true
1774 ; (var(Check) ; Check=visb) -> extended_static_check_default_visb_file
1775 ; true),
1776 (Check=simb -> extended_static_check_default_simb_file ; true).
1777 cli_lint :- cli_lint(_).
1778
1779
1780 :- use_module(extrasrc(predicate_debugger),[tcltk_debug_properties/3]).
1781 :- use_module(state_space,[current_state_corresponds_to_setup_constants_b_machine/0]).
1782 :- public cli_check_properties/0. % for REPL
1783 cli_check_properties :- probcli_time_stamp(NOW),
1784 cli_check_properties(NOW).
1785 cli_check_properties(NOW) :-
1786 printsilent('% Checking PROPERTIES: '),nls,
1787 writeln_log_time(starting_check_properties(NOW)),
1788 ( current_state_corresponds_to_setup_constants_b_machine ->
1789 set_analyse_hook('_P'),
1790 predicate_evaluator:tcltk_analyse_properties(_PROPRES,PROPInfos),
1791 unset_analyse_hook,
1792 printsilent(PROPInfos),nls, % ex: [total/33,true/29,false/0,unknown/4,timeout/4,runtime/49950]
1793 accumulate_infos(properties,PROPInfos),
1794 write_important_xml_element_to_log(check_properties,PROPInfos),
1795 (predicate_evaluator:check_summary_all_true(PROPInfos) -> true
1796 ; print_error('Not all PROPERTIES true'), error_occurred(check_properties))
1797 ;
1798 (tcltk_debug_properties(list(PROPRES),false,Satisfiable)
1799 -> printsilent(PROPRES),nls,
1800 printsilent(Satisfiable),nls
1801 ; error_occurred(debug_properties_failed))
1802 ),
1803 writeln_log_time(finished_check_properties(NOW,PROPInfos)),
1804 loaded_root_filename(RootName),
1805 formatsilent('% Finished checking PROPERTIES of ~w~n',[RootName]).
1806
1807 % TODO: provide argument so that we run it only if necessary; e.g., when ProB has not already found a solution
1808
1809 cli_core_properties(Algorithm) :-
1810 format('% Checking CONSISTENCY of PROPERTIES by finding UNSAT CORE (using ~w)~n',[Algorithm]),
1811 b_get_properties_from_machine(Properties),!,
1812 size_of_conjunction(Properties,NrOfConjuncts),
1813 statistics(walltime,[W1,_]),
1814 (find_core(Algorithm,Properties,Core,Result)
1815 -> statistics(walltime,[W2,_]), WTime is W2-W1,
1816 length(Core,Len),
1817 accumulate_infos(properties_core,[contradiction_found-1,core_length-Len,
1818 properties-NrOfConjuncts,walltime-WTime]),
1819 format('UNSAT CORE of length ~w found, PROPERTIES are inconsistent! (~w, ~w ms walltime using ~w)~n',[Len,Result,WTime,Algorithm]),
1820 translate:nested_print_bexpr_as_classicalb(Core),
1821 format('% END OF UNSAT CORE (~w conjuncts)~n',[Len])
1822 % TODO: raise setup_constants_fails and avoid trying to solve properties later
1823 ; statistics(walltime,[W2,_]), WTime is W2-W1,
1824 accumulate_infos(properties_core,[contradiction_found-0,core_length-0,
1825 properties-NrOfConjuncts,walltime-WTime]),
1826 format('No small UNSAT CORE found, PROPERTIES may be consistent (~w ms walltime).~n',[WTime])
1827 ).
1828
1829 :- use_module(extrasrc(unsat_cores),[quick_bup_core_up_to/4]).
1830 :- use_module(wdsrc(well_def_analyser),[find_inconsistent_axiom/3]).
1831 find_core(wd_prover,_,Core,Result) :-
1832 find_inconsistent_axiom([],Axiom,NecHyps),
1833 Core = [Axiom|NecHyps], Result = contradiction_found.
1834 find_core(z3_bup(MaxSize),Properties,Core,Result) :-
1835 (var(MaxSize) -> MaxSize=2 ; true),
1836 quick_bup_core_up_to(Properties,MaxSize,Core,Result).
1837
1838
1839 % -----------------------
1840
1841 :- public cli_check_assertions/2. % for REPL
1842 cli_check_assertions(ALL,RI) :-
1843 probcli_time_stamp(NOW),
1844 cli_check_assertions(ALL,RI,NOW).
1845 cli_check_assertions(ALL,ReqInfos,NOW) :-
1846 printsilent('% Checking ASSERTIONS: '),nls,
1847 writeln_log_time(starting_check_assertions(NOW)),
1848 set_analyse_hook('_A'), % for dot output, in case users wants to generate dot files for assertions
1849 predicate_evaluator:tcltk_analyse_assertions(ALL,_ASSRES,Infos), % also checks CSP assertions
1850 unset_analyse_hook,
1851 printsilent(Infos),nls,
1852 accumulate_infos(assertions,Infos),
1853 write_important_xml_element_to_log(check_assertions,Infos),
1854 check_required_infos(ReqInfos,Infos,check_assertions),
1855 writeln_log_time(finished_check_assertions(NOW,Infos)),
1856 loaded_root_filename(RootName),
1857 formatsilent('% Finished checking ASSERTIONS of ~w~n',[RootName]),!.
1858 cli_check_assertions(ALL,ReqInfos,NOW) :-
1859 add_internal_error('Analyse ASSERTIONS unexpectedly failed',cli_check_assertions(ALL,ReqInfos,NOW)),
1860 error_occurred(internal_error).
1861 cli_set_goal(GOAL) :-
1862 debug_println(20,set_goal(GOAL)), %print(set_goal(GOAL)), nl,
1863 (bmachine:b_set_machine_goal(GOAL) -> true
1864 ; add_error(scope,'Setting GOAL predicate failed:',GOAL)).
1865 cli_add_additional_property(PROP) :-
1866 debug_println(20,add_additional_property(PROP)),
1867 (bmachine:add_additional_property(PROP,'command line -property') -> true
1868 ; add_error(scope,'Adding additional predicate to PROPERTIES failed:',PROP)).
1869 cli_set_searchscope(GOAL) :-
1870 debug_println(20,set_searchscope(GOAL)),
1871 format('Setting SCOPE for verification: ~w~n (Only states satisfying this predicate will be examined)~n',[GOAL]),
1872 (b_or_z_mode, bmachine:b_set_machine_searchscope(GOAL) -> true
1873 ; (xtl_mode, xtl_interface:xtl_set_search_scope(GOAL) -> true
1874 ; add_error(scope,'Setting model checking search SCOPE failed:',GOAL))
1875 ).
1876 cli_check_goal :- \+ b_get_machine_goal(_),!,
1877 add_error(cli_check_goal,'No GOAL DEFINITION found'),
1878 error_occurred(cli_check_goal).
1879 cli_check_goal :-
1880 printsilent('% Checking GOAL predicate: '),nls,
1881 tcltk_analyse_goal(_List,Summary),
1882 debug_println(20,Summary),
1883 accumulate_infos(check_goal,Summary),
1884 write_important_xml_element_to_log(check_goal,Summary),
1885 check_required_infos([false/0,unknown/0],Summary,check_goal).
1886 :- public cli_mc/2. % for REPL
1887 cli_mc(Nr,Opts) :- probcli_time_stamp(NOW), cli_start_model_check(Nr,NOW,Opts).
1888 cli_start_model_check(Nr,NOW,Options) :-
1889 (member(reset_state_space,Options)
1890 -> formatsilent('Resetting state space for benchmarking model checking (limit:~w, options:~w)~n',[Nr, Options]),
1891 announce_event(reset_specification) % for benchmarking purposes
1892 %,state_space:portray_state_space,nl
1893 ; true),
1894 start_xml_feature(model_check,max_states,Nr,FINFO),
1895 regular_safety_model_check_now(Nr,Time,WallTime,MCRes,NOW),
1896 %nl,
1897 stop_xml_feature(model_check,FINFO),
1898 get_state_space_stats(TS,TT,PT,IgnT),
1899 statistics_memory_used(Mem),
1900 (MCRes=time_out -> TInfos=[timeout/1] ; TInfos=[]),
1901 accumulate_infos(model_check,[runtime-Time,walltime-WallTime, % mc only runtime, and total wall time
1902 processed_states/PT,total_states/TS,total_transitions/TT,
1903 ignored_states/IgnT, memory_used/Mem|TInfos]), %for bench_csv output
1904 writeln_log_time(model_check(NOW,Nr,Time,WallTime,MCRes)),
1905 (select(repeat(RepNr),Options,RestOptions)
1906 -> (RepNr>1
1907 -> N1 is RepNr-1,
1908 cli_start_model_check(Nr,NOW,[repeat(N1)|RestOptions])
1909 ; merge_accumulated_infos(model_check)
1910 )
1911 ; true
1912 ).
1913
1914 cli_start_mc_with_tlc :-
1915 (animation_mode(b), \+ animation_minor_mode(eventb) -> true
1916 ; error_manager: add_error_and_fail(mc_with_tlc,'TLC4B tool can be used only for classical B models.')),
1917 % TO DO: use b_write_eventb_machine_to_classicalb_to_file to do conversion
1918 catch(
1919 safe_absolute_file_name(prob_lib('TLC4B.jar'),TLC4BTool),
1920 error(E,_),
1921 error_manager:add_error_fail(get_tlc_command,'Could not find TLC4B.jar file.',E)),
1922 start_xml_feature(model_check_with_tlc,tlc4bjar,TLC4BTool,FINFO),
1923 construct_and_execute_tlc_command(TLC4BTool),
1924 stop_xml_feature(model_check_with_tlc,FINFO).
1925
1926 :- use_module(system_call,[system_call/4]).
1927 construct_and_execute_tlc_command(TLC4BTool) :-
1928 parsercall: get_java_command_path(JavaCmd),
1929 loaded_main_file(File),
1930 % determine extra arguments:
1931 (get_preference(tlc_number_of_workers,TLCWorkers), TLCWorkers>1
1932 -> number_codes(TLCWorkers,CC), atom_codes(TLAWA,CC), WW = ['-workers',TLAWA]
1933 ; WW=[]),
1934 (option(no_assertion_violations) -> WA = ['-noass'] ; WA=[]),
1935 (option(no_deadlocks) -> WD = ['-nodead'] ; WD=[]),
1936 (option(no_invariant_violations) -> WI = ['-noinv'] ; WI=[]),
1937 (option(no_goal) -> WG = ['-nogoal'] ; WG=[]),
1938 (option(no_ltl) -> WL = ['-noltl'] ; WL=[]),
1939 (option_verbose -> WV = ['-verbose'] ; WV=[]),
1940 (option_silent_set -> WS = ['-silent'] ; WS=[]),
1941 (option(logtlc(Log)) -> WLG = ['-log',Log] ; WLG=[]),
1942 (get_preference(tlc_use_prob_constant_setup,true),
1943 tcltk_get_constants_predicate(DNF_Pred)
1944 -> WCS = ['-constantssetup', DNF_Pred]
1945 ; WCS=[]),
1946 append([WW,WA,WD,WI,WG,WL,WCS,WV,WS,WLG,[File]],TLCArgs),
1947 debug_println(19,tlc_args(TLCArgs)),
1948 statistics(walltime,[W1,_]),
1949 % we could call get_jvm_options: '-Xss5m' is useful e.g. for Generated1000.mch
1950 system_call(JavaCmd, ['-Xss5m', '-jar', TLC4BTool | TLCArgs], Text,JExit),
1951 statistics(walltime,[W2,_]),
1952 WTime is W2-W1,
1953 formatsilent('exit : ~w walltime: ~w ms~n',[JExit,WTime]),
1954 (JExit=exit(0)
1955 -> accumulate_infos(mc_with_tlc,[walltime-WTime,model_check_ok-1])
1956 ; accumulate_infos(mc_with_tlc,[walltime-WTime,model_check_error-1]),
1957 add_error(construct_and_execute_tlc_command,'Error while model checking with TLC: ',TLC4BTool/File),
1958 atom_codes(T,Text),
1959 add_error_fail(construct_and_execute_tlc_command,'Std error: ',T)
1960 ).
1961
1962 % SymbolicOrSequential = symbolic or sequential
1963 cli_start_sym_mc_with_lts(SymbolicOrSequential) :-
1964 (option(no_deadlocks) -> NoDead = true ; NoDead = false),
1965 (option(no_invariant_violations) -> NoInv = true ; NoInv = false), % does LTSMin support goal checking
1966 findall(Option,option(ltsmin_option(Option)),MoreFlags1),
1967 findall(ltl_formula(LTLF),option(ltl_formula_model_check(LTLF,_)),MoreFlags2),
1968 append(MoreFlags1,MoreFlags2,MoreFlags),
1969 (NoDead = false, NoInv = false ->
1970 print_error('ERROR: cannot start LTSmin with both deadlock and invariant checking'),
1971 print_error(' use either the -noinv or -nodead flag'),
1972 flush_output(user_error)
1973 ; true),
1974 formatsilent('starting prob2lts-sym/seq (flags nodead=~w, noinv=~w, moreflags=~w)~n',[NoDead,NoInv,MoreFlags]),
1975 statistics(walltime,[W1,_]),
1976 start_ltsmin(SymbolicOrSequential, [NoDead, NoInv], MoreFlags,Result),
1977 process_ltsmin_result(Result,AccInfos),
1978 statistics(walltime,[W2,_]), WT is W2-W1,
1979 accumulate_infos(mc_with_lts_min(SymbolicOrSequential),[walltime-WT|AccInfos]).
1980 % TO DO: start lts-sym + start start_ltsmin_srv('/tmp/ltsmin.probz', NOW) + print output
1981
1982 :- use_module(extension('ltsmin/ltsmin_trace'),[csv_to_trace/3]).
1983 process_ltsmin_result(ltsmin_model_checking_ok,[model_check_ok-1]) :-
1984 print_green('LTSMin found no counter example\n').
1985 process_ltsmin_result(ltsmin_model_checking_aborted,[model_check_aborted-1]) :-
1986 add_warning(ltsmin_model_checking_aborted,'LTSMin was aborted (e.g., by CTRL-C)').
1987 process_ltsmin_result(ltsmin_counter_example_found(CsvFile),[model_check_counter_example-1]) :-
1988 add_error(ltsmin_counter_example_found,'LTSMin found a counter example, written to:',CsvFile),
1989 (option_silent_set -> true
1990 ; csv_to_trace(CsvFile,_States,Transitions) ->
1991 print('*** TRACE: '),nl,print_list(Transitions) % ,print(_States),nl
1992 ; add_error(ltsmin,'Could not extract trace information from LTSmin file: ',CsvFile)
1993 ).
1994
1995 :- use_module(symbolic_model_checker(ic3), [ic3_symbolic_model_check/1]).
1996 :- use_module(symbolic_model_checker(ctigar), [ctigar_symbolic_model_check/1]).
1997 :- use_module(symbolic_model_checker(kinduction), [kinduction_symbolic_model_check/1,
1998 tinduction_symbolic_model_check/1]).
1999 :- use_module(symbolic_model_checker(bmc), [bmc_symbolic_model_check/1]).
2000 cli_symbolic_model_check(Algorithm) :-
2001 debug_format(20,'% Starting Symbolic Model Check. Using ~w Algorithm', [Algorithm]),
2002 start_xml_feature(model_check,algorithm,Algorithm,FINFO),
2003 (animation_mode(b)
2004 -> true
2005 ; error_manager:add_error_and_fail(cli_symbolic_model_check,'Symbolic Model Checking is currently only available for B and Event-B.')),
2006 perform_symbolic_model_checking(Algorithm,Result),
2007 handle_symbolic_model_check_result(Result),
2008 stop_xml_feature(model_check,FINFO).
2009
2010 perform_symbolic_model_checking(ic3,Result) :- !, ic3_symbolic_model_check(Result).
2011 perform_symbolic_model_checking(ctigar,Result) :- !, ctigar_symbolic_model_check(Result).
2012 perform_symbolic_model_checking(kinduction,Result) :- !, kinduction_symbolic_model_check(Result).
2013 perform_symbolic_model_checking(tinduction,Result) :- !, tinduction_symbolic_model_check(Result).
2014 perform_symbolic_model_checking(bmc,Result) :- !, bmc_symbolic_model_check(Result).
2015 perform_symbolic_model_checking(Alg,_) :- add_error_fail(cli_symbolic_model_check,'Invalid symbolic model checking algorithm: ',Alg).
2016
2017 handle_symbolic_model_check_result(counterexample_found) :- !, error_occurred(invariant_violation).
2018 handle_symbolic_model_check_result(property_holds) :- !,
2019 format('Model checking complete, invariant holds~n',[]).
2020 handle_symbolic_model_check_result(solver_and_provers_too_weak) :- !,
2021 format('Model checking incomplete because a constraint could not be solved in time~n',[]),
2022 error_occurred(model_check_incomplete).
2023 handle_symbolic_model_check_result(limit_reached) :- !,
2024 format('Model checking incomplete because an iteration limit was reached~n',[]),
2025 error_occurred(model_check_incomplete).
2026
2027 zmq_start_master(invariant,Identifier) :-
2028 start_animation_without_computing,
2029 zmq_get_initialisation_term(InitTerm),
2030 (option(strict_raise_error) -> Strict = 1 ; Strict = 0),
2031 get_preference(port, PortStart),
2032 get_preference(max_states, Max),
2033 get_preference(ip, IP),
2034 get_preference(logdir, LogDir),
2035 get_preference(tmpdir, TmpDir),
2036 get_preference(hash_cycle, HashCycle),
2037 atom_concat(LogDir, '/distb-', ATmp),
2038 atom_concat(ATmp, Identifier, Logfile),
2039 atom_concat(TmpDir, '/db-distb-', TTmp),
2040 atom_concat(TTmp, Identifier, TmpDir2),
2041 start_master(InitTerm,Max,PortStart,Strict,IP,Logfile,TmpDir2,HashCycle),
2042 halt.
2043 zmq_start_master(assertion,Identifier) :-
2044 get_preference(port, PortStart),
2045 get_preference(logdir, LogDir),
2046 get_preference(ip, IP),
2047 get_preference(tmpdir, TmpDir),
2048 get_preference(hash_cycle, HashCycle),
2049 atom_concat(LogDir, '/distb-', ATmp),
2050 atom_concat(ATmp, Identifier, Logfile),
2051 atom_concat(TmpDir, '/db-distb-', TTmp),
2052 atom_concat(TTmp, Identifier, TmpDir2),
2053 current_state_corresponds_to_setup_constants_b_machine,
2054 animation_mode(b),
2055 full_b_machine(Machine),
2056 b_get_assertions(_,static,SAss),
2057 b_get_assertions(_,dynamic,DAss),
2058 append(SAss,DAss,Ass),
2059 count_assertions(Ass,0,N),
2060 assertz(master:assertion_count(N)),
2061 current_expression(_,State1),
2062 specfile:state_corresponds_to_set_up_constants(State1,State),
2063 zmq_get_important_options(Options),
2064 (option(strict_raise_error) -> Strict = 1 ; Strict = 0),
2065 %start_master(assertions(classical_b(Machine,Options),State,Ass),2,-1,PortStart,0,Strict,IP,Logfile,TmpDir2),
2066 start_master(assertions(classical_b(Machine,Options),State,Ass),2,PortStart,Strict,IP,Logfile,TmpDir2,HashCycle),
2067 halt.
2068
2069 zmq_get_initialisation_term(Term) :-
2070 (animation_mode(b) ; animation_mode(csp_and_b)), % CSP file not yet added when ZMQ master starts working
2071 \+ animation_minor_mode(eventb),
2072 option(add_csp_guide(CspGuide)),
2073 !, % Classical B + CSP
2074 debug_println(20,'ZMQ: Transferring CSP || B model'),
2075 full_b_machine(Machine),
2076 % TO DO: extract CSP Term rather than file name: will not work for distribution on other file-systems
2077 zmq_get_important_options(Options),
2078 Term = classical_b_with_csp(Machine,CspGuide,Options).
2079 zmq_get_initialisation_term(Term) :-
2080 debug_println(20,'Generating ZMQ Worker Initialisation'),
2081 animation_mode(b), \+ animation_minor_mode(eventb), !, % Classical B
2082 debug_println(20,'ZMQ: Transferring Classical-B model'),
2083 full_b_machine(Machine),
2084 zmq_get_important_options(Options),
2085 Term = classical_b(Machine,Options).
2086 zmq_get_initialisation_term(Term) :-
2087 animation_mode(b), animation_minor_mode(eventb), !, % Event-B
2088 debug_println(20,'ZMQ: Transferring Event-B model'),
2089 full_b_machine(Machine),
2090 zmq_get_important_options(Options),
2091 Term = eventb(Machine,Options).
2092 zmq_get_initialisation_term(Term) :-
2093 animation_mode(cspm),
2094 loaded_main_file(MainCSPFile),!, % TO DO: pass CSP Prolog term rather than file name (for distribution)
2095 zmq_get_important_options(Options),
2096 debug_println(20,'ZMQ: Transferring CSP specification'),
2097 Term = csp_specification(MainCSPFile,Options).
2098 zmq_get_initialisation_term(_Term) :-
2099 \+ real_error_occurred, % otherwise error occured while loading
2100 animation_mode(Mode),
2101 add_internal_error('Unsupported formalism for ZMQ', Mode),
2102 fail.
2103
2104 zmq_get_initialisation_term(filename(FN)) :-
2105 loaded_main_file(FN).
2106
2107 % get important command-line options to be transmitted to probcli worker
2108 zmq_get_important_options(Options) :- findall(O, (option(O), zmq_important_option(O)), Options),
2109 debug_println(20,transferring_zmq_options_to_workers(Options)).
2110 zmq_important_option(coverage(_)).
2111 zmq_important_option(expect_error(_)).
2112 zmq_important_option(optional_error(_)).
2113 zmq_important_option(file_info).
2114 zmq_important_option(log(_)).
2115 zmq_important_option(print_version(_)).
2116 zmq_important_option(profiling_on).
2117 zmq_important_option(set_card(_,_)).
2118 zmq_important_option(set_pref(_,_)).
2119 zmq_important_option(set_preference_group(_,_)).
2120 zmq_important_option(statistics).
2121 zmq_important_option(csv_table_command(_,_,_,_)).
2122 zmq_important_option(verbose(_)).
2123 zmq_important_option(set_searchscope(_)).
2124 zmq_important_option(no_invariant_violations).
2125 %zmq_important_option(no_deadlocks).
2126 %zmq_important_option(no_goal).
2127 % we could consider also supporting: -argv, -cache, -prefs FILE csp_main(ProcessName) profiling_on prob_profile runtimechecking
2128
2129 % set options received by a zmq worker
2130 :- use_module(b_global_sets, [set_user_defined_scope/2]).
2131 :- use_module(tools_strings, [convert_cli_arg/2]).
2132 zmq_set_important_options(Options) :- debug_println(20,setting_zmq_options(Options)),
2133 maplist(prob_cli:zmq_set_option,Options).
2134 zmq_set_option(file_info) :- !, file_info.
2135 zmq_set_option(log(F)) :- !,
2136 generate_time_stamp(Datime,NOW),
2137 cli_start_logging(F,ascii,NOW,Datime,[zmq_worker]).
2138 zmq_set_option(print_version(V)) :- !, print_version(V).
2139 zmq_set_option(profiling_on) :- !, profiling_on.
2140 zmq_set_option(set_card(Set,V)) :- !,
2141 convert_cli_arg(V,Value),
2142 set_user_defined_scope(Set,Value).
2143 zmq_set_option(set_pref(P,V)) :- !, set_pref(P,V).
2144 zmq_set_option(set_preference_group(P,V)) :- !, set_preference_group(P,V).
2145 zmq_set_option(verbose(Nr)) :- !, verbose(Nr).
2146 zmq_set_option(O) :- zmq_delayed_option(O),!, assert_option(O). % DO IT LATER
2147 zmq_set_option(O) :- add_internal_error('Unsupported option for ZMQ worker: ',zmq_set_option(O)).
2148
2149 zmq_delayed_option(coverage(_)).
2150 zmq_delayed_option(expect_error(_)).
2151 zmq_delayed_option(expect_error_pos(_,_,_)).
2152 zmq_delayed_option(optional_error(_)).
2153 zmq_delayed_option(statistics).
2154 zmq_delayed_option(set_searchscope(_)).
2155 zmq_delayed_option(no_invariant_violations). % not supported yet
2156
2157 ltsmin_ltl_output(Filename, NOW) :-
2158 if_option_set(ltl_formula_model_check(Formula, _),true),
2159 ltsmin_generate_ltlfile(Formula, Filename),
2160 halt_prob(NOW,0). % if we additionally specify -ltsformula, we do not want to model check it
2161
2162
2163 start_ltsmin_srv(X, NOW) :-
2164 nls,println_silent('Starting LTSMin Server...'),
2165 if_option_set(ltl_formula_model_check(Formula, _),true),
2166 ltsmin_init(X, Zocket, Formula),
2167 ltsmin_loop(Zocket),
2168 ltsmin_teardown(Zocket, X),
2169 nls,println_silent('Stopped LTSMin Server.'),
2170 halt_prob(NOW,0). % if we additionally specify -ltsformula, we do not want to model check it
2171
2172 zmq_start_worker(Identifier, NOW) :-
2173 get_preference(port, Port),
2174 get_preference(logdir, LogDir),
2175 get_preference(tmpdir, TmpDir),
2176 get_preference(proxynumber, ProxyNumber),
2177 /* TODO: ensure directory exists (pk, 09.01.2018) */
2178 atom_concat(LogDir, '/worker-', ATmp),
2179 atom_concat(ATmp, Identifier, Logfile),
2180 % TODO: tmp dir currently not used
2181 atom_concat(TmpDir, '/db-worker-', TTmp),
2182 atom_concat(TTmp, Identifier, TmpDir2),
2183 start_worker(Port,ProxyNumber,Logfile,TmpDir2,zmq_worker_load_model),
2184 formatsilent('ZMQ worker finished (Port:~w)~n',[Port]),
2185 cli_process_loaded_file_afer_start_animation(NOW),
2186 println_silent('Exiting probcli worker'),
2187 halt_prob(NOW,0).
2188
2189 zmq_start_animation :-
2190 prob2_interface:start_animation,
2191 if_option_set(set_goal(GOAL),
2192 cli_set_goal(GOAL)), % not used yet
2193 if_option_set(set_searchscope(SCOPE),
2194 cli_set_searchscope(SCOPE)),
2195 cli_computeOperations(_).
2196 zmq_worker_load_model(classical_b(Machine,Options)) :- !,
2197 debug_println(20,'ZMQ WORKER: Loading classical B model'),
2198 zmq_set_important_options(Options),
2199 bmachine:b_machine_reset, bmachine:assert_main_machine(Machine),
2200 set_animation_mode(b),
2201 zmq_start_animation.
2202 zmq_worker_load_model(classical_b_with_csp(Machine,CspGuide,Options)) :- !,
2203 debug_println(20,'ZMQ WORKER: Loading CSP || B model'),
2204 zmq_set_important_options(Options),
2205 bmachine:b_machine_reset, bmachine:assert_main_machine(Machine),
2206 set_animation_mode(b),
2207 prob2_interface:start_animation,
2208 tcltk_add_csp_file(CspGuide), % TO DO: use CSP Prolog term rather than filename <----------------
2209 zmq_start_animation.
2210 zmq_worker_load_model(eventb(Machine,Options)) :- !,
2211 print(loading_eventb(Options)),nl,
2212 zmq_set_important_options(Options),
2213 bmachine:b_machine_reset, bmachine:assert_main_machine(Machine),
2214 set_animation_mode(b), set_animation_minor_mode(eventb),
2215 zmq_start_animation.
2216 zmq_worker_load_model(csp_specification(CSPFile,Options)) :-
2217 zmq_set_important_options(Options),
2218 load_cspm_spec_from_cspm_file(CSPFile), % TO DO: pass CSP Prolog term rather than filename
2219 zmq_start_animation.
2220 zmq_worker_load_model(filename(FN)) :- !,
2221 printsilent('loading file by filename\n'),flush_output,
2222 ( is_eventb_b(FN) ->
2223 eclipse_interface:load_eventb_file(FN)
2224 ;
2225 bmachine:b_load_machine_probfile(FN)),
2226 zmq_start_animation.
2227 zmq_worker_load_model(assertions(Machine,State,Assertions)) :- !,
2228 assertz(assertion_counter(-1)),
2229 println_silent(loaded_model_for_assertion_checking),
2230 zmq_worker_load_model(Machine),
2231 assertz(worker:assertion_state(State)),
2232 make_assertionwps(Assertions).
2233 % assert current state
2234 zmq_worker_load_model(Other) :-
2235 add_internal_error('ZMQ worker: Unexpected machine description', zmq_worker_load_model(Other)),
2236 fail.
2237
2238
2239 :-dynamic assertion_counter/1.
2240
2241 count_assertions([],A,A).
2242 count_assertions([H|T],A,R) :- size_of_conjunction(H,N1),
2243 NN is A + N1,
2244 count_assertions(T,NN,R).
2245
2246 make_assertionwps([]).
2247 make_assertionwps([H|T]) :- conjunction_to_list(H,HL),
2248 sort_assertions(HL,SL),
2249 append_assertion(SL),
2250 make_assertionwps(T).
2251
2252 append_assertion([]).
2253 append_assertion([H|T]) :- assertion_counter(N),
2254 retractall(assertion_counter(_)),
2255 N1 is N + 1,
2256 assertz(assertion_counter(N1)),
2257 assertz(worker:assertion_task(N1,H)),
2258 append_assertion(T).
2259
2260 %assertions_order(A,B) :- term_size(A,NA),term_size(B,NB), NA > NB.
2261 sort_assertions(X,X).
2262 % :- samsort(assertions_order,X,Y).
2263
2264
2265
2266 is_eventb_b(FN) :- append(_,FN,".eventb").
2267 % load_model(Initialisation)
2268
2269
2270 :- use_module(predicate_evaluator).
2271 :- use_module(bmachine,[b_machine_name/1]).
2272 set_analyse_hook(AddPrefix) :- % set a hook to write false/unknown expressions into a dot file
2273 reset_dot_file_number,
2274 if_options_set(dot_analyse_output_prefix(_Path),
2275 (set_dot_file_prefix_if_option_set(AddPrefix),
2276 register_conjunct_error_hook(prob_cli:pred_eval_hook))).
2277 unset_analyse_hook :- predicate_evaluator:reset_conjunct_error_hook.
2278
2279 :- use_module(tools,[get_modulename_filename/2]).
2280 loaded_root_filename(RootName) :- loaded_main_file(MainFile),
2281 get_modulename_filename(MainFile,RootName).
2282
2283 set_dot_file_prefix_if_option_set(AddPrefix) :-
2284 if_options_set(dot_analyse_output_prefix(Path),
2285 (loaded_root_filename(RootName),
2286 % we could also use b_machine_hierarchy:main_machine_name(RootName)
2287 string_concatenate(Path,RootName,P1),
2288 string_concatenate(P1,AddPrefix,FullPath),
2289 set_dot_file_prefix(FullPath),
2290 debug_println(9,dot_file_prefix(FullPath)))).
2291
2292 % Status: true, false, unknown
2293 :- public pred_eval_hook/5.
2294 pred_eval_hook(_Conjunct,true,_EnumWarning,_IsExpanded, _CS) :-
2295 \+ option(dot_generate_for_all_formulas),!. % don't generate .dot for true formulas, unless explicitly requested
2296 pred_eval_hook(Conjunct,Status,_EnumWarning,_IsExpanded, CS) :-
2297 printsilent('Generating dotfile for: '),printsilent(CS),nls,
2298 (write_dot_graph_to_new_file(Status,Conjunct) -> true
2299 ; add_error(dot_output,'Writing dot to file failed: ',CS)).
2300
2301
2302 :- dynamic dot_file_prefix/1.
2303 :- dynamic dot_file_number/1.
2304
2305 dot_file_prefix('~/Desktop/dot').
2306 set_dot_file_prefix(F) :- retractall(dot_file_prefix(_)), assertz(dot_file_prefix(F)).
2307 dot_file_number(0).
2308 reset_dot_file_number :- retractall(dot_file_number(_)), assertz(dot_file_number(0)).
2309 get_next_nr(GNr) :- retract(dot_file_number(Nr)), N1 is Nr+1,
2310 assertz(dot_file_number(N1)), GNr = Nr.
2311 write_dot_graph_to_new_file(Status,BExpr) :-
2312 dot_file_prefix(Dir),get_next_nr(Nr),
2313 string_concatenate('_',Status,Str1),
2314 string_concatenate(Nr,Str1,NS),
2315 string_concatenate(Dir,NS,F1),
2316 atom_concat(F1,'.dot',FileName),
2317 tcltk_interface:write_dot_file_for_pred_expr(BExpr,FileName).
2318
2319 % get dot file name if dot_output has been set
2320 get_dot_file(Type,FileName) :- option(dot_analyse_output_prefix(_)),
2321 set_dot_file_prefix_if_option_set(Type),
2322 dot_file_prefix(Dir),
2323 string_concatenate('_',Type,Str1),
2324 string_concatenate(Dir,Str1,F1),
2325 atom_concat(F1,'.dot',FileName).
2326
2327 :- use_module(extrasrc(refinement_checker),
2328 [tcltk_refinement_search/3, tcltk_load_refine_spec_file/1, tcltk_save_specification_state_for_refinement/1]).
2329 cli_csp_in_situ_refinement_check(P,Type,Q,NOW) :-
2330 debug_println(20,'% Starting CSP Refinement Check'),
2331 loaded_main_file(CSPFile),
2332 ajoin_with_sep(['assert',P,Type,Q], ' ',Assertion),
2333 start_xml_feature(csp_refinement_check,assertion,Assertion,FINFO),
2334 ( timeout_call(tcltk_interface:tcltk_check_csp_assertion(Assertion,CSPFile,'False',_PlTerm,RefTrace),NOW,'cspref')
2335 -> check_ref_result(RefTrace)
2336 ; true),
2337 stop_xml_feature(csp_refinement_check,FINFO).
2338 cli_start_refinement_check(RefFile,FailuresModel,RefNrNodes,NOW) :-
2339 start_xml_feature(refinement_check,file,RefFile,FINFO),
2340 tcltk_load_refine_spec_file(RefFile),
2341 ( timeout_call(tcltk_refinement_search(RefTrace,FailuresModel,RefNrNodes),NOW,refinement_check)
2342 -> check_ref_result(RefTrace)
2343 ; true),
2344 stop_xml_feature(refinement_check,FINFO).
2345 check_ref_result(RefTrace) :-
2346 ( RefTrace==no_counter_example ->
2347 print('==> Refinement Check Successful'),nl
2348 ; RefTrace==no_counter_example_found ->
2349 print('==> Refinement Check did not find Counterexample but is incomplete'),nl,
2350 error_occurred(refinement_check_incomplete)
2351 ; RefTrace==not_checked -> % an error has already been raised
2352 print('==> Refinement Check not performed'),nl
2353 ;
2354 print('*** Refinement Check Counterexample: ***'),nl, print(RefTrace),nl,
2355 (expected_error(refinement_check_fails)
2356 -> print('*** Refinement Check found Counterexample (as expected) ***')
2357 ; print('*** Refinement Check found Counterexample ***')),nl,
2358 error_occurred(refinement_check_fails)).
2359 cli_checkAssertion(Proc,Model,AssertionType,_NOW) :-
2360 loaded_main_file(CSPFile),
2361 ajoin(['assert ',Proc,' :[ ',AssertionType,'[',Model,']',' ]'],Assertion),
2362 start_xml_feature(csp_deadlock_check,assertion,Assertion,FINFO),
2363 ( /*timeout_call(*/tcltk_interface:tcltk_check_csp_assertion(Assertion,CSPFile,'False',_PlTerm,ResTrace)/*,NOW,a)*/
2364 -> check_model_result(Assertion,ResTrace)
2365 ; true),
2366 stop_xml_feature(csp_deadlock_check,FINFO).
2367 cli_check_csp_assertion(Assertion,NOW) :-
2368 start_xml_feature(csp_assertion_check,assertion,Assertion,FINFO),
2369 loaded_main_file(CSPFile),
2370 ajoin(['assert ',Assertion],AssertionFull),
2371 ( timeout_call(tcltk_interface:tcltk_check_csp_assertion(AssertionFull,CSPFile,_Negated,PlTerm,ResTrace),NOW,csp_assertion_check)
2372 -> check_model_result(PlTerm,ResTrace)
2373 ; true),
2374 stop_xml_feature(csp_assertion_check,FINFO).
2375
2376
2377
2378 check_model_result(AssertionPlTerm,ResTrace) :-
2379 ( ResTrace==no_counter_example ->
2380 printsilent('==> Model Check Successful'),nls
2381 ; ResTrace==not_checked -> % an error has already been raised
2382 print('==> Check not performed'),nl
2383 ; ResTrace==no_counter_example_found ->
2384 (functor(AssertionPlTerm,assertRef,_)
2385 -> print('==> Refinement Check did not find Counterexample but is incomplete'),nl,
2386 error_occurred(refinement_check_incomplete)
2387 ; print('==> Model Check did not find Counterexample but is incomplete'),nl,
2388 error_occurred(model_check_incomplete))
2389 ;
2390 (functor(AssertionPlTerm,assertRef,_Arity) ->
2391 print('*** Refinement Check Counterexample: ***'),nl, print(ResTrace),nl,
2392 (expected_error(refinement_check_fails)
2393 -> print('*** Refinement Check found Counterexample (as expected) ***')
2394 ; print('*** Refinement Check found Counterexample ***')),nl,
2395 error_occurred(refinement_check_fails)
2396 ;
2397 print('*** Model Check Counterexample: ***'),nl,print(ResTrace),nl,
2398 (expected_error(model_check_fails)
2399 -> print('*** Model Check found Counterexample (as expected) ***')
2400 ; print('*** Model Check found Counterexample ***')),nl,
2401 error_occurred(model_check_fails))
2402 ).
2403 :- use_module(probcspsrc(haskell_csp),[get_csp_assertions_as_string/2,
2404 parse_and_load_cspm_file_into_specific_pl_file/2,
2405 evaluate_csp_expression/2, evaluate_csp_expression/3]).
2406 cli_csp_get_assertions :-
2407 loaded_main_file(CSPFile),
2408 get_csp_assertions_as_string(CSPFile,String),
2409 print('*** Assertions in File (separated by $) ***'),nl,print(String),nl.
2410 cli_eval_csp_expression(E) :-
2411 (loaded_main_file(CSPFile) ->
2412 evaluate_csp_expression(E, CSPFile, Res)
2413 ; evaluate_csp_expression(E,Res)
2414 ), print('Evaluated Expression: '),nl,print(Res),nl.
2415 cli_csp_translate_to_file(PlFile) :-
2416 loaded_main_file(CSPFile),
2417 parse_and_load_cspm_file_into_specific_pl_file(CSPFile,PlFile).
2418 :- use_module(probltlsrc(ltl_fairness),[check_scc_ce/2]).
2419 cli_check_scc_for_ltl_formula(LtlFormula,SCC) :-
2420 check_scc_ce(LtlFormula,SCC).
2421
2422 :- use_module(extrasrc(coverage_statistics),[pretty_print_coverage_information_to_file/1]).
2423 cli_get_coverage_information(FileName) :-
2424 pretty_print_coverage_information_to_file(FileName).
2425 cli_vacuity_check :-
2426 eclipse_interface:get_vacuous_invariants(L),
2427 (L=[] -> print('No vacuous invariants'),nl
2428 ; maplist(prob_cli:add_vacuous_invariant,L)).
2429 add_vacuous_invariant(Inv) :-
2430 translate:translate_bexpression(Inv,TI),
2431 add_error(vacuity_check,'Vacuous invariant: ',TI).
2432 cli_start_socketserver(Port,Loopback) :-
2433 printsilent('Starting Socket Server'),nls,
2434 safe_absolute_file_name(prob_home('.'),AppDir),
2435 printsilent('Application Path: '),printsilent(AppDir),nls,
2436 disable_interaction_on_errors,
2437 ( start_prob_socketserver(Port,Loopback) -> true
2438 ;
2439 print('Starting socket server failed, Port: '), print(Port),nl),
2440 printsilent('Finished Socket Server'),nls.
2441 :- use_module(tools_platform, [platform_is_64_bit/0]).
2442 cli_check_statespace_hash(Expected,Kind) :-
2443 printsilent('Computing hash of entire statespace: '),
2444 compute_full_state_space_hash(Hash),
2445 printsilent(Hash),nls, % TO DO: maybe also compute hash for transitions and check that
2446 (Hash=Expected -> true
2447 ; Kind=='64bit', \+ platform_is_64_bit -> format('Hash does not match ~w (but was computed on 64-bit system)~n',[Expected])
2448 ; Kind=='32bit', platform_is_64_bit -> format('Hash does not match ~w (but was computed on 32-bit system)~n',[Expected])
2449 ; add_error(hash,'Expected Statespace Hash to be: ',Expected)).
2450 :- use_module(extrasrc(b_operation_cache),[get_op_cache_stats/1]).
2451 cli_check_op_cache(ReqInfos) :-
2452 get_op_cache_stats(Stats),
2453 (ReqInfos=[] -> format('Operation caching statistics: ~w~n',[Stats])
2454 ; formatsilent('Operation caching statistics: ~w~n',[Stats])),
2455 accumulate_infos(op_cache,Stats),
2456 check_required_infos(ReqInfos,Stats,op_cache_stats).
2457 cli_show_coverage(ShowEnabledInfo,NOW) :-
2458 cli_show_coverage(_Nodes,_Operations,ShowEnabledInfo,NOW).
2459 cli_show_coverage(Nodes,Operations,ShowEnabledInfo,NOW) :-
2460 ShowEnabledInfo == just_check_stats,!, % no printing of individual transition coverage
2461 get_state_space_stats(TotalNodeSum,TotalTransSum,_ProcessedTotal,_), % no computation overhead
2462 writeln_log(computed_coverage(NOW,TotalNodeSum,TotalTransSum)),
2463 check_totals(Nodes,Operations,TotalNodeSum,TotalTransSum).
2464 cli_show_coverage(Nodes,Operations,ShowEnabledInfo,NOW) :-
2465 ShowEnabledInfo == just_summary,
2466 !, % no printing of detailed transition coverage (avoid traversing state space)
2467 get_state_space_stats(TotalNodeSum,TotalTransSum,ProcessedTotal,Ignored), % no computation overhead
2468 writeln_log(computed_coverage(NOW,TotalNodeSum,TotalTransSum)),
2469 format('Coverage:~n States: ~w (~w processed, ~w ignored)~n Transitions: ~w~n',
2470 [TotalNodeSum,ProcessedTotal,Ignored,TotalTransSum]),
2471 show_initialisation_summary(NOW),
2472 show_operation_coverage_summary(NOW),
2473 (invariant_violated(ID) -> format('At least one state violates the invariant (~w) ~n',[ID]) ; true),
2474 check_totals(Nodes,Operations,TotalNodeSum,TotalTransSum).
2475 cli_show_coverage(Nodes,Operations,ShowEnabledInfo,NOW) :-
2476 write('Coverage Information:'),nl,
2477 compute_the_coverage(Res,TotalNodeSum,TotalTransSum,ShowEnabledInfo,false),
2478 writeln_log(computed_coverage(NOW,TotalNodeSum,TotalTransSum)),
2479 write_table_to_text_file(user_output,Res),
2480 check_totals(Nodes,Operations,TotalNodeSum,TotalTransSum).
2481 check_totals(Nodes,Operations,TotalNodeSum,TotalTransSum) :-
2482 ( Nodes=TotalNodeSum -> true
2483 ;
2484 add_error(probcli,'Unexpected number of nodes: ',TotalNodeSum),
2485 add_error(probcli,'Expected: ',Nodes),error_occurred(coverage)),
2486 ( Operations=TotalTransSum -> true
2487 ;
2488 add_error(probcli,'Unexpected number of transitions: ',TotalTransSum),
2489 add_error(probcli,'Expected: ',Operations),error_occurred(coverage)).
2490
2491
2492 :- use_module(bmachine,[b_machine_statistics/2, b_get_main_filename/1, b_get_all_used_filenames/1,get_full_b_machine_sha_hash/1]).
2493 :- use_module(tools_strings,[get_hex_bytes/2]).
2494 cli_print_machine_info(statistics) :-
2495 b_machine_name(Name),
2496 %(b_get_main_filename(File) -> true ; File=unknown),
2497 format('Machine statistics for ~w:~n',[Name]),
2498 findall(Key/Nr,b_machine_statistics(Key,Nr),L),
2499 maplist(prob_cli:print_keynr,L),!.
2500 cli_print_machine_info(files(WithSha)) :-
2501 b_machine_name(Name),
2502 (WithSha = with_sha -> Msg2='and SHA1 ' ; Msg2=''),
2503 format('Files ~wused for machine ~w:~n',[Msg2,Name]),
2504 b_get_all_used_filenames(Files),
2505 maplist(prob_cli:print_individual_file(WithSha),Files),!.
2506 cli_print_machine_info(hash(Expected)) :-
2507 b_machine_name(MainName), % to do: findall machines and hashes
2508 get_full_b_machine_sha_hash(HashBytes),
2509 get_hex_bytes(HashBytes,Hash),
2510 format('SHA hash for machine ~w = ~s~n',[MainName,Hash]),!,
2511 write_xml_element_to_log(machine_hash,[hash/Hash]),
2512 (var(Expected) -> true
2513 ; atom_codes(Expected,Hash)
2514 -> format_with_colour_nl(user_output,[green],'Machine hash for ~w matches provided hash.',[MainName])
2515 ; add_error(machine_hash_check,'Unexpected machine hash, expected: ',Expected)).
2516 cli_print_machine_info(Kind) :- add_error(machine_stats,'Could not obtain machine information:',Kind).
2517 print_keynr(Key/Nr) :- format(' ~w : ~w~n',[Key,Nr]).
2518 :- use_module(extension('probhash/probhash'),[raw_sha_hash_file/3]).
2519 :- use_module(tools_strings,[get_hex_bytes/2]).
2520 print_individual_file(with_sha,File) :- Span = machine_info,
2521 raw_sha_hash_file(File,Term,Span),
2522 get_hex_bytes(Term,SHAHexCodes),
2523 format(' ~w, ~s~n',[File,SHAHexCodes]).
2524 print_individual_file(_,File) :- format(' ~w~n',[File]).
2525
2526 check_machine_file_sha(File,ExpectedHash) :- Span = check_machine_file_sha,
2527 get_full_machine_file_path(File,AbsFile),
2528 raw_sha_hash_file(AbsFile,Term,Span),
2529 get_hex_bytes(Term,SHAHexCodes), atom_codes(ExpectedHash,ExpectedShaCodes),
2530 (SHAHexCodes=ExpectedShaCodes
2531 -> format_with_colour_nl(user_output,[green],'Checked SHA1 hash for file ~w is ~s',[AbsFile,SHAHexCodes])
2532 ; add_error(check_machine_file_sha,'Unexpected SHA1 hash of file:',AbsFile),
2533 format_with_colour_nl(user_error,[orange],'! Expected: ~w~n! Actual : ~s',[ExpectedHash,SHAHexCodes])
2534 ).
2535
2536 :- use_module(bmachine,[get_machine_file_number/4, b_absolute_file_name_relative_to_main_machine/2]).
2537 :- use_module(probsrc(tools), [get_parent_directory/2]).
2538 get_full_machine_file_path(File,AbsFile) :-
2539 get_modulename_filename(File,Name),
2540 (get_filename_extension(File,ExtF), ExtF \= ''
2541 -> true ; debug_format(19,'No extension provided for file ~w~n',[File])),
2542 (get_machine_file_number(Name,ExtF,_Nr,AbsFile)
2543 -> get_parent_directory(File,Parent),
2544 (Parent='' -> true % no path provided
2545 ; File=AbsFile -> true % full path provided
2546 ; b_absolute_file_name_relative_to_main_machine(File,AbsFile) -> true % consistent partial path provided
2547 ; add_error(check_machine_file_sha,'File path (relative to main model) is inconsistent with used file:',File),
2548 b_absolute_file_name_relative_to_main_machine(File,AbsFile1),
2549 format_with_colour_nl(user_error,[orange],'! Full path in -check_machine_file_sha:~n ~w',[AbsFile1]),
2550 format_with_colour_nl(user_error,[orange],'! File actually used in B main model :~n ~w',[AbsFile])
2551 )
2552 ; get_machine_file_number(_,_,_,_) ->
2553 add_error(check_machine_file_sha,'Could not locate the file for:',File),
2554 b_absolute_file_name_relative_to_main_machine(File,AbsFile)
2555 ; add_message(check_machine_file_sha,'No main B machine loaded for, converting to absolute path: ',File),
2556 absolute_file_name(File,AbsFile)
2557 ).
2558
2559 :- use_module(tools,[get_tail_filename/2]).
2560 xml_log_machine_statistics :-
2561 animation_mode(Major),
2562 (animation_minor_mode(Minor) -> true ; Minor=none),
2563 write_xml_element_to_log(animation_mode,[major/Major,minor/Minor]),
2564 (b_or_z_mode, b_machine_name(Main)
2565 -> findall(Key/Nr,b_machine_statistics(Key,Nr),BMachStats),
2566 (b_get_main_filename(MainFile) -> get_tail_filename(MainFile,TailFile) ; TailFile = unknown),
2567 write_xml_element_to_log(b_machine_statistics,[machine_name/Main, tail_filename/TailFile|BMachStats])
2568 ; true).
2569
2570 cli_print_junit_results :-
2571 junit_mode(S),!,
2572 statistics(runtime,[E,_]),
2573 T is E - S,
2574 create_and_print_junit_result([],probcli,T,pass).
2575 cli_print_junit_results.
2576
2577 :- use_module(visbsrc(visb_visualiser),[load_visb_file/1, tcltk_perform_visb_click_event/1]).
2578 :- use_module(visbsrc(visb_html_export),[generate_visb_html_for_history/2]).
2579 cli_visb_history(JSONFile,HTMLFile,Options) :-
2580 (load_visb_file(JSONFile)
2581 -> ifm_option_set(visb_click(SVGID),tcltk_perform_visb_click_event(SVGID)), % simulate clicks if requested
2582 generate_visb_html_for_history(HTMLFile,Options)
2583 ; true). % errors already reported
2584
2585 cli_print_history(HistFile) :-
2586 findall( O, option(history_option(O)), Options),
2587 debug_println(9,writing_history_to_file(HistFile)),
2588 (select(trace_file,Options,ROpt) -> tcltk_save_history_as_trace_file(prolog,ROpt,HistFile) % save as Prolog trace file for replay with -t
2589 ; select(json,Options,ROpt) -> tcltk_save_history_as_trace_file(json,ROpt,HistFile) % save for replay with ProB2 UI
2590 ; write_history_to_file(HistFile,Options) -> true
2591 ; add_error(history,'Writing history to file failed: ',HistFile)).
2592
2593 cli_print_values(ValuesFilename) :-
2594 (write_values_to_file(ValuesFilename) -> true ; add_error(sptxt,'Writing values to file failed: ',ValuesFilename)).
2595 cli_print_all_values(ValuesDirname) :-
2596 (write_all_values_to_dir(ValuesDirname) -> true ; add_error(sstxt,'Writing all values to directory failed: ',ValuesDirname)).
2597
2598 :- use_module(probltlsrc(trace_generator),[generate_all_traces_until/4]).
2599
2600 cli_generate_all_traces_until(LTL_Stop_AsAtom,FilePrefix) :-
2601 generate_all_traces_until(LTL_Stop_AsAtom,FilePrefix,Result,NrTracesGenerated),
2602 format_with_colour_nl(user_error,[blue],'Generated ~w traces, result=~w~n',[NrTracesGenerated,Result]).
2603
2604 :- dynamic probcli_time_stamp/1.
2605 generate_time_stamp(NOW,TS) :- retractall(probcli_time_stamp(_)),
2606 now(NOW),
2607 current_prolog_flag(argv,ArgV),term_hash(ArgV,Hash),
2608 Rnd is Hash mod 1000,
2609 % random(0,1000,Rnd), always returns 216 % TO DO: try to get milliseconds from some library function
2610 TS is (NOW*1000)+Rnd,
2611 assertz(probcli_time_stamp(TS)).
2612 update_time_stamp(NOW1) :- retractall(probcli_time_stamp(_)),
2613 assertz(probcli_time_stamp(NOW1)).
2614
2615 %get_errors :- \+ real_error_occurred,!, (get_error(_Source,_Msg) -> print('*** Warnings occurred'),nl ; true), reset_errors.
2616 get_errors :-
2617 (get_preference(view_probcli_errors_using_bbresults,true)
2618 -> tools_commands:show_errors_with_bb_results([current]) ; true),
2619 get_error_sources.
2620
2621 get_error_sources :- get_error_with_span(ErrSource,Msg,Span), !,
2622 error_occurred_with_msg(ErrSource,Msg,Span),
2623 findall(1,get_error(ErrSource,_),L), length(L,Nr),
2624 (Nr>0 -> N1 is Nr+1, get_error_category_and_type(ErrSource,Cat,Type),
2625 % TODO: do not print if error is optional/expected
2626 (Type=error
2627 -> format_error_with_nl('*** Occurences of this ~w error: ~w',[Cat, N1])
2628 ; format_error_with_nl('*** Occurences of this ~w warning: ~w',[Cat, N1])
2629 ),
2630 write_xml_element_to_log(multiple_errors_occurred,[category/Cat,(type)/Type,number/N1])
2631 ; true),
2632 get_error_sources.
2633 get_error_sources.
2634
2635 :- use_module(state_space,[state_error/3, invariant_violated/1, time_out_for_invariant/1, time_out_for_assertions/1, time_out_for_node/3]).
2636 ?get_state_space_errors :- option(strict_raise_error),
2637 !,
2638 (\+ option(no_invariant_violations),invariant_violated(ID)
2639 -> (option_verbose ->
2640 format('Invariant violation in state with id = ~w~n',[ID]),
2641 b_interpreter:analyse_invariant_for_state(ID) % caused issue for test 1076
2642 ; format('Invariant violation in state with id = ~w (use -v to print more details)~n',[ID])
2643 ),
2644 error_occurred(invariant_violation)
2645 ; true),
2646 (state_error(_,_,abort_error(TYPE,Msg,_,Span)) -> error_occurred(TYPE,error,Span,Msg) ; true),
2647 get_state_errors(_).
2648 get_state_space_errors.
2649
2650 get_state_errors(ID) :- state_error(ID,_,X), X\=invariant_violated, X\=abort_error(_,_,_,_),
2651 create_state_error_description(X,Msg),error_occurred(Msg),fail.
2652 get_state_errors(ID) :- time_out_for_invariant(ID),error_occurred(time_out_for_invariant),fail.
2653 get_state_errors(ID) :- time_out_for_assertions(ID),error_occurred(time_out_for_assertions),fail.
2654 get_state_errors(ID) :- time_out_for_node(ID,_,time_out),error_occurred(time_out),fail.
2655 get_state_errors(ID) :-
2656 time_out_for_node(ID,_,virtual_time_out(_)), %print(virtual_time_out_for_node(ID)),nl,
2657 error_occurred(virtual_time_out),fail.
2658 get_state_errors(_).
2659
2660
2661 create_state_error_description(eventerror(Event,Error,_),Description) :- !,
2662 functor(Error,Functor,_),
2663 ajoin(['event_error:',Event,':',Functor],Description).
2664 create_state_error_description(StateError,Description) :-
2665 functor(StateError,Functor,_),
2666 atom_concat('state_error:',Functor,Description).
2667
2668 % require a real machine to be loaded
2669 check_loaded_not_empty(Action) :-
2670 file_loaded(true,'$$empty_machine'),!,
2671 add_error(probcli,'No file specified; cannot perform command: ',Action),
2672 error_occurred(loading),fail.
2673 check_loaded_not_empty(Action) :- check_loaded(Action).
2674
2675 check_loaded(Action) :-
2676 ( file_loaded(true) -> true
2677 ; file_loaded(error) -> fail /* we have already generated error message */
2678 ;
2679 add_error(probcli,'No file specified; cannot perform action: ',Action),
2680 error_occurred(loading),fail).
2681
2682 :- dynamic loaded_main_file/2.
2683 loaded_main_file(File) :- loaded_main_file(_Ext,File).
2684
2685 :- use_module(tools,[get_filename_extension/2]).
2686 load_main_file(MainFile,NOW,Already_FullyProcessed) :- retractall(loaded_main_file(_,_)),
2687 debug_print(20,'% Loading: '), debug_println(20,MainFile),
2688 writeln_log_time(loading(NOW,MainFile)),
2689 get_filename_extension(MainFile,Ext),
2690 debug_println(6,file_extension(Ext)),
2691 file_extension_can_be_loaded(Ext,MainFile),
2692 start_probcli_timer(Timer),
2693 load_spec_file(Ext,MainFile,Already_FullyProcessed),
2694 stop_probcli_debug_timer(Timer,'% Finished loading file after'),
2695 (Already_FullyProcessed==true -> true
2696 ; assertz(loaded_main_file(Ext,MainFile))).
2697
2698 known_spec_file_extension('P',xtl).
2699 known_spec_file_extension(als,alloy).
2700 known_spec_file_extension(csp,csp).
2701 known_spec_file_extension(cspm,csp).
2702 known_spec_file_extension(def,b).
2703 known_spec_file_extension(eval,b_eval).
2704 known_spec_file_extension(eventb,eventb).
2705 known_spec_file_extension(fuzz,z).
2706 known_spec_file_extension(imp,b).
2707 known_spec_file_extension(mch,b).
2708 known_spec_file_extension(pb,b).
2709 known_spec_file_extension(pl,xtl).
2710 known_spec_file_extension(pla,alloy). % Prolog AST of Alloy translation
2711 known_spec_file_extension(probpo,sequent_prover). % disprover PO files
2712 known_spec_file_extension(prob,b).
2713 known_spec_file_extension(ref,b).
2714 known_spec_file_extension(rmch,b_rules).
2715 known_spec_file_extension(smt,smt).
2716 known_spec_file_extension(smt2,smt).
2717 known_spec_file_extension(sys,b).
2718 known_spec_file_extension(tex,z).
2719 known_spec_file_extension(tla,tla).
2720 known_spec_file_extension(zed,z).
2721
2722 :- use_module(pathes_extensions_db, [load_spec_file_requires_extension/2]).
2723 :- use_module(pathes_lib, [available_extension/1, unavailable_extension/2]).
2724 % check if we can load the file extension given available ProB extensions
2725 file_extension_can_be_loaded(FileExt,_) :- known_spec_file_extension(FileExt,Mode),
2726 load_spec_file_requires_extension(Mode,ProBExtension),
2727 unavailable_extension(ProBExtension,Reason),!,
2728 ajoin(['File with ending .', FileExt,' cannot be loaded because extension not available (',Reason,'):'],Msg),
2729 add_error(probcli,Msg,ProBExtension),
2730 fail.
2731 file_extension_can_be_loaded(_,_). % assume ok; if unrecognized we will load as B machine
2732
2733 %load_spec_file('pl',MainFile) :- !, load_cspm_spec_from_pl_file(MainFile). % no longer needed ?
2734 load_spec_file('pl',MainFile) :- !, load_xtl_spec_from_prolog_file(MainFile).
2735 load_spec_file('csp',MainFile) :- !, load_cspm_spec_from_cspm_file(MainFile).
2736 load_spec_file('cspm',MainFile) :- !, load_cspm_spec_from_cspm_file(MainFile).
2737 load_spec_file('P',MainFile) :- !, load_xtl_spec_from_prolog_file(MainFile).
2738 load_spec_file('p',MainFile) :- !, load_xtl_spec_from_prolog_file(MainFile). % sometimes windows is confused about the upper case letter....
2739 load_spec_file('probpo',MainFile) :- !, load_xtl_spec_from_prolog_file(MainFile). % load (Disprover) PO files in sequent_prover mode
2740 load_spec_file('eventb',MainFile) :- !, load_eventb_file(MainFile).
2741 load_spec_file('v',MainFile) :- !,
2742 print('Warning: .v proof rule file format no longer supported, use -eval_rule_file FILE'),nl,
2743 % but even that may not work; some older rule files required predicate variables
2744 load_b_file_with_options(MainFile). % Siemens Rule File; now use -eval_rule_file
2745 load_spec_file('prob',MainFile) :- !,load_prob_file_with_options(MainFile). % .prob files
2746 load_spec_file('mch',MainFile) :- !,load_b_file_with_options(MainFile).
2747 load_spec_file('sys',MainFile) :- !,load_b_file_with_options(MainFile).
2748 load_spec_file('ref',MainFile) :- !,load_b_file_with_options(MainFile).
2749 load_spec_file('imp',MainFile) :- !,load_b_file_with_options(MainFile).
2750 load_spec_file('rmch',MainFile) :- !,load_b_file_with_options(MainFile).
2751 load_spec_file('def',MainFile) :- !,load_b_file_with_options(MainFile). % .def DEFINITIONS file
2752 load_spec_file('fuzz',MainFile) :- !,tcltk_open_z_file(MainFile).
2753 load_spec_file('tex',MainFile) :- !,tcltk_open_z_tex_file(MainFile).
2754 load_spec_file('zed',MainFile) :- !,tcltk_open_z_tex_file(MainFile). % proz .zed file
2755 load_spec_file('als',MainFile) :- !,tcltk_open_alloy_file(MainFile).
2756 load_spec_file('pla',MainFile) :- !,tcltk_open_alloy_prolog_ast_file(MainFile). % maybe we should detect .als.pl
2757 load_spec_file('tla',MainFile) :- !, load_tla_file(MainFile).
2758 load_spec_file('cnf',MainFile) :- !, load_cnf_file_with_options(MainFile).
2759 load_spec_file('eval',File) :- !, % .eval file
2760 cli_set_empty_machine,
2761 assertz(option(eval_string_or_file(file(default),File,exists,_,norecheck))).
2762 load_spec_file('pb',File) :- !, cli_set_empty_machine, % .pb file
2763 cli_set_empty_machine,
2764 assertz(option(eval_string_or_file(file(default),File,exists,_,norecheck))).
2765 %load_spec_file('pml',MainFile) :- !,parsercall:call_promela_parser(MainFile),
2766 % parsercall:promela_prolog_filename(MainFile,PrologFile),
2767 % println_silent(consulting(PrologFile)),
2768 % tcltk_open_promela_file(PrologFile).
2769 load_spec_file(EXT,MainFile) :- print_error('Unknown file extension, assuming B machine:'),
2770 print_error(EXT),
2771 load_b_file_with_options(MainFile).
2772
2773 load_spec_file(EXT,MainFile, Already_FullyProcessed) :-
2774 (EXT='probpo' ; EXT= 'pl'),
2775 % we could check: xtl_interface:check_is_po_file(MainFile,EXT); adds warning for .pl files
2776 load_pl_file_with_disprover(MainFile), !,
2777 Already_FullyProcessed=true,
2778 printsilent('Processing PO file: '),printsilent(MainFile),nls,
2779 load_po_file(MainFile),
2780 (option(timeout(TO)) -> set_disprover_timeout(TO) ; reset_disprover_timeout),
2781 (option(disprover_options(L)) -> set_disprover_options(L) ; set_disprover_options([])),
2782 println_silent('Running ProB Disprover'),
2783 run_disprover_on_all_pos(Summary),
2784 print_disprover_stats,
2785 accumulate_infos(disprover,[po_files-1|Summary]),
2786 get_errors,
2787 (option(cli_check_disprover_result(Infos)) -> check_required_infos(Infos,Summary,load_po_file)
2788 ; option(strict_raise_error) -> check_required_infos([false-0,unknown-0,failure-0],Summary,load_po_file)
2789 % TO DO: provide way for user to specify expected info
2790 ; true),
2791 cli_process_options_for_alrady_fully_processed_file(MainFile),
2792 clear_loaded_machines.
2793 load_spec_file(EXT,MainFile,Already_FullyProcessed) :- (EXT='smt2' ; EXT= 'smt'), !,
2794 Already_FullyProcessed=true,
2795 printsilent('Processing SMT file: '),printsilent(MainFile),nls,
2796 (option(eval_repl([])) -> Opts = [repl] ; Opts=[]),
2797 start_probcli_timer(Timer),
2798 get_total_number_of_errors(TE1),
2799 smtlib2_file(MainFile,Opts),
2800 get_probcli_elapsed_walltime(Timer,WallTime),
2801 get_probcli_elapsed_runtime(Timer,RunTime),
2802 get_total_number_of_errors(TE2), Errs is TE2-TE1,
2803 get_smtlib2_result_infos(Result),
2804 accumulate_file_infos(MainFile,smtlib2_file,[file-1,runtime-RunTime,walltime-WallTime,errors-Errs|Result]).
2805 load_spec_file(EXT,F,false) :- load_spec_file(EXT,F).
2806
2807 % check if we should load a pl file using the disprover runner; if not we will load it in XTL mode
2808 load_pl_file_with_disprover(_MainFile) :- option(disprover_options(_)).
2809 load_pl_file_with_disprover(_MainFile) :- option(cli_check_disprover_result(_)).
2810 load_pl_file_with_disprover(_) :-
2811 \+ computeOperations_for_root_required,
2812 \+ (option(A), option_requires_all_properties(A)).
2813
2814
2815 load_cnf_file_with_options(File) :-
2816 get_b_load_options(Options),
2817 load_cnf_file(File,Options) .
2818
2819 get_b_load_options(Options) :-
2820 (option(release_java_parser) -> Options = [release_java_parser,use_fastread]
2821 ; option(fast_read_prob) -> Options = [use_fastread] % use fastread for large .prob files
2822 ; Options = []).
2823 % TO DO: automatically release if no option requires parsing and no more file uses it;
2824 % or print warning if release will affect other options like -repl (DEFINITIONS not available,...)
2825
2826 load_prob_file_with_options(File) :-
2827 get_b_load_options(Options),
2828 load_prob_file(File,Options).
2829 load_b_file_with_options(File) :-
2830 get_b_load_options(Options),
2831 load_b_file(File,Options).
2832
2833 % do not perform -execute_all if no parameters provided
2834 do_not_execute_automatically('pl').
2835 do_not_execute_automatically('smt2').
2836
2837 test_kodkod_and_exit(MaxResiduePreds,NOW) :-
2838 start_animation_without_computing,
2839 test_kodkod(MaxResiduePreds),
2840 halt_prob(NOW,0).
2841
2842 compare_kodkod_performance1(KPFile,Iterations,NOW) :-
2843 start_animation_without_computing,
2844 compare_kodkod_performance(KPFile,Iterations),
2845 halt_prob(NOW,0).
2846
2847 :- use_module(parsercall,[check_java_version/2,get_parser_version/1, ensure_console_parser_launched/0,
2848 connect_to_external_console_parser_on_port/1]).
2849 check_java_version :- check_java_version(V,Result),
2850 format('Result of checking Java version:~n ~w~n',[V]),
2851 (Result=compatible -> check_parser_version
2852 ; add_error(check_java_version,V)).
2853
2854 check_parser_version :- get_parser_version(PV),!,
2855 format(' ProB B Java Parser available in version: ~w.~n',[PV]). % will also launch parser
2856 check_parser_version :- add_error(check_parser_version,'Cannot start Java B Parser to obtain version number').
2857
2858 :- use_module(pathes_lib,[install_lib_component/2]).
2859 install_prob_lib(Lib,Opts) :- install_lib_component(Lib,Opts).
2860 load_prob_external_library(ModuleFile) :- consult_new_external_function_library(ModuleFile).
2861
2862 print_version(Kind) :- print_version(Kind,user_output).
2863
2864 print_version(short,Stream) :- print_short_version(Stream).
2865 print_version(cpp,Stream) :- print_cpp_version(Stream).
2866 print_version(java,Stream) :- print_java_version(Stream).
2867 print_version(full,Stream) :- print_full_version(Stream).
2868 print_version(full_verbose,Stream) :- print_full_version(Stream,verbose).
2869 print_version(host,Stream) :- print_host_version(Stream).
2870 print_version(lib,Stream) :- check_lib_contents(Stream,verbose).
2871
2872 :- use_module(version).
2873 print_short_version(Stream) :-
2874 version(V1,V2,V3,Suffix),revision(Rev),
2875 format(Stream,'VERSION ~p.~p.~p-~p (~p)~N',[V1,V2,V3,Suffix,Rev]).
2876
2877 :- use_module(parsercall,[get_parser_version/1, get_java_command_path/1, get_java_fullversion/1]).
2878 :- use_module(pathes_lib,[check_lib_contents/2]).
2879 print_full_version(Stream) :-
2880 (option_verbose ->
2881 (option_very_verbose
2882 -> print_full_version(Stream,very_verbose)
2883 ; print_full_version(Stream,verbose)
2884 )
2885 ; print_full_version(Stream,normal)
2886 ).
2887 print_full_version(Stream,Verbose) :-
2888 format(Stream,'ProB Command Line Interface~n',[]),
2889 print_probcli_version(Stream),
2890 ( Verbose=normal -> true
2891 ;
2892 current_prolog_flag(system_type,SysType),
2893 format(Stream,' Prolog System Type: ~p~N', [SysType]), % development or runtime
2894 safe_absolute_file_name(prob_home('.'),AppDir),
2895 format(Stream,' Application Path: ~p~N', [AppDir]),
2896 print_host_version(Stream),
2897 print_java_version(Stream),
2898 print_cpp_version(Stream),
2899 (Verbose = very_verbose
2900 -> print_prolog_flags(Stream), print_extensions(Stream), print_modules(Stream),
2901 check_lib_contents(Stream,verbose)
2902 ; check_lib_contents(Stream,silent)
2903 )
2904 ), print_compile_time_flags.
2905
2906 print_java_version(Stream) :-
2907 (get_java_command_path(JavaPath)
2908 -> format(Stream,' Java Runtime: ~p~N', [JavaPath]),
2909 (get_java_fullversion(JavaVersion)
2910 -> format(Stream,' Java Version: ~s~N', [JavaVersion])
2911 ; format(Stream,' Java Version: *** not available ***~N',[])
2912 ),
2913 (get_parser_version(ParserVersion)
2914 -> format(Stream,' Java Parser: ~p~N', [ParserVersion])
2915 ; format(Stream,' Java Parser: *** not available ***~N',[])
2916 )
2917 ; format(Stream,' Java Runtime: *** not available ***~N',[])
2918 ).
2919
2920 :- use_module(tools_platform, [host_platform/1, host_processor/1]).
2921 print_host_version(Stream) :-
2922 host_platform(HP),
2923 host_processor(Proc),
2924 (platform_is_64_bit -> Bits=64 ; Bits=32),
2925 format(Stream,' Host Processor: ~w (~w bits)~n Host Operating System: ~w~n',[Proc,Bits,HP]).
2926
2927
2928 print_probcli_version(Stream) :-
2929 full_version_str(VersStr),
2930 revision(Rev), lastchangeddate(LCD),
2931 current_prolog_flag(dialect, Dialect),
2932 (Dialect= swi, current_prolog_flag(version_git,PV) -> true
2933 ; current_prolog_flag(version,PV)
2934 ),
2935 format(Stream,' VERSION ~w (~p)~N ~p~N Prolog (~w): ~p~N',
2936 [VersStr,Rev,LCD,Dialect, PV]).
2937
2938
2939 :- use_module(compile_time_flags,[compile_time_flags/1, relevant_prolog_flags/1]).
2940 :- use_module(extension('regexp/regexp'),[get_cpp_version/1]).
2941 print_compile_time_flags :-
2942 compile_time_flags(list(Flags)),
2943 (Flags=[], \+ option_verbose -> true ; format(' COMPILE TIME FLAGS: ~w~N',[Flags])).
2944 print_prolog_flags(Stream) :-
2945 relevant_prolog_flags(Flags),
2946 format(Stream,' PROLOG FLAGS: ~w~N',[Flags]).
2947 print_extensions(Stream) :- findall(E,available_extension(E),Es),
2948 format(Stream,' EXTENSIONS: ~w~N',[Es]).
2949 print_cpp_version(Stream) :-
2950 available_extension(regexp_extension),!,
2951 get_cpp_version(V),
2952 format(Stream,' C++ Version for extensions: ~w~n',[V]).
2953 print_cpp_version(_).
2954 print_modules(Stream) :- findall(M,current_module(M),Ms), sort(Ms,SMs),
2955 format(Stream,' PROLOG MODULES: ~w~N',[SMs]).
2956
2957 print_logo :-
2958 % should be improved considerably; doesn't look very nice yet on macOS terminal due to line separation
2959 % â–„â–„â–„â–„ â–„â–„â–„â–„
2960 % â–ˆ â–ˆ â–ˆ â–ˆ
2961 % █▀▀▀ ▄ ▄▄▄ █▀▀▀▄
2962 % █ █ █▄█ █▄▄▄▀
2963 format_with_colour_nl(user_output,[blue],' ~s',[[9604,9604,9604,9604,32,32,32,32,32,32,32,9604,9604,9604,9604]]),
2964 format_with_colour_nl(user_output,[blue],' ~s',[[9608,32,32,32,9608,32,32,32,32,32,32,9608,32,32,32,9608]]),
2965 format_with_colour_nl(user_output,[blue],' ~s',[[9608,9600,9600,9600,32,9604,32,9604,9604,9604,32,9608,9600,9600,9600,9604]]),
2966 format_with_colour_nl(user_output,[blue],' ~s',[[9608,32,32,32,9608,32,32,9608,9604,9608,32,9608,9604,9604,9604,9600]]).
2967
2968 print_help :-
2969 print_version(full),
2970 print('Usage: probcli FILE [OPTIONS]'),nl,
2971 print(' OPTIONS are: '),nl,
2972 print(' -mc Nr model check; checking at most Nr states'),nl,
2973 print(' -model_check model check without limit on states explored'),nl,
2974 ( \+ option_verbose ->
2975 print(' -noXXX XXX=dead,inv,goal,ass (for model check)'),nl % -nodead, -noinv, -nogoal, -noass
2976 ;
2977 print(' -nodead do not look for deadlocks (for model check, animate, execute)'),nl,
2978 print(' -noinv do not look for invariant violations (for model check, animate, execute)'),nl,
2979 print(' -nogoal do not look for GOAL predicate (for model check, execute)'),nl,
2980 print(' -noass do not look for ASSERTION violations (for model check, execute)'),nl
2981 ),
2982 print(' -bf proceed breadth-first (default is mixed bf/df)'),nl,
2983 print(' -df proceed depth-first'),nl,
2984 print(' -mc_mode M M=hash,heuristic,random,dlk,breadth-first,depth-first,mixed,size'),nl, % dlk stands for out_degree_hash
2985 print(' -global_time_out N total timeout in ms for model/refinement checking and'),nl,
2986 print(' and execute steps and disprover checks'),nl,
2987 print(' -disable_timeout disable timeouts for operations, invariants,....'),nl, % speeds up mc
2988 print(' -t trace check (associated .trace file must exist)'),nl,
2989 print(' -trace_replay K F replay trace file F in format K (prolog,json,B)'),nl,
2990 print(' -init initialise specification'),nl,
2991 print(' -cbc OPNAME constraint-based invariant checking for an operation'),nl,
2992 print(' -cbc_assertions_after OPNAME constraint-based checking whether an operation can violate the dynamic ASSERTIONS'),nl,
2993 print(' (you can also use OPNAME=all)'),nl,
2994 print(' -cbc_deadlock constraint-based deadlock checking'),nl,
2995 ( \+ option_verbose -> true ;
2996 print(' -cbc_deadlock_pred PRED as above but with additional predicate'),nl
2997 ),
2998 print(' -cbc_assertions constraint-based static assertion checking'),nl,
2999 print(' -cbc_refinement constraint-based static refinement checking'),nl,
3000 print(' -cbc_sequence S constraint-based search for sequence of operations'),nl,
3001 print(' -cbc_sequence_all S as above but find all solutions'),nl,
3002 print(' -check_cbc_sequence_solutions Nr check number of solutions found by -cbc_sequence_all'),nl,
3003 print(' -strict raise error if model-checking finds counter example'),nl,
3004 print(' or trace checking fails or any error state found'),nl,
3005 print(' -expcterr ERR expect error to occur (ERR=cbc,mc,ltl,...)'),nl,
3006 print(' -animate Nr random animation (max. Nr steps)'),nl,
3007 print(' -animate_all random animation until a deadlock is reached'),nl,
3008 print(' -animate_until_ltl P random animation until LTL property satisfied on trace'),nl,
3009 print(' -animate_until_ltl_state_property P until state satisfies LTL state property)'),nl,
3010 print(' -animate_stats provide feedback which operations are animated or executed'),nl,
3011 print(' -execute Nr execute specification (maximally Nr steps)'),nl,
3012 print(' in contrast to -animate: stops at first operation found, is deterministic,'),nl,
3013 print(' does not store intermediate states and does not use TIME_OUT preference'),nl,
3014 print(' -execute_all execute until a deadlock, direct loop, goal or error is reached'),nl,
3015 print(' -execute_monitor monitor performance of execute'),nl,
3016 print(' -his File write history to File'),nl,
3017 print(' -his_option O additional option when writing a history (show_init,show_states,json,trace_file)'),nl,
3018 print(' -sptxt File save constants and variable values of last discovered state to File'),nl,
3019 print(' -sstxt Dir save constants and variable values of all discovered states to files in Dir'),nl,
3020 print(' -cache Directory automatically save constants and operations to files to avoid recomputation'),nl,
3021 print(' -det_check check if animation steps are deterministic'),nl,
3022 print(' -det_constants only check if SETUP_CONSTANTS step is deterministic'),nl,
3023 ( \+ option_verbose -> true ;
3024 print(' -i interactive animation. Only for interactive sessions,'),nl,
3025 print(' the output can arbitrarily change in future versions. '),nl,
3026 print(' Do not build automatic tools using the interactive mode'),nl
3027 ),
3028 print(' -repl start interactive read-eval-loop'),nl,
3029 print(' -eval "E" evaluate expression or predicate'),nl,
3030 print(' -eval_file FILE evaluate expression or predicate from file'),nl,
3031 print(' -c print coverage statistics'),nl,
3032 print(' -cc Nr Nr print and check coverage statistics'),nl,
3033 print(' -vacuity_check look for vacuous implications in invariant'),nl,
3034 print(' -cbc_redundant_invariants Nr find redundant invariants, expecting Nr'),nl, % Nr exepcted
3035 print(' -statistics print memory and other statistics at the end'),nl,
3036 print(' -p PREF Val set preference to value'),nl,
3037 print(' -prefs FILE set preferences from Prolog file'),nl,
3038 print(' -pref_group G S set group G of preferences to predefined value set S'),nl,
3039 print(' -card GS Val set cardinality (aka scope) of B deferred set'),nl,
3040 print(' -goal "PRED" set GOAL predicate for model checker'),nl,
3041 print(' -check_goal check GOAL (after -mc, -t, or -animate)'),nl,
3042 print(' -scope "PRED" set scope predicate for model checker'),nl,
3043 print(' (only states satsifying this predicate will be examined)'),nl,
3044 print(' -property "PRED" virtually add predicate to PROPERTIES'),nl,
3045 print(' -s Port start socket server on given port'),nl,
3046 print(' -ss start socket server on port 9000'),nl,
3047 print(' -sf start socket server on some free port'),nl,
3048 print(' -l LogFile log activities in LogFile'),nl,
3049 print(' -ll log activities in /tmp/prob_cli_debug.log'),nl,
3050 print(' -logxml LogFile log activities in XML LogFile'),nl,
3051 print(' -logxml_write_ids P write variables/constants starting with P to XML LogFile'),nl,
3052 print(' -pp FILE pretty-print internal representation to file (or user_output)'), nl,
3053 print(' -ppf FILE like -pp, but force printing of all type infos'),nl,
3054 print(' -ppAB FILE like -ppf, but make output readable by Atelier-B'),nl,
3055 print(' -ppB FILE pretty-print Event-B model to file in valid B syntax'),nl,
3056 ( \+ option_verbose -> true ;
3057 print(' -ppi FILE pretty-print B model main file with indenatation'),nl,
3058 print(' -indent_b_file BFILE FILE pretty-print BFILE to FILE with indenatation'),nl,
3059 print(' -reformat_b_file BFILE FILE reformat BFILE to FILE (may insert newlines)'),nl,
3060 print(' -pp_pl_file PLFILE FILE indent Prolog PLFILE to FILE'),nl
3061 ),
3062 print(' -v verbose'),nl,
3063 ( \+ option_verbose -> true ;
3064 print(' -vv very verbose'),nl
3065 ),
3066 print(' -mc_with_tlc model check using TLC (see also TLC_WORKERS preference)'),nl,
3067 print(' -mc_with_lts_sym model check using LTSmin (symbolic)'),nl,
3068 print(' -mc_with_lts_seq model check using LTSmin (sequential)'),nl,
3069
3070 ( \+ option_verbose -> true ;
3071 print(' -ltsmin_option OPT set option for LTSmin (e.g, por)'),nl,
3072 print(' -ltsmin_ltl_output FILE set output file for LTSMin'),nl,
3073 print(' -symbolic_model_check ALGO ALGO is bmc, kinduction, ctigar, ic3'),nl,
3074 print(' -enabling_analysis_csv FILE perform operation enabling analysis'),nl,
3075 print(' -feasibility_analysis perform operation feasibility analysis'),nl,
3076 print(' -feasibility_analysis_csv TIMEOUT FILE write feasibility result to file'),nl,
3077 print(' -read_write_matrix show read/write matrix for operations'),nl
3078 ),
3079 print(' -version print version information (-svers for short info)'),nl,
3080 print(' -check_java_version check that Java version compatible with ProB parser'),nl,
3081 print(' -assertions check ASSERTIONS'),nl,
3082 print(' -main_assertions check ASSERTIONS from main file only'),nl,
3083 print(' -properties check PROPERTIES'),nl,
3084 print(' -ccache Dir like -cache Dir but create directoy if it does not exist'),nl,
3085 print(' -show_cache show contents of cache'),nl,
3086 print(' -show_cache_verbose show contents of cache in more detail'),nl,
3087 print(' -cache_statistics show statistics about cache reuse'),nl,
3088 print(' -clear_cache clear the cache'),nl,
3089 print(' -clear_cache_for M clear the cache for machine M'),nl,
3090 print(' -show_inclusion_hierarchy useful to determine order for pre-populating cache for constants'),nl,
3091 print(' -ltlfile F check LTL formulas in file F'),nl,
3092 print(' -ltlassertions check LTL assertions (in DEFINITIONS)'),nl,
3093 print(' -ltllimit L explore at most L states when model-checking LTL or CTL'),nl,
3094 print(' -ltlformula \"F\" check the LTL formula F'),nl,
3095 print(' -ctlformula \"F\" check the CTL formula F'),nl,
3096 print(' -save File save state space for later refinement check'),nl,
3097 print(' -refchk File refinement check against previous saved state space'),nl,
3098 print(' -mcm_tests Depth MaxStates EndPredicate File'),nl,
3099 print(' generate test cases with maximum length Depth, explore'),nl,
3100 print(' maximally MaxStates, the last state satisfies EndPredicate'),nl,
3101 print(' and the test cases are written to File'),nl,
3102 print(' -mcm_cover Operation'),nl,
3103 print(' when generating MCM test cases, Operation should be covered'),nl,
3104 print(' -cbc_tests Depth EndPredicate File'),nl,
3105 print(' generate test cases by constraint solving with maximum'),nl,
3106 print(' length Depth, the last state satisfies EndPredicate'),nl,
3107 print(' and the test cases are written to File'),nl,
3108 print(' -cbc_cover Operation'),nl,
3109 print(' when generating CBC test cases, Operation should be covered'),nl,
3110 % print(' -cbc_cover_all try and cover all operations'),nl, % is now default if no cbc_cover provided
3111 print(' -test_description File'),nl,
3112 print(' read information for test generation from File'),nl,
3113 print(' -dot CMD File write a graph to a dot file, with CMD being one of:'),nl,
3114 (is_dot_command(Cmd),command_description(Cmd,_,Desc),
3115 format(' ~w : ~w~n',[Cmd,Desc]),fail
3116 ; true),
3117 print(' -dotexpr CMD Expr File write a graph for Expr to a dot file, with CMD:'),nl,
3118 (is_dot_command_for_expr(Cmd),command_description(Cmd,_,Desc),
3119 format(' ~w : ~w~n',[Cmd,Desc]),fail
3120 ; true),
3121 print(' -puml CMD File write a graph to a plantuml file, with CMD being one of:'),nl,
3122 (is_plantuml_command(Cmd),command_description(Cmd,_,Desc),
3123 format(' ~w : ~w~n',[Cmd,Desc]),fail
3124 ; true),
3125 print(' -pumlexpr CMD Expr File write a graph for Expr to a plantuml file, with CMD:'),nl,
3126 (is_plantuml_command_for_expr(Cmd),command_description(Cmd,_,Desc),
3127 format(' ~w : ~w~n',[Cmd,Desc]),fail
3128 ; true),
3129 print(' -csv CMD File write a table to a CSV file, with CMD being one of:'),nl,
3130 (is_table_command(Cmd),command_description(Cmd,_,Desc),
3131 format(' ~w : ~w~n',[Cmd,Desc]),fail
3132 ; true),
3133 print(' -csvexpr CMD Expr File write a table for Expr to a CSV file, with CMD:'),nl,
3134 (is_table_command_for_expr(Cmd),command_description(Cmd,_,Desc),
3135 format(' ~w : ~w~n',[Cmd,Desc]),fail
3136 ; true),
3137 print(' -dot_output Path generate dot files for false assertions/properties'),nl,
3138 print(' -dot_all also generate dot files for true assertions/properties'),nl,
3139 print(' -rule_report generate HTML validation report for rules machines (.rmch)'),nl,
3140 print(' -proof_export generate HTML proof export in sequent prover mode (for .probpo PO files)'),nl,
3141 print(' -csvhist E File evaluate expression over history and generate CSV file'),nl,
3142 print(' -visb JFile HFile use VisB JSON file JFILE to create HTML visualistion of history'),nl,
3143 print(' -visb_with_vars JFile HFile (similar, but also show variable values)'),nl,
3144 print(' -load_state File load state of ProB from a saved state space (generated by ProB Tcl/Tk or -save_state)'),nl,
3145 % For Eclipse Version only
3146 %% print(' -parsercp CP class path of the B Parser, this has to be a valid Java class path'),nl,
3147 %% print(' -cspm load CSP-M .csp file rather than B Machine .mch/.ref/.imp File'),nl,
3148 %% print(' -csp load CSP-M .pl file rather than B Machine File'),nl,
3149
3150 /* Options -cspref, -cspdeadlock, -cspdeterministic, and -csplivelock are deprecated, should be excluded in favor of -csp_assertion */
3151 print(' -cspref Spec [m= Impl File'),nl,
3152 print(' checks a refinement statement,'),nl,
3153 print(' where Spec and Impl are processes from File, and \'m\' the type of the refinement:'),nl,
3154 print(' \'T\' for traces, \'F\' for failures, or \'FD\' for failures-divergences.'),nl,
3155 print(' -cspdeadlock P m File'),nl,
3156 print(' checks a process for deadlock,'),nl,
3157 print(' where \'P\' is a process from File, and \'m\' the type of the model:'),nl,
3158 print(' \'F\' for failures and \'FD\' for failures-divergences.'),nl,
3159 print(' -cspdeterministic P m File'),nl,
3160 print(' checks a process for determinism,'),nl,
3161 print(' where \'P\' is a process from File, and \'m\' the type of the model:'),nl,
3162 print(' \'F\' for failures and \'FD\' for failures-divergences.'),nl,
3163 print(' -csplivelock P File'),nl,
3164 print(' checks a process for divergence,'),nl,
3165 print(' where \'P\' is a process from File.'),nl,
3166 /* Options -cspref, -cspdeadlock, -cspdeterministic, and -csplivelock are deprecated, should be excluded in favor of -csp_assertion */
3167
3168 print(' -csp_assertion \"A\" File'),nl,
3169 print(' checks the CSP assertion \'A\' on file \'File\''),nl,
3170 print(' -csp_eval "E" evaluate CSP-M expression.'),nl,
3171 print(' -csp_guide File CSP||B: Use the CSP File to control the B machine'),nl,
3172 print(' '),nl,
3173 ( \+ option_verbose -> true
3174 ;
3175 print(' -test_mode set random seed to the Prolog\'s current random state'),nl,
3176 print(' -rc runtime checking of types/pre-/post-conditions'),nl,
3177 print(' -state_trace File read a file of B predicates (one per line) and try find a matching trace.'),nl
3178
3179 ),
3180 print(' FILE extensions are: '),nl,
3181 print(' .mch for B abstract machines'),nl,
3182 print(' .ref for B refinement machines'),nl,
3183 print(' .imp for B implementation machines'),nl,
3184 print(' .sys for Event-B abstract machines'),nl,
3185 print(' .rmch for B Rule DSL machines'),nl,
3186 print(' .csp, .cspm for CSP-M files, same format as FDR'),nl,
3187 print(' .eventb for Event-B packages exported from Rodin ProB Plugin'),nl,
3188 print(' .tex, .zed for Z models'),nl,
3189 print(' .tla for TLA+ models'),nl,
3190 print(' .als for Alloy models'),nl,
3191 print(' .P for Prolog XTL models'),nl,
3192 ( option_verbose ->
3193 print(' Preferences PREF are: '),nl,
3194 print_eclipse_prefs
3195 ;
3196 print(' Use --help -v to print available preferences PREF'),nl
3197 ),
3198 print(' Use -no_color or set NO_COLOR environment variable to disable terminal colors'),nl,
3199 print(' More info at: https://prob.hhu.de/w/index.php/ProB_Cli'),nl,
3200 nl.
3201
3202
3203 set_argv(V) :-
3204 debug_println(20,set_argv(V)),
3205 set_argv_from_atom(V).
3206
3207 :- use_module(b_global_sets, [set_user_defined_scope/2]).
3208 :- use_module(state_space_exploration_modes,[set_depth_breadth_first_mode/1, get_current_breadth_first_level/1]).
3209 :- use_module(tools_strings, [convert_cli_arg/2]).
3210 set_prefs :-
3211 if_option_set(cli_start_sym_mc_with_lts(_),
3212 preferences:set_preference(try_operation_reuse,false)), % LTSMIN does its own OPERATION_REUSE
3213 if_option_set(socket(_,_), % then we may need the event(.) transition_info for the Java API
3214 preferences:set_preference(store_event_transinfo,true)),
3215 option(set_prefs_from_file(File)),
3216 debug_println(20,load_preferences(File)),
3217 preferences:load_preferences(File),
3218 fail.
3219 set_prefs :-
3220 option(set_preference_group(P,V)),
3221 debug_println(20,set_preference_group(P,V)),
3222 set_preference_group(P,V),
3223 fail.
3224 % eclipse preference or 'normal preference'
3225 set_prefs :-
3226 ? option(set_pref(P,V)),
3227 set_pref(P,V),
3228 fail.
3229 set_prefs :- option(set_card(Set,V)),
3230 debug_println(20,set_card(Set,V)),
3231 convert_cli_arg(V,Value),
3232 set_user_defined_scope(Set,Value),
3233 fail.
3234 set_prefs :-
3235 ( option(breadth_first) -> set_depth_breadth_first_mode(breadth_first)
3236 ; option(depth_first) -> set_depth_breadth_first_mode(depth_first)
3237 ; option(depth_breadth_first_mode(M)) -> set_depth_breadth_first_mode(M)
3238 ; true
3239 ).
3240 :- use_module(tools_matching,[get_possible_preferences_matches_msg/2]).
3241 set_pref(P,V) :-
3242 debug_println(20,set_pref(P,V)),
3243 ? ( eclipse_preference(P,_)
3244 -> set_eclipse_preference(P,V)
3245 ; deprecated_eclipse_preference(P,_,_,_) -> set_eclipse_preference(P,V)
3246 ; obsolete_eclipse_preference(P) -> probcli_add_light_warning('Obsolete preference: ',P)
3247 ; obsolete_preference(P) -> probcli_add_light_warning('Obsolete preference: ',P)
3248 ; % might be a term if its a plugin preference
3249 atom_codes(P,Codes),
3250 append(Codes,".",Codes2), % to make term readable by read_from_codes
3251 read_from_codes(Codes2,Preference),
3252 (nonvar(Preference),preference_val_type(Preference,_)
3253 -> convert_cli_arg(V,Value),
3254 set_preference(Preference,Value)
3255 ; P=timeout ->
3256 add_error(probcli,'Unknown preference timeout. Either set preference TIME_OUT or use -gobal_time_out command','')
3257 ; get_possible_preferences_matches_msg(P,FuzzyMsg) ->
3258 ajoin(['Unknown preference: ',P,'. Did you mean:'],Msg),
3259 add_error(probcli,Msg,FuzzyMsg)
3260 ; get_possible_fuzzy_match_options(P,FuzzyMatches),
3261 % will only give perfect matches as P usually does not have the hyphen in front
3262 FuzzyMatches = [FMC|_] ->
3263 ajoin(['Unknown preference ', P, ' which looks like a probcli command! Did you want to call:'],Msg),
3264 add_error(probcli,Msg,FMC)
3265 ;
3266 add_error(probcli,'Unknown preference:',P)
3267 )
3268 ).
3269
3270 % add non severe warning:
3271 probcli_add_light_warning(Msg,Term) :- option(strict_raise_error),!,
3272 add_warning(probcli,Msg,Term). % does not write on user_error
3273 probcli_add_light_warning(Msg,Term) :- add_message(probcli,Msg,Term).
3274
3275 set_optional_errors :- % register optional/expected errors in the error_manager; avoid printing on stderr
3276 reset_optional_errors_or_warnings,
3277 (option(optional_error(Type)) ; option(expect_error(Type)) ; option(expect_error_pos(Type,_Line,_Col))),
3278 register_optional_error_or_warning(Type),
3279 fail.
3280 set_optional_errors.
3281
3282 % explicit state model checking, without LTL/CTL
3283 regular_safety_model_check_now(Nr,Runtime,WallTime,MCRes,NOW) :-
3284 statistics(runtime,[T1,_]),
3285 statistics(walltime,[W1,_]),
3286 (option(timeout(TO)) -> safe_time_out(regular_safety_model_check(Nr,Time,MCRes),TO,Res)
3287 ; regular_safety_model_check(Nr,Time,MCRes), Res=success
3288 ),
3289 statistics(runtime,[T2,_]),
3290 statistics(walltime,[W2,_]),
3291 WallTime is W2-W1,
3292 Runtime is T2-T1,
3293 (Res=time_out
3294 -> (model_checker:replay_stored_mc_error(StoredRes) % an error was found and stored with mc_continue_after_error
3295 -> report_mc_counter_example(StoredRes),
3296 MCRes=StoredRes
3297 ; add_warning(model_check_incomplete,'Not all states examined due to -global_time_out option set by user: ',TO),
3298 writeln_log(timeout_occurred(NOW,model_check(Nr,Time,MCRes))),
3299 coverage(just_summary),
3300 MCRes=time_out
3301 )
3302 ; true).
3303
3304 :- use_module(model_checker,[model_checking_is_incomplete/6]).
3305
3306 % TO DO: check for ignored states
3307 % code somewhat redundant also with model_check_incomplete below
3308 add_model_checking_warnings(FindInvViolations,FindDeadlocks,FindGoal,FindAssViolations) :-
3309 %print(check(model_checking_is_incomplete(FindInvViolations,FindDeadlocks,FindGoal,FindAssViolations,Msg,Term))),nl,
3310 model_checking_is_incomplete(FindInvViolations,FindDeadlocks,FindGoal,FindAssViolations,Msg,Term),
3311 add_warning(model_check_incomplete,Msg,Term),
3312 % TO DO: store for accumulate_infos
3313 fail.
3314 add_model_checking_warnings(_,_,_,_).
3315
3316 :- use_module(state_space,[current_state_id/1]).
3317 regular_safety_model_check(Nr,Time,ErrRes) :-
3318 statistics(runtime,[T1,_]),
3319 statistics(walltime,[W1,_]),
3320 catch(model_check_aux(Nr,T1,W1,Time,ErrRes), user_interrupt_signal, (
3321 statistics(walltime,[W2,_]), TotalWT is W2-W1,
3322 format_with_colour_nl(user_error,[red],'~nmodel checking interrupted after ~w ms by user (CTRL-C)',[TotalWT]),
3323 coverage(just_summary),
3324 perform_feedback_options_after_exception,
3325 throw(user_interrupt_signal)
3326 )).
3327
3328 % perform some important options for user feedback after CTRL-C interrupts model checking, execute, ...
3329 perform_feedback_options_after_exception :-
3330 (option(check_op_cache(_)) -> cli_check_op_cache([]) ; true),
3331 if_options_set(csv_table_command(TECommand,TableFormulas,TableOptions,TableCSVFile),
3332 csv_table_command(TECommand,TableFormulas,TableOptions,TableCSVFile)),
3333 (option(get_coverage_information(FCC)) -> pretty_print_coverage_information_to_file(FCC) ; true),
3334 (option(cli_print_statistics(X)), (cli_print_statistics(X) -> fail) ; true).
3335
3336 model_check_aux(Nr,T1,W1,Time,ErrRes) :-
3337 (option(no_deadlocks) -> FindDeadlocks=0 ; FindDeadlocks=1),
3338 (option(no_invariant_violations) -> FindInvViolations=0 ; FindInvViolations=1),
3339 (option(no_goal) -> FindGoal=0 ; FindGoal=1),
3340 (option(no_state_errors) -> FindStateErrors=0 ; FindStateErrors=1),
3341 (option(no_assertion_violations)
3342 -> FindAssViolations=0
3343 ; FindAssViolations=1
3344 ),
3345 get_preference(por,POR),
3346 StopAtFullCoverage=0,
3347 %STOPMCAFTER = 86400000, /* 86400000 = 1 day timeout */
3348 STOPMCAFTER = 1152921504606846975, /* equals 13,343,998,895 days */
3349 InspectExistingNodes = 1,
3350 write_xml_element_to_log(model_checking_options,[find_deadlocks/FindDeadlocks,
3351 find_invariant_violations/FindInvViolations, find_goal/FindGoal,
3352 find_assertion_violations/FindAssViolations,
3353 find_state_errors/FindStateErrors,
3354 partial_order_reduction/POR,
3355 inspect_existing_nodes/InspectExistingNodes]),
3356 (tcltk_interface:do_model_check(Nr,NodesAnalysed,STOPMCAFTER,ErrRes,
3357 FindDeadlocks,FindInvViolations,FindGoal,
3358 FindAssViolations,FindStateErrors,StopAtFullCoverage,POR, InspectExistingNodes)
3359 -> (statistics(runtime,[T2,_]), statistics(walltime,[W2,_]),
3360 Time1 is T2-T1, WTime is W2-W1,
3361 (model_checker: expired_static_analysis_time(AnalysisTime) ->
3362 Time is Time1 - AnalysisTime
3363 ; Time = Time1, AnalysisTime=0),
3364 formatsilent('Model checking time: ~w ms (~w ms walltime)~n',[Time,WTime]),
3365 formatsilent('States analysed: ~w~n',[NodesAnalysed]),
3366 get_state_space_stats(_,NrTransitions,_,_),
3367 printsilent('Transitions fired: '),printsilent(NrTransitions),nls,
3368 (get_current_breadth_first_level(Level)
3369 -> formatsilent('Breadth-first levels: ~w~n',[Level]) % is this the equivalent of TLC's diameter?
3370 ; true),
3371 write_xml_element_to_log(model_checking_statistics,
3372 [result/ErrRes,runtime/Time,walltime/WTime,
3373 states/NodesAnalysed,transitions/NrTransitions,staticAnalysisTime/AnalysisTime]),
3374 (ErrRes = no
3375 -> print('No counter example Found, not all states visited'),nl,
3376 add_warning(model_check_incomplete,'Not all states examined due to limit set by user: ',Nr)
3377 ; ErrRes=all
3378 -> (tcltk_find_max_reached_node
3379 -> (not_interesting(_)
3380 -> print('No counter example found. However, not all transitions were computed (and some states not satisfying SCOPE predicate were ignored) !')
3381 ; print('No counter example found. However, not all transitions were computed !')
3382 )
3383 ; not_interesting(_)
3384 -> print_green('No counter example found. ALL states (satisfying SCOPE predicate) visited.')
3385 % b_get_machine_searchscope(Scope)
3386 ; print_green('No counter example found. ALL states visited.')
3387 ),nl,
3388 add_model_checking_warnings(FindInvViolations,FindDeadlocks,FindGoal,FindAssViolations)
3389 ; % ErrRes is not no or all
3390 report_mc_counter_example(ErrRes)
3391 ),nl
3392 )
3393 ; % do_model_check failed
3394 statistics(runtime,[T2,_]), Time1 is T2-T1,
3395 (model_checker: expired_static_analysis_time(AnalysisTime) -> Time is Time1 - AnalysisTime
3396 ; Time = Time1),
3397 printsilent('Model checking time: '), printsilent(Time), printsilent(' ms'),nls,
3398 print_error('*** Model checking FAILED '),nl,
3399 ErrRes=fail,
3400 definite_error_occurred
3401 ).
3402
3403 report_mc_counter_example(ErrRes) :-
3404 print_red('*** COUNTER EXAMPLE FOUND ***'),nl,
3405 debug_println(20,ErrRes),nl,
3406 tcltk_interface:translate_error_for_tclk(ErrRes,TclTkRes),
3407 print(TclTkRes),nl,
3408 print_history_as_counter_example(true),
3409 error_occurred(TclTkRes).
3410
3411 print_history_as_counter_example(CheckInv) :-
3412 (option_silent_set -> true
3413 ; option(no_counter_examples) -> true % -nocounter
3414 ; cli_print_history,
3415 (silent_mode(off), CheckInv=true,
3416 current_state_id(ID),invariant_violated(ID)
3417 -> b_interpreter:analyse_invariant_for_state(ID)
3418 ; true)
3419 ).
3420
3421 cli_print_history :-
3422 (option_very_verbose
3423 -> portray_history % detailed printout with transition ids, state ids, ...
3424 ; tcltk_interface:tcltk_get_history(list(Hist)),
3425 length(Hist,Len),
3426 format('*** TRACE (length=~w):~n',[Len]),
3427 reverse(Hist,Trace),
3428 print_nr_list(Trace) % TODO: print loop back for LTL lasso
3429 ).
3430
3431 % perform all cbc checks on current machine
3432 cbc_check(_NOW) :-
3433 option(cbc_deadlock_check(DeadlockGoalPred)),
3434 cbc_deadlock_check(DeadlockGoalPred),
3435 fail.
3436 cbc_check(_NOW) :-
3437 option(constraint_based_check(OpName)),
3438 constraint_based_check(OpName),
3439 fail.
3440 cbc_check(_NOW) :-
3441 option(cbc_assertions_after(OpName)),
3442 constraint_based_check(OpName,assertions),
3443 fail.
3444 cbc_check(_NOW) :- option(cbc_assertions(AllowEnumWarning,Options)),
3445 cbc_assertions(AllowEnumWarning,Options),
3446 fail.
3447 %cbc_check(NOW) :-
3448 % option(cbc_pred(TargetPredString)),
3449 % check_loaded(cbc_pred),
3450 % print('% Starting Constraint-Based Check for Predicate: '), print(TargetPredString),nl,
3451 % b_set_up_valid_state_with_pred(NormalisedState,Pred) TO DO: add this feature
3452 cbc_check(_NOW) :- option(cbc_sequence(Sequence,TargetPredString,Findall)),
3453 cbc_sequence(Sequence,TargetPredString,Findall),
3454 fail.
3455 cbc_check(_NOW) :- option(cbc_refinement),
3456 cbc_refinement,
3457 fail.
3458 cbc_check(_NOW) :- option(cbc_redundant_invariants(NrExpected)),
3459 cbc_redundant_invariants(NrExpected),
3460 fail.
3461 cbc_check(_).
3462
3463 :- use_module(tcltk_interface,[tcltk_constraint_based_check/2,
3464 tcltk_constraint_based_check_with_timeout/3,
3465 tcltk_constraint_find_deadlock_state_with_goal/3,
3466 tcltk_cbc_find_trace/4,
3467 tcltk_cbc_refinement_check/2]).
3468 :- use_module(probsrc(bmachine),[b_is_operation_name/1]).
3469
3470 constraint_based_check(all) :-
3471 check_loaded_not_empty(constraint_based_check),
3472 print_repl_prompt_s('% Starting Constraint-Based Check for all Operations: '),nl,
3473 start_xml_feature(cbc_operation_check,all_operations,true,FINFO),
3474 (tcltk_constraint_based_check(list(Result),ErrorsWereFound)
3475 -> print('% Constraint-Based Check Result: '),nl,
3476 print(Result),nl,
3477 write_result_to_file(Result),
3478 (ErrorsWereFound=true
3479 -> print_red('*** CONSTRAINT-BASED CHECK FOUND ERRORS ***'),nl, error_occurred(cbc)
3480 ; (ErrorsWereFound=false -> print_green('NO ERRORS FOUND'),nl)
3481 ; print_red('*** TIMEOUT OCCURRED ***'),nl,error_occurred(cbc)
3482 )
3483 ; write_result_to_file(cbc_check_failed), Result=internal_error, ErrorsWereFound=false,
3484 add_internal_error('ConstraintBasedCheck unexpectedly failed. ',cbc_check(all)),definite_error_occurred
3485 ),nl,
3486 write_cbc_check_result(Result,ErrorsWereFound),
3487 stop_xml_feature(cbc_operation_check,FINFO).
3488 constraint_based_check(OpName) :- OpName\=all, % -cbc OpName
3489 constraint_based_check(OpName,invariant).
3490
3491 % check whether OpName can violate the invariant or the (dynamic) assertions
3492 constraint_based_check(OpName,InvOrAssertion) :-
3493 check_loaded_not_empty(constraint_based_check),
3494 print_repl_prompt_s('% Starting Constraint-Based Check for Operation: '), print(OpName),
3495 (InvOrAssertion=invariant -> true ; print(' and '), print(InvOrAssertion)),nl,
3496 start_xml_feature(cbc_operation_check,operation,OpName,FINFO),
3497 (tcltk_constraint_based_check_with_timeout(OpName,InvOrAssertion,Result)
3498 -> print('% Constraint-Based Check Result: '),nl, print(Result),nl,
3499 write_result_to_file(Result),
3500 (Result=time_out
3501 -> print_red('*** TIMEOUT OCCURRED ***'),nl, error_occurred(cbc)
3502 ; (Result=ok -> print_green('NO ERRORS FOUND'),nl)
3503 ; print_red('*** CONSTRAINT-BASED CHECK FOUND ERRORS ***'),nl,error_occurred(cbc) )
3504 ; write_result_to_file(constraint_based_check_failed), Result=internal_error,
3505 add_error(probcli,'ConstraintBasedCheck unexpectedly failed'),
3506 (b_is_operation_name(OpName) -> true
3507 ; add_error(probcli,'Unknown Operation Name: ',OpName)),
3508 definite_error_occurred
3509 ),nl,
3510 write_cbc_check_result(Result),
3511 stop_xml_feature(cbc_operation_check,FINFO).
3512
3513 write_cbc_check_result(Result) :-
3514 functor(Result,F,_), % example result: no_counterexample_exists(Ids,Prd,Other)
3515 write_xml_element_to_log(cbc_check_result,[result/F]).
3516 write_cbc_check_result(Result,ErrorsWereFound) :- functor(Result,F,_),
3517 write_xml_element_to_log(cbc_check_result,[result/F,errors_were_found/ErrorsWereFound]).
3518
3519 cbc_deadlock_check(DeadlockGoalPred) :-
3520 print_repl_prompt_s('% Starting Constraint-Based DEADLOCK check '),nl,
3521 start_xml_feature(cbc_deadlock_check,FINFO),
3522 (tcltk_constraint_find_deadlock_state_with_goal(DeadlockGoalPred,false,Res)
3523 -> write_result_to_file(Res),
3524 (Res=time_out ->
3525 print_red('*** TIME_OUT occurred ***'),nl,
3526 error_occurred(cbc_deadlock_check_time_out)
3527 ; print_red('*** DEADLOCK state found ***'),nl,
3528 error_occurred(cbc_deadlock_check),
3529 (silent_mode(on) -> true
3530 ; print('*** STATE = '),nl,
3531 current_b_expression(DBState), translate:print_bstate(DBState),nl,
3532 print('*** END DEADLOCKING STATE '),nl
3533 )
3534 )
3535 ; write_result_to_file(no_deadlock_found), Res=no_deadlock_found,
3536 print_green('No DEADLOCK state found'),nl
3537 ),
3538 write_cbc_check_result(Res),
3539 stop_xml_feature(cbc_deadlock_check,FINFO).
3540 cbc_assertions(AllowEnumWarning,Options) :-
3541 findall(OPT,option(cbc_option(OPT)),FullOptions,Options),
3542 check_loaded_not_empty(cbc_assertions),
3543 print_repl_prompt_s('% Starting Constraint-Based static ASSERTIONS check '),nl,
3544 start_xml_feature(cbc_assertion_check,allow_enumeration_warning,AllowEnumWarning,FINFO),
3545 write_prolog_term_as_xml_to_log(options(Options)),
3546 (cbc_constraint_find_static_assertion_violation(Res,FullOptions)
3547 -> process_cbc_assertion_result(Res,AllowEnumWarning)
3548 ; write_result_to_file(cbc_assertions_failed), Res=internal_error,
3549 print_red('CBC Check failed'),nl,
3550 error_occurred(cbc_assertions_failure)
3551 ),
3552 write_cbc_check_result(Res),
3553 stop_xml_feature(cbc_assertion_check,FINFO).
3554 cbc_sequence(Sequence,TargetPredString,Findall) :-
3555 check_loaded_not_empty(cbc_sequence),
3556 print_repl_prompt_s('% Starting Constraint-Based Check for Sequence: '), print_repl_prompt_s(Sequence),
3557 start_xml_feature(cbc_sequence_check,sequence,Sequence,FINFO),
3558 (TargetPredString='' -> true ; print(' with target: '), print(TargetPredString)),
3559 nl,
3560 write_xml_element_to_log(options,[target_predicate/TargetPredString]),
3561 (tcltk_cbc_find_trace(Sequence,TargetPredString,Findall,Res)
3562 -> (Res=ok -> print_green('Sequence found and executed'),nl
3563 ; Res=time_out -> error_occurred(cbc_sequence_time_out)
3564 ; Res=no_solution_found -> print_red('*** NO SOLUTION FOUND '),error_occurred(cbc_sequence_no_solution_found)
3565 ; Res=nr_cbc_sols(NrSols) -> print('*** # SOLUTIONS FOUND: '),print(NrSols),nl
3566 ; print_red('*** Unknown result: '), print(Res),nl,
3567 error_occurred(cbc_sequence)
3568 )
3569 ; print('*** Internal error: Check failed '), error_occurred(cbc_sequence), Res=internal_error
3570 ),
3571 check_nr_of_cbc_sequence_solutions(Res),
3572 write_cbc_check_result(Res),
3573 stop_xml_feature(cbc_sequence_check,FINFO).
3574 % check the number of solutions found by -cbc_sequence_all or -cbc_sequence_with_target_all
3575 check_nr_of_cbc_sequence_solutions(Res) :-
3576 option(check_cbc_sequence_solutions(Expected)),
3577 (Res=nr_cbc_sols(NrSols) -> true
3578 ; Res=no_solution_found -> NrSols=0
3579 ; Res=ok -> NrSols=1), % single solution mode (-cbc_sequence) stops after first solution
3580 !,
3581 (NrSols=Expected -> true
3582 ; ajoin(['Unexpected number of solutions for constraint-based sequence check (expected ',Expected,'): '],Msg),
3583 add_error(cbc_sequence_solutions,Msg,NrSols)
3584 ).
3585 check_nr_of_cbc_sequence_solutions(_).
3586
3587 cbc_refinement :-
3588 check_loaded_not_empty(cbc_refinement),
3589 print_repl_prompt_s('% Starting Constraint-Based static refinement check '),nl,
3590 start_xml_feature(cbc_refinement_check,FINFO),
3591 tcltk_cbc_refinement_check(list(Result),ErrorsWereFound),
3592 print('% Constraint-Based Refinement Check Result: '),nl,print(Result),nl,
3593 (ErrorsWereFound = time_out -> print_red('*** TIME_OUT occurred ***'),nl,error_occurred(cbc_refinement_time_out) ;
3594 ErrorsWereFound = true -> print_red('*** Refinement Violation found ***'),nl,error_occurred(cbc_refinement) ;
3595 print_green('No static Refinement Violation found'),nl
3596 ),
3597 write_xml_element_to_log(cbc_check_result,[errors_were_found/ErrorsWereFound]),
3598 stop_xml_feature(cbc_refinement_check,FINFO).
3599 :- use_module(b_state_model_check,[cbc_find_redundant_invariants/2]).
3600 cbc_redundant_invariants(NrExpected) :-
3601 check_loaded_not_empty(cbc_redundant_invariants),
3602 print_repl_prompt_s('% Starting Constraint-Based invariant redundancy check'),nl,
3603 start_xml_feature(cbc_redundant_invariants,FINFO),
3604 cbc_find_redundant_invariants(Res,TimeoutOccured),
3605 length(Res,NrInvs),
3606 (Res = [] -> print_green('No redundant invariants found'),nl
3607 ; format('*** REDUNDANT INVARIANTS (~w) ***~n',[NrInvs]),
3608 prnt(1,Res), nl
3609 ),
3610 (NrExpected = NrInvs -> true
3611 ; format_with_colour_nl(user_error,[red],'*** Expected ~w redundant invariants (instead of ~w).',[NrExpected,NrInvs]),
3612 error_occurred(cbc_redundant_invariants)),
3613 write_xml_element_to_log(cbc_redundant_invariants,[redundant_invariants/NrInvs, timeout_occured/TimeoutOccured]),
3614 stop_xml_feature(cbc_redundant_invariants,FINFO).
3615
3616 prnt(_,[]).
3617 prnt(N,[H|T]) :- format(' ~w : ~w~n',[N,H]), N1 is N+1, prnt(N1,T).
3618
3619 :- use_module(solver_interface,[predicate_uses_unfixed_deferred_set/2, unfixed_typed_id_in_list/3]).
3620 process_cbc_assertion_result(time_out,_) :- !,
3621 write_result_to_file(no_counterexample_found('"TIME_OUT"')),
3622 print_red('*** TIME_OUT occurred ***'),nl,
3623 error_occurred(cbc_assertions_time_out).
3624 process_cbc_assertion_result(no_counterexample_exists(Constants,TotPredicate,OtherInfo),AllowEnumWarning) :- !,
3625 print_green('No Counterexample to ASSERTION exists '),(OtherInfo=[] -> true ; print(OtherInfo)),nl,
3626 (unfixed_typed_id_in_list(TID,CType,Constants) % TO DO: look only at component
3627 -> write_deferred_set_used(AllowEnumWarning),
3628 get_texpr_id(TID,CID),pretty_type(CType,CTypeS),
3629 format('Warning: Some constants use deferred sets (e.g., ~w:~w) which have only been checked for a single cardinality!~n',[CID,CTypeS])
3630 ; predicate_uses_unfixed_deferred_set(TotPredicate,CType)
3631 -> write_deferred_set_used(AllowEnumWarning),pretty_type(CType,CTypeS),
3632 format('Warning: Some quantified variables use deferred sets (e.g., ~w) which have only been checked for a single cardinality!~n',[CTypeS]) % happens for tests 1173, 1174
3633 ; write_result_to_file(no_counterexample_exists)
3634 %,print('Computing unsat core: '),nl,unsat_cores:unsat_core(TotPredicate,Core),print('CORE: '),translate:print_bexpr(Core),nl
3635 ). % WE HAVE A PROOF
3636 process_cbc_assertion_result(no_counterexample_found,AllowEnumWarning) :- !,
3637 write_result_to_file(no_counterexample_found('"Enumeration Warning"')),
3638 print('No Counterexample for ASSERTION found (*enumeration warning occured*)'),nl,
3639 (AllowEnumWarning=true -> true ; error_occurred(cbc_assertions_enumeration_warning)).
3640 process_cbc_assertion_result(counterexample_found,_) :- !,
3641 write_result_to_file(counterexample_found),
3642 print_red('*** Counterexample for ASSERTION found ***'),nl,
3643 error_occurred(cbc_assertions),
3644 (silent_mode(on) -> true
3645 ; print('*** STATE = '),nl,
3646 current_b_expression(DBState), translate:print_bstate(DBState),nl,
3647 print('*** END ASSERTION Counterexample STATE '),nl
3648 ),
3649 (get_dot_file('cbc_assertions',DFile) -> generate_dot_from_assertions(DFile) ; true).
3650 process_cbc_assertion_result(Res,A) :-
3651 write_result_to_file(Res),
3652 add_internal_error('Unknown: ',process_cbc_assertion_result(Res,A)).
3653
3654
3655 write_deferred_set_used(AllowEnumWarning) :-
3656 write_result_to_file(no_counterexample_found('"Deferred Sets Used"')),
3657 (AllowEnumWarning=true -> true ; error_occurred(cbc_assertions_enumeration_warning)).
3658
3659 :- use_module(tools_io,[safe_open_file/4]).
3660 write_result_to_file(Result) :- option(cbc_result_file(FILE)),
3661 safe_open_file(FILE,write,Stream,[encoding(utf8)]),
3662 !,
3663 write(Stream,Result),
3664 close(Stream).
3665 write_result_to_file(_).
3666
3667
3668
3669 if_option_set(Option,Call) :-
3670 if_option_set(Option,Call,true).
3671 if_option_set(Option,Then,Else) :-
3672 (option(Option) -> call_for_option(Then) ; call_for_option(Else)).
3673 ifm_option_set(Option,Call) :-
3674 ifm_option_set(Option,Call,true).
3675 ifm_option_set(Option,Then,Else) :- % can perform multiple options
3676 findall(Then,option(Option),As),
3677 (As=[] -> call_for_option(Else) ; perform(As)).
3678 perform([]).
3679 perform([A|T]) :-
3680 call_for_option(A),
3681 perform(T).
3682 call_for_option(Call) :- (call(Call) -> true ; add_internal_error('probcli option call failed: ',Call)).
3683 if_option_set_loaded(Option,Action,Call) :-
3684 ( option(Option),check_loaded_not_empty(Action) ->
3685 call_for_option(Call)
3686 ; true).
3687 ifm_option_set_loaded(Option,Action,Call) :- % can perform multiple options
3688 findall(Call,(option(Option),check_loaded_not_empty(Action)),As),
3689 perform(As).
3690
3691
3692
3693 if_options_set(Option,Call) :- % allow multiple solutions for Option
3694 option(Option),call(Call),fail.
3695 if_options_set(_,_).
3696
3697 print_options :- print('CLI OPTIONS: '),nl,
3698 option(Option), print(Option), nl, fail.
3699 print_options :- nl.
3700
3701 :- use_module(cbcsrc(enabling_analysis),[infeasible_operation_cache/1]).
3702 :- use_module(cbcsrc(sap),[explore_and_generate_testcases/7,cbc_gen_test_cases_from_string/5, tcl_get_stored_test_cases/1]).
3703 :- use_module(translate,[print_bexpr/1]).
3704
3705 mcm_test_case_generation(ADepth,AMaxStates,ATarget,Output) :-
3706 arg_is_number(ADepth,MaxDepth),
3707 arg_is_number(AMaxStates,MaxStates),
3708 bmachine:b_parse_machine_predicate(ATarget,Target),!,
3709 get_comma_or_space_separated_options(mcm_cover,Events),
3710 (option_silent_set -> true
3711 ; print('mcm test case generation, maximum search depth: '),print(MaxDepth),nl,
3712 print('mcm test case generation, maximum number of states: '),print(MaxStates),nl,
3713 print('mcm test case generation, target state predicate: '),print_bexpr(Target),nl,
3714 print('mcm test case generation, output file: '),print(Output),nl,
3715 print('mcm test case generation, events to cover: '),print_list(Events),nl
3716 ),
3717 explore_and_generate_testcases(Events,Target,MaxDepth,MaxStates,Output,NumTests,Uncovered),
3718 printsilent('mcm test case generation, generated test cases: '),printsilent(NumTests),nls,
3719 print_uncovered('mcm test case generation, ',Uncovered).
3720 mcm_test_case_generation(_ADepth,_AMaxStates,_ATarget,_Output) :-
3721 print_error('MCM Test Case Generation failed'),
3722 error_occurred(mcm_tests).
3723
3724 cbc_test_case_generation(ADepth,TargetString,Output) :-
3725 arg_is_number(ADepth,MaxDepth),
3726 ( option(cbc_cover_all) -> Events=all
3727 ; (get_comma_or_space_separated_options(cbc_cover,Events), Events \= []) -> true
3728 ; Events=all ),
3729 (\+ option(cbc_cover_final) -> FEvents = Events
3730 ; Events=all -> FEvents=all,
3731 add_error(cbc_cover_final,'Option cbc_cover_final not compatible with trying to cover all events')
3732 ; FEvents = final(Events),
3733 println_silent('constraint based test case generation, target events considered final')),
3734 printsilent('constraint based test case generation, maximum search depth: '),printsilent(MaxDepth),nls,
3735 printsilent('constraint based test case generation, target state predicate: '),printsilent(TargetString),nls,
3736 printsilent('constraint based test case generation, output file: '),printsilent(Output),nls,
3737 (TargetString = '#not_invariant' -> BMC=invariant_violation
3738 ; TargetString = '#deadlock' -> BMC=deadlock
3739 ; BMC = 'none'),
3740 (BMC \= 'none' ->
3741 printsilent('constraint based test case generation, performing bounded model checking'),nls
3742 ; option_silent_set -> true
3743 ; print('constraint based test case generation, events to cover: '),print_list(Events),nl),
3744 cbc_gen_test_cases_from_string(FEvents,TargetString,MaxDepth,Output,Uncovered),
3745 !,
3746 format('constraint based test case generation finished~n',[]),
3747 (BMC \= 'none'
3748 -> tcl_get_stored_test_cases(list(Tests)), %print(tests(Tests)),nl,
3749 (Tests=[] -> print_green('No counterexample found'),nl
3750 ; Tests = [_|_], BMC=deadlock -> add_error(deadlock,'Deadlock found by bmc')
3751 ; Tests = [_|_] -> add_error(invariant_violation,'Invariant violation found by bmc')
3752 ; add_internal_error('Unexpected bmc result: ',Tests)
3753 )
3754 ; Uncovered=[_|_],option(strict_raise_error)
3755 -> add_error(cbc_tests,'Uncovered events: ',Uncovered)
3756 ; print_uncovered('constraint based test case generation, ',Uncovered)
3757 ).
3758 cbc_test_case_generation(_ADepth,_ATarget,_Output) :-
3759 print_error('Constraint based test case generation failed!'),
3760 error_occurred(cbc_tests).
3761
3762 print_uncovered(Msg,Uncovered) :-
3763 include(enabling_analysis:infeasible_operation_cache,Uncovered,Infeasible),
3764 (Infeasible=[]
3765 -> format('~wuncovered events: ',[Msg]),print_list(Uncovered),nl
3766 ; format('~winfeasible uncovered events: ',[Msg]),print_list(Infeasible),nl,
3767 exclude(enabling_analysis:infeasible_operation_cache,Uncovered,Feasible),
3768 format('~wuncovered events: ',[Msg]),print_list(Feasible),nl
3769 ).
3770
3771 print_list(all) :- print('** all **').
3772 print_list(list(L)) :- print_list(L). % possibly not used
3773 print_list([]) :- print('** none **').
3774 print_list([H|T]) :- length([H|T],Len), format('(~w) ',[Len]),
3775 print(H),print(' '),print_list2(T).
3776 print_list2([]).
3777 print_list2([H|T]) :- print(H),print(' '),print_list2(T).
3778
3779 get_comma_or_space_separated_options(Option,Selection) :-
3780 functor(O,Option,1),
3781 findall(E, (option(O),arg(1,O,CommaSep),
3782 split_by_seperator(CommaSep,Es),
3783 member(E,Es)),
3784 Selection).
3785
3786 split_by_seperator(NonAtomic,Res) :- \+ atomic(NonAtomic),!, Res=[NonAtomic].
3787 split_by_seperator(String,Strings) :-
3788 atom_chars(String,Chars),
3789 split_by_seperator2(Chars,Strings).
3790 split_by_seperator2(Chars,Result) :-
3791 append(AChars,[X|B],Chars),seperator(X),!,
3792 (AChars=[] -> Result=Rest ; atom_chars(A,AChars), Result=[A|Rest]),
3793 split_by_seperator2(B,Rest).
3794 split_by_seperator2(Chars,[String]) :- atom_chars(String,Chars).
3795
3796 seperator(',').
3797 seperator(' ').
3798 seperator(';').
3799
3800 ltl_check_assertions :-
3801 (option(ltl_limit(Limit)) -> true; Limit= -1), % -1 means no limit
3802 formatsilent('Model checking LTL assertions~n',[]),
3803 ltl_check_assertions(Limit,Outcome),!,
3804 ( Outcome = pass -> print_green('LTL check passed'),nl
3805 ; Outcome = fail, expected_error(ltl) -> print_blue('LTL check not successful (as expected)'),nl,error_occurred(ltl)
3806 ; Outcome = fail -> print_red('*** LTL check failed'),nl,error_occurred(ltl)
3807 ; Outcome = no_tests -> print_red('*** No LTL assertions found, test failed'),nl,definite_error_occurred
3808 ; print_red('*** An error occurred in the LTL assertion test'),nl,
3809 definite_error_occurred).
3810 ltl_check_assertions :-
3811 add_internal_error('Call failed:',ltl_check_assertions),definite_error_occurred.
3812
3813 :- use_module(probltlsrc(ltl),[parse_ltlfile/2]).
3814 ltl_check_file(Filename) :-
3815 (option(ltl_limit(Limit)) -> true; Limit= -1), % -1 means no limit
3816 ajoin(['Model checking LTL assertions from file ',Filename],Msg),
3817 print_repl_prompt_s(Msg),nl,
3818 ( parse_ltlfile(Filename, Formulas)
3819 -> ltl_check_formulas(Formulas,Limit)
3820 ; print_red('An error occurred while parsing the LTL file.\n'),
3821 definite_error_occurred
3822 ).
3823
3824 :- use_module(probltlsrc(ltl),[ltl_model_check2/4]).
3825 ltl_check_formulas([],_) :-
3826 print_green('All LTL formulas checked.\n').
3827 ltl_check_formulas([formula(Name,F)|Rest],Limit) :-
3828 print('Checking formula '),print(Name),print(':\n'),
3829 ltl_model_check2(F,Limit,init,Status),
3830 ( Status == no ->
3831 print_red('Counterexample found for formula \"'),print_red(Name),
3832 print_red('\", saving trace file.\n'),
3833 ajoin(['ltlce_', Name, '.trace'], Tracefile),
3834 tcltk_save_history_as_trace_file(prolog,Tracefile),
3835 add_error(ltl_counterexample,'Counterexample was found')
3836 ; Status == ok ->
3837 ltl_check_formulas(Rest,Limit)
3838 ; Status == incomplete ->
3839 ajoin(['Model was not completly model-checked, aborted after ',Limit,' new states'],
3840 Msg),
3841 add_error(ltl,Msg)
3842 ;
3843 ajoin(['Model checker returns unexpected result (',Status,')'],Msg),
3844 add_error(ltl,Msg)).
3845
3846 % Mode = init or specific_node(ID) or starthere
3847 cli_ltl_model_check(Formula,Mode,ExpectedStatus,Status) :-
3848 (option(ltl_limit(Max)) -> true; Max = -1), % -1 means no limit
3849 start_xml_feature(ltl_model_check,formula,Formula,FINFO),
3850 ltl_model_check(Formula,Max,Mode,Status),
3851 write_xml_element_to_log(model_check_result,[status/Status,expected_status/ExpectedStatus,(mode)/Mode]),
3852 check_status(Status,ExpectedStatus,Formula,ltl),
3853 stop_xml_feature(ltl_model_check,FINFO).
3854
3855 % Mode = init or specific_node(ID) or starthere
3856 cli_ctl_model_check(Formula,Mode,ExpectedStatus,Status) :-
3857 (option(ltl_limit(Max)) -> true; Max = -1), % -1 means no limit
3858 start_xml_feature(ctl_model_check,formula,Formula,FINFO),
3859 ctl_model_check(Formula,Max,Mode,Status),
3860 write_xml_element_to_log(model_check_result,[status/Status,expected_status/ExpectedStatus,(mode)/Mode]),
3861 check_status(Status,ExpectedStatus,Formula,ctl),
3862 stop_xml_feature(ctl_model_check,FINFO).
3863
3864 :- use_module(extension('markov/dtmc_model_checking.pl')).
3865 cli_pctl_model_check(Formula,Mode,ExpectedStatus,Status) :-
3866 % use_module(extension('markov/dtmc_model_checking.pl')),
3867 (option(ltl_limit(Max)) -> true; Max = -1), % -1 means no limit
3868 dtmc_model_checking:pctl_model_check(Formula,Max,Mode,Status),
3869 check_status(Status,ExpectedStatus,Formula,pctl).
3870
3871 check_expected(St,Exp,Mode) :-
3872 (St=Exp -> true
3873 ; ajoin(['Unexpected ',Mode,' model checking result ',St,', expected: '],Msg),
3874 add_error(Mode,Msg,Exp)).
3875
3876 check_status(ok,Expected,Formula,ltl) :- !, % TO DO: make uniform ? CTL returns true; LTL returns ok
3877 format_with_colour_nl(user_output,[green],'LTL Formula TRUE.~nNo counter example found for ~w.',[Formula]),
3878 flush_output(user_output),
3879 check_expected(true,Expected,ltl).
3880 check_status(true,Expected,Formula,ctl) :- !,
3881 format_with_colour_nl(user_output,[green],'CTL Formula TRUE.~nNo counter example found for ~w.',[Formula]),
3882 flush_output(user_output),
3883 check_expected(true,Expected,ctl).
3884 check_status(true,Expected,Formula,pctl) :- !,
3885 format_with_colour_nl(user_output,[green],'PCTL Formula TRUE: ~w~n',[Formula]),
3886 flush_output(user_output),
3887 check_expected(true,Expected,pctl).
3888 check_status(solution(Bindings),Expected,Formula,pctl) :- !,
3889 format_with_colour_nl(user_output,[green],'PCTL Formula TRUE: ~w',[Formula]),
3890 format_with_colour_nl(user_output,[green],'PCTL Solutions: ~w~n',[Bindings]),
3891 flush_output(user_output),
3892 check_expected(true,Expected,pctl).
3893 check_status(nostart,_Expected,Formula,LTLorCTL) :- !, % as in the Tcl/Tk GUI
3894 add_error(LTLorCTL,'No initialisation found to start from, cannot check formula: ',Formula).
3895 check_status(incomplete,Expected,Formula,LTLorCTL) :- !,
3896 incomplete_warning(LTLorCTL,Warning),
3897 add_warning(Warning, 'Warning: Model Check incomplete for: ', Formula),nl,
3898 format('No counter example found so far for ~w.~n',[Formula]),
3899 check_expected(incomplete,Expected,LTLorCTL).
3900 check_status(NO,Expected,Formula,LTLorCTL) :- (NO=no ; NO=false),!, % TO DO: make uniform
3901 (Expected==false
3902 -> format_with_colour_nl(user_error,[red],'Model Check Counterexample found for: ~w',[Formula])
3903 ; add_error(LTLorCTL, 'Model Check Counterexample found for: ', Formula)
3904 ),
3905 cli_print_history,
3906 print('Formula '), print('FALSE.'),nl,
3907 debug_format(19,'Use -his FILE -his_option show_states to display states of counterexample~n',[]),
3908 nl,
3909 check_expected(false,Expected,LTLorCTL).
3910 check_status(Status,Expected,Formula,LTLorCTL) :-
3911 add_internal_error('Unknown status: ', check_status(Status,Expected,Formula,LTLorCTL)).
3912
3913 incomplete_warning(ltl,ltl_incomplete) :- !.
3914 incomplete_warning(ctl,ctl_incomplete) :- !.
3915 incomplete_warning(X,X).
3916
3917 :- if(environ(prob_release,true)).
3918
3919 run_benchmark(_, _, _) :-
3920 add_message(probcli, 'Command-line argument for benchmarking is not available in release mode.').
3921
3922 :- else.
3923
3924 :- use_module('../tests/smt_solver_benchmarks/alloy2b_benchmarks').
3925 :- use_module('../tests/smt_solver_benchmarks/smt_solver_benchmarks').
3926 run_benchmark(alloy, CmdName, AlloyFilePath) :-
3927 alloy2b_benchmarks:benchmark_alloy_command(CmdName, AlloyFilePath).
3928 run_benchmark(smt, bmc, Path) :-
3929 smt_solver_benchmarks:run_additional_bmc_benchmarks(false, [Path]), halt.
3930 run_benchmark(smt, cbc_deadlock, Path) :-
3931 smt_solver_benchmarks:run_additional_deadlock_benchmarks(false, [Path]), halt.
3932 run_benchmark(smt, cbc_inv, Path) :-
3933 smt_solver_benchmarks:run_additional_inductive_inv_benchmarks(false, [Path]), halt.
3934
3935 :- endif.
3936
3937 evaluate_from_commandline :-
3938 retractall(eval_result(_,_)),
3939 option(eval_string_or_file(A,B,Q,E,Rchk)), %print(eval(A,B,Q,E)),nl,
3940 % treat eval_string and eval_file together to ensure proper order of evaluation
3941 % (only possible side-effect at the moment: formula can add new machine_string facts)
3942 eval_string_or_file(A,B,Q,E,Rchk),
3943 fail.
3944 evaluate_from_commandline :- print_eval_results,
3945 % treat -repl option or -replay File option
3946 (option(eval_repl([File1|TF]))
3947 -> (repl_evaluate_expressions([File1|TF]) -> true ; true)
3948 ; start_repl_if_required).
3949 start_repl_if_required :-
3950 (option(eval_repl([]))
3951 -> (repl_evaluate_expressions([]) -> true ; true)
3952 ; true).
3953
3954 :- dynamic eval_result/2.
3955 add_eval_result(R) :- retract(eval_result(R,N)),!,
3956 N1 is N+1, assertz(eval_result(R,N1)).
3957 add_eval_result(R) :- assertz(eval_result(R,1)).
3958 print_eval_results :- findall(R/N, eval_result(R,N), L), sort(L,SL),
3959 (SL=[] -> true ; format('Evaluation results: ~w~n',[SL])).
3960
3961 :- use_module(tools_printing,[print_error/1, format_error_with_nl/2]).
3962 %eval_string_or_file(string,_String,_,'FALSE',_Recheck) :- !. % comment in to skip evalf
3963 eval_string_or_file(string,String,_,Expected,Recheck) :-
3964 inc_counter(eval_string_nr,EvalNr),
3965 set_current_probcli_command(eval_string(String)),
3966 (option_silent_set,nonvar(Expected) -> true
3967 ; nonvar(Expected) -> format('eval(~w:~w): ~w~n',[EvalNr,Expected,String])
3968 ; format('eval(~w): ~w~n',[EvalNr,String])
3969 ),
3970 reset_error_spans, % avoid underlining previous errors in eval_string
3971 (eval_string_with_time_out(String,StringResult,EnumWarning,_LS) -> true
3972 ; print_error('Eval string failed: '), print_error(String),
3973 error_occurred(eval_string),
3974 StringResult='fail'
3975 ),
3976 add_eval_result(StringResult),
3977 eval_check_result(StringResult,Expected,EnumWarning,eval_string(EvalNr),String),
3978 (Recheck=recheck(Mode) -> recheck_pp_of_last_expression(Mode,_,_)
3979 ; Recheck=add_to_profile_stats(Category) ->
3980 (arg_is_number(StringResult,Nr) -> add_to_profile_stats(Category,Nr)
3981 ; add_error(eval_for_bench_csv,'Result of expression must be number:',String))
3982 ; true),
3983 unset_current_probcli_command.
3984 eval_string_or_file(file(bench),File,Quantifier,Expected,Recheck) :- !,
3985 ( member(Solver,[prob,kodkod,sat,'sat-z3','z3', 'cdclt',clingo]),
3986 (eval_string_or_file(file(Solver),File,Quantifier,Expected,Recheck) -> fail)
3987 ; true).
3988 eval_string_or_file(file(Solver),File,Quantifier,Expected,_) :-
3989 % evaluate a single formula stored in a file
3990 set_current_probcli_command(eval_file(Solver,File)),
3991 turn_show_error_source_off, % reduce clutter in user feedback; eval_file used in ProB Logic Calculator for example
3992 formatsilent('~nEvaluating file: ~w~n',[File]),
3993 error_manager:reset_error_scopes, % TO DO: avoid that exceptions mess up error scopes in eval_string/file
3994 statistics(runtime,[Start,_]),
3995 statistics(walltime,[W1,_]),
3996 (Expected=='TRUE' -> TypeInfo=predicate(_) % avoids parsing as expression
3997 ; true),
3998 (eval_file(Solver,File,Quantifier,Result,EnumWarning,TypeInfo)
3999 -> statistics(walltime,[W2,_]), WT is W2-W1,
4000 translate_solver_result(Result,Infos),
4001 accumulate_file_infos(File,Solver,[walltime-WT|Infos]),
4002 add_eval_result(Result),
4003 eval_check_result(Result,Expected,EnumWarning,eval_file,File)
4004 ; statistics(walltime,[W2,_]), WT is W2-W1,
4005 accumulate_file_infos(File,Solver,[failure-1,false-0,true-0,unknown-1,walltime-WT]),
4006 add_eval_result(eval_file_failed),
4007 print_error('Eval from file failed: '), print_error(File),
4008 error_occurred(eval_file)
4009 ),
4010 statistics(runtime,[Stop,_]), Time is Stop - Start,
4011 debug_format(19,'Time for ~w : ~w ms (~w ms walltime)~n',[File,Time,WT]),
4012 turn_show_error_source_on,
4013 unset_current_probcli_command.
4014
4015 translate_solver_result('TRUE',I) :- !, I=[false-0,true-1,unknown-0].
4016 translate_solver_result('FALSE',I) :- !, I=[false-1,true-0,unknown-0].
4017 translate_solver_result('UNKNOWN',I) :- !,I=[false-0,true-0,unknown-1].
4018 translate_solver_result('**** TIME-OUT ****',I) :- !,I=[false-0,true-0,unknown-1].
4019 translate_solver_result(_,[false-0,true-0,unknown-1]). % we could record this as error
4020
4021 eval_check_result(StringResult,Expected,_,Origin,File) :- Expected\=StringResult,!,
4022 format_error_with_nl('! Evaluation error, expected result to be: ~w (but was ~w) in ~w',[Expected,StringResult,File]),
4023 error_occurred(Origin).
4024 eval_check_result('NOT-WELL-DEFINED',Expected,_,Origin,File) :- var(Expected),!,
4025 format_error_with_nl('! Evaluation NOT-WELL-DEFINED in ~w',[File]),
4026 error_occurred(Origin).
4027 eval_check_result(_,_,EnumWarning,_,_) :- eval_gen_enum_warning(EnumWarning).
4028
4029 eval_gen_enum_warning(false) :- !.
4030 eval_gen_enum_warning(time_out) :- !,error_occurred(eval_string_time_out).
4031 eval_gen_enum_warning(_) :- print_error('Enumeration warning occurred'),
4032 error_occurred(eval_string_enum_warning,warning).
4033 %repl :- repl_evaluate_expressions([]).
4034 :- use_module(parsercall,[ensure_console_parser_launched/0]).
4035 repl_evaluate_expressions(StartFiles) :-
4036 get_errors, % first clear any errors from earlier commands
4037 nl,
4038 print('ProB Interactive Expression and Predicate Evaluator '), nl,
4039 print('Type ":help" for more information.'),nl,
4040 turn_show_error_source_off, % reduce clutter in user feedback
4041 (option(evaldot(File))
4042 -> print('Solutions written to dot file: '), print(File),nl
4043 ; true
4044 ),
4045 (ensure_console_parser_launched
4046 -> maplist(prob_cli:set_repl_input_file(verbose),StartFiles),
4047 top_level_eval
4048 ; print_repl_prompt, write('ABORTING REPL'),nl),
4049 turn_show_error_source_on.
4050
4051 :- use_module(user_interrupts,[interruptable_call/1]).
4052 top_level_eval :-
4053 catch(top_level_eval1, halt(0), (format('~s', ["Bye."]), nl)).
4054
4055 :- use_module(tools_printing,[reset_terminal_colour/1, print_red/1, print_green/1, print_blue/1,
4056 get_repl_prompt/1, get_repl_continuation_prompt/1]).
4057 print_repl_prompt :- get_repl_prompt(Prompt), write(Prompt),reset_terminal_colour(user_output).
4058 print_repl_prompt_s(_) :- option_silent_set,!.
4059 print_repl_prompt_s(P) :- print_repl_prompt(P).
4060 print_repl_prompt(P) :- reset_terminal_colour(user_output), write(P).
4061 %print_repl_prompt(P) :- tools_printing:start_terminal_colour(dark_gray,user_output), write(P), reset_terminal_colour(user_output).
4062
4063 top_level_eval1 :-
4064 (interruptable_call(eval1) -> true
4065 ; print_red('Evaluation failed or interrupted'),nl,
4066 print_repl_prompt('Use :q to quit REPL'),nl),
4067 reset_errors,
4068 top_level_eval1.
4069 eval0 :- store_last_error_location_for_repl,
4070 reset_errors, % get_errors prints errors again and quits in -strict mode
4071 % However, reset_errors means that in subsequent REPL runs errors are not printed again!!
4072 garbage_collect, eval1.
4073 eval1 :- repl_multi_read_line(Expr), eval_probcli_repl_line(Expr).
4074
4075 :- dynamic last_repl_error/2.
4076 store_last_error_location_for_repl :-
4077 retractall(last_repl_error(_,_)),
4078 check_error_span_file_linecol(_,File,Line,_,_,_),!,
4079 assertz(last_repl_error(File,Line)).
4080 store_last_error_location_for_repl.
4081
4082 :- dynamic current_repl_input_stream/2.
4083 close_repl_input_stream(file_closed) :- retract(current_repl_input_stream(X,File)),!,
4084 format(":replayed ~w~n",[File]),
4085 close(X).
4086 close_repl_input_stream(no_file).
4087 :- use_module(tools_io,[safe_open_file/4]).
4088 set_repl_input_file(_,File) :- current_repl_input_stream(_,File),!,
4089 add_error(set_repl_input_file,'Cyclic file replay: ',File).
4090 set_repl_input_file(Verbose,File) :-
4091 % close_repl_input_stream, % this way we allow one REPL file to call another
4092 safe_open_file(File,read,Stream,[encoding(utf8)]),!,
4093 (Verbose=verbose -> format('Replaying REPL commands in file: ~w~n',[File]) ; true),
4094 asserta(current_repl_input_stream(Stream,File)).
4095 set_repl_input_file(_,_).
4096
4097 repl_multi_read_line(Line) :-
4098 (current_repl_input_stream(Stream,_)
4099 -> repl_multi_read_line(Stream,Line),
4100 format(user_output,'~s~n',[Line])
4101 ; repl_multi_read_line(user_input,Line)
4102 ).
4103 repl_multi_read_line(Stream,Line) :-
4104 get_repl_prompt(Prompt),
4105 repl_multi_read_line_aux(Stream,Prompt,[],Line).
4106 repl_multi_read_line_aux(Stream,Prompt,SoFar,Line) :-
4107 prompt(OldPrompt,Prompt),
4108 call_cleanup(read_line(Stream,L), prompt(_,OldPrompt)),
4109 (L=end_of_file -> close_repl_input_stream(FileC),
4110 (SoFar=[], FileC = file_closed
4111 -> repl_multi_read_line(Line) % last line of file empty; do not process
4112 ; FileC = file_closed -> Line=SoFar
4113 ; Line=end_of_file) % user pressed CTRL-D
4114 ; append(LFront,[92],L) % line ends with slash \
4115 -> append(LFront,[10],LFront2), % insert newline instead;
4116 % note cleanup_newlines in parsercall transforms this into 8232 \x2028 Unicode
4117 append(SoFar,LFront2,NewSoFar),
4118 get_repl_continuation_prompt(NewPrompt),
4119 repl_multi_read_line_aux(Stream,NewPrompt,NewSoFar,Line)
4120 ; append(SoFar,L,Line)).
4121
4122 :- use_module(eval_strings).
4123 :- dynamic trace_eval/0.
4124
4125 generate_atom_list([],[],R) :- !, R=[].
4126 generate_atom_list([],Last,[NewAtom]) :-
4127 reverse(Last,RL),
4128 atom_codes(NewAtom,RL).
4129 generate_atom_list([39|X],[],[QuotedAtom|T]) :- !,
4130 get_quoted_atom(X,[],QuotedAtom,Rest),
4131 strip_leading_ws(Rest,X2),
4132 generate_atom_list(X2,[],T).
4133 generate_atom_list([32|X],Last,[NewAtom|T]) :- !,
4134 reverse(Last,RL),
4135 atom_codes(NewAtom,RL),
4136 strip_leading_ws(X,X2),
4137 generate_atom_list(X2,[],T).
4138 generate_atom_list([H|X],Last,Res) :- generate_atom_list(X,[H|Last],Res).
4139
4140 get_quoted_atom([],Acc,QuotedAtom,[]) :- reverse(Acc,R), atom_codes(QuotedAtom,R).
4141 get_quoted_atom([39|T],Acc,QuotedAtom,T) :- !, reverse(Acc,R), atom_codes(QuotedAtom,R).
4142 get_quoted_atom([H|T],Acc,QuotedAtom,Rest) :- get_quoted_atom(T,[H|Acc],QuotedAtom,Rest).
4143
4144
4145 strip_leading_ws([32|X],R) :- !, strip_leading_ws(X,R).
4146 strip_leading_ws(X,X).
4147
4148 :- meta_predicate call_probcli_option(0).
4149 call_probcli_option(_:Option) :- just_assert_option(Option), !,
4150 (option(Option) -> true ; assert_option(Option)).
4151 call_probcli_option(_:statistics) :- !, % avoid calling SICS version
4152 cli_print_statistics(full).
4153 call_probcli_option(Option) :-
4154 catch(call(Option), error(existence_error(A,B),E), (
4155 treat_existence_error(A,B,E,Option),
4156 nl % ensure that next prompt is printed
4157 )).
4158
4159 % commands that require no execution; just asserting option(.)
4160 just_assert_option(depth_first).
4161 just_assert_option(breadth_first).
4162 just_assert_option(strict_raise_error).
4163 just_assert_option(no_deadlocks).
4164 just_assert_option(no_invariant_violations).
4165 just_assert_option(no_goal).
4166 just_assert_option(no_ltl).
4167 just_assert_option(no_assertion_violations).
4168 just_assert_option(no_state_errors).
4169 just_assert_option(no_counter_examples).
4170
4171 treat_existence_error(source_sink,File,E,Option) :- !,
4172 format_with_colour_nl(user_error,[red],
4173 '* Could not find file ~w~n* for probcli command ~w~n* Detailed error: ~w',[File,Option,E]).
4174 treat_existence_error(_,_,E,Option) :-
4175 format_with_colour_nl(user_error,[red],
4176 '* probcli command not yet supported in REPL: ~w~n* Error: ~w',[Option,E]).
4177
4178 reload_mainfile :-
4179 file_loaded(_,MainFile),
4180 reset_errors,
4181 print_repl_prompt_s('Reloading and initialising file: '), print_repl_prompt_s(MainFile),nl,
4182 clear_loaded_files,
4183 load_main_file(MainFile,0,_),
4184 get_errors,
4185 cli_start_animation(0),
4186 cli_start_initialisation(0).
4187
4188 % REPL EVAL LOOP:
4189 eval_probcli_repl_line(end_of_file) :- !, eval_line(end_of_file).
4190 eval_probcli_repl_line(Line) :- strip_ws(Line,SLine),
4191 catch(eval_line(SLine), E, (
4192 E=halt(_) -> throw(E) % e.g., coming from :quit; will be caught above
4193 ; E=unwind(_) -> throw(E) % from SWI-Prolog
4194 ; E='$aborted' -> throw(E) % thrown by SWI-Prolog on abort by user
4195 ; add_error(repl,'Uncaught Exception in REPL: ',E),
4196 nl % ensure that next prompt is printed
4197 )).
4198
4199 % strip whitespace at end and beginning
4200 strip_ws([H|T],Res) :- is_ws(H),!, strip_ws(T,Res).
4201 strip_ws(C,Res) :- reverse(C,CR), strip_ws2(CR,SCR), reverse(SCR,Res).
4202 strip_ws2([H|T],Res) :- is_ws(H),!, strip_ws2(T,Res).
4203 strip_ws2(R,R).
4204
4205 is_ws(32).
4206
4207 :- use_module(performance_messages,[toggle_perfmessages/0]).
4208 eval_line([]) :- !, print_repl_prompt('Type :q or :quit to quit.'),nl,eval0.
4209 eval_line(end_of_file) :- !, halt_exception(0).
4210 % Haskell GHCI like syntax
4211 eval_line(":r") :- !, eval_line("--reload").
4212 eval_line(":reload") :- !, eval_line("--reload").
4213 eval_line("--reload") :- !,
4214 (reload_mainfile -> true ; get_errors,print_repl_prompt('Error(s) occured during reload (use :e to jump to first error)'),nl),
4215 eval0.
4216 eval_line(":rx") :- !, reload_external_libraries, get_errors, eval0.
4217 % TO DO: other Haskell commands :info E :l FILE , let pattern = expression
4218 eval_line(":prefs") :- !,print_eclipse_prefs, eval0.
4219 eval_line([45|Command]) :- % -command
4220 generate_atom_list([45|Command],[],ArgV),
4221 %print(argv(ArgV)),nl,
4222 % try and parse like commands passed to probcli
4223 get_options(ArgV,recognised_cli_option,Options,[],Err=true),
4224 !,
4225 (Err==true -> print_red('Cannot execute probcli command'),nl
4226 ; print_repl_prompt('Executing probcli command: '),print_repl_prompt(Options),nl,!,
4227 (maplist(prob_cli:call_probcli_option,Options) -> true
4228 ; print_red('Failed to execute probcli command'),nl)
4229 ),
4230 eval0.
4231 eval_line("+") :- !, add_last_expression_to_unit_tests, eval0.
4232 eval_line("$+") :- !, preferences:temporary_set_preference(expand_avl_upto,-1,CHNG),
4233 print_last_value,preferences:reset_temporary_preference(expand_avl_upto,CHNG),
4234 eval0.
4235 eval_line(Command) :- append("$file ",FC,Command),!, atom_codes(File,FC),
4236 print_last_value_to_file(File).
4237 %eval_line("$$") :- !, print_last_expression, eval0. % now in eval_strings
4238 eval_line("$$$") :- !, % $$0 - $$9 commands to print last expression with indentation
4239 indent_print_last_expression, eval0.
4240 %eval_line("$") :- !, print_last_info, eval0. % now in eval_strings
4241 eval_line("!trace") :- !, eval_line("^").
4242 eval_line("^") :- !,
4243 (retract(trace_eval) -> print_repl_prompt('TRACING OFF'),nl
4244 ; assertz(trace_eval), print_repl_prompt('TRACING ON'),nl), eval0.
4245 eval_line("!observe") :- !, toggle_observe_evaluation.
4246 eval_line("!v") :- !, tcltk_turn_debugging_off.
4247 eval_line("!p") :- !, toggle_perfmessages.
4248 eval_line("!perf") :- !, toggle_perfmessages.
4249 eval_line("!profile") :- !, eval_line("%").
4250 eval_line("!print_profile") :- !, eval_line("%%").
4251 eval_line("%") :- !, print_repl_prompt('PROFILING : '), %spy([avl:avl_size/2]),
4252 (current_prolog_flag(profiling,on)
4253 -> set_prolog_flag(profiling,off), print('OFF') ;
4254 set_prolog_flag(profiling,on), print('ON')),
4255 nl,print_repl_prompt('USE %% to print profile info'),nl,eval0.
4256 eval_line("%%") :- !, nl,print_repl_prompt('PROLOG PROFILE INFORMATION:'), nl,
4257 catch(print_profile,
4258 error(existence_error(_,_),_),
4259 print_red('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
4260 nl,
4261 debug:timer_statistics,
4262 eval0.
4263 eval_line("!print_coverage") :- !, nl,print_repl_prompt('PROLOG COVERAGE INFORMATION:'), nl,
4264 (current_prolog_flag(source_info,on) -> true ; print_red('Only useful when current_prolog_flag(source_info,on)!'),nl),
4265 catch(print_coverage,
4266 error(existence_error(_,_),_),
4267 print_red('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
4268 nl,
4269 eval0.
4270 eval_line("!profile_reset") :- !, nl,print_repl_prompt('RESETTING PROLOG PROFILE INFORMATION'), nl,
4271 catch(profile_reset,
4272 error(existence_error(_,_),_),
4273 print_red('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
4274 eval0.
4275 eval_line("%%%") :- !, nl,print('PROFILE INFORMATION (Starting TK Viewer):'), nl,
4276 catch(
4277 (use_module(library(gauge)), gauge:view),
4278 error(existence_error(_,_),_),
4279 print_red('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
4280 nl,
4281 eval0.
4282 eval_line("!debug") :- !,
4283 print_repl_prompt('ENTERING PROLOG DEBUG MODE:'),
4284 catch(
4285 debug,
4286 error(existence_error(_,_),_),
4287 print_red('CAN ONLY BE USED WHEN RUNNING PROB FROM SOURCE')),
4288 nl,
4289 eval0.
4290 eval_line("@") :- !, get_preference(find_abort_values,OldVal),
4291 print_repl_prompt('Try more aggressively to detect ill-defined expressions: '),
4292 (OldVal=true -> Val=false ; Val=true), print(Val),nl,
4293 temporary_set_preference(find_abort_values,Val) , eval0.
4294 eval_line("!") :- !, toggle_eval_det,eval0.
4295 eval_line("!norm") :- !, toggle_normalising,eval0.
4296 eval_line(Codes) :- parse_eval_command(Codes,CommandName,Argument),!,
4297 debug_println(9,executing_eval_command(CommandName,Argument)),
4298 (exec_eval_command(CommandName,Argument) -> eval0
4299 ; format_with_colour_nl(user_error,[red,bold],'Command ~w failed',[CommandName]),
4300 eval0).
4301 eval_line(ExpressionOrPredicate) :- (trace_eval -> trace ; true),
4302 (eval_codes(ExpressionOrPredicate,exists,_,_,_,_)
4303 -> eval0
4304 ; print_red('Evaluation failed'),nl,eval0).
4305
4306 parse_eval_command([C|Rest],CommandName,Argument) :- [C]=":",
4307 eval_command(Cmd,CommandName),
4308 append(Cmd,RestArg,Rest),
4309 (RestArg = [Letter1|_] -> is_ws(Letter1) /* otherwise command name continues */ ; true),
4310 strip_ws(RestArg,Argument),
4311 (eval_command_help(CommandName,[],_), Argument = [_|_]
4312 -> format_with_colour_nl(user_error,[red],'WARNING: Command ~w does not take arguments!',[CommandName])
4313 ; eval_command_help(CommandName,[_|_],_), Argument = []
4314 -> format_with_colour_nl(user_error,[red],'WARNING: Command ~w requires arguments!',[CommandName])
4315 ; true).
4316
4317 % TO DO: some of these commands should also be made available in the Tcl/Tk Console
4318 eval_command("q",quit).
4319 eval_command("quit",quit).
4320 eval_command("halt",quit).
4321 eval_command("x",exit).
4322 eval_command("exit",exit).
4323 eval_command("f",find).
4324 eval_command("find",find).
4325 eval_command("*",apropos).
4326 eval_command("apropos",apropos).
4327 eval_command("help",help).
4328 eval_command("h",help).
4329 eval_command("?",help).
4330 eval_command("ctl",ctl(init)). % :ctl
4331 eval_command("ctlh",ctl(starthere)). % :ctlh
4332 eval_command("ltl",ltl(init)). % :ltl
4333 eval_command("ltlh",ltl(starthere)). % :ltlh
4334 eval_command("pctl",pctl(init)). % :pctl
4335 eval_command("pctlh",pctl(starthere)). % :pctlh
4336 eval_command("reset",reset_animator(hard)). % :reset
4337 eval_command("reset-history",reset_animator(history_only)). % :reset
4338 eval_command("statistics",statistics).
4339 eval_command("stats",statistics). % :stats
4340 eval_command("states",state_space_stats). % :states
4341 eval_command("state",show_state_info(2000)). % :state
4342 eval_command("statespace",state_space_display). % :statespace
4343 eval_command("u",unsat_core).
4344 %eval_command("core",unsat_core).
4345 eval_command("show",show_last_as_table). % :show
4346 eval_command("dot",show_last_as_dot(no_dot_viewing)). % :dot
4347 eval_command("dotty",show_last_as_dot(dotty)).
4348 eval_command("dotpdf",show_last_as_dot(dot)).
4349 eval_command("sfdp",show_last_as_dot(sfdp)).
4350 eval_command("browse",browse). % :browse
4351 eval_command("abstract_constants",check_abstract_constants). % :abstract_constants
4352 eval_command("det_check_constants",det_check_constants). % :det_check_constants
4353 eval_command("b",browse).
4354 eval_command("hbrowse",hbrowse). % :hbrowse browse hiearchy
4355 eval_command("hshow",hshow). % show inclusion hieararchy
4356 eval_command("comp",show_components). % :comp
4357 eval_command("replay",replay_repl_file). % :replay
4358 eval_command("trim",trimcore). % :trim
4359 eval_command("src",show_source). %:src
4360 eval_command("source",show_source). %:source
4361 eval_command("origin",show_origin). %:origin
4362 eval_command("edit",edit_main_file).
4363 eval_command("e",edit_main_file). % :e
4364 eval_command("comment",comment).
4365 eval_command("machine",show_machine_info(statistics)). %:machine
4366 eval_command("machine-stats",show_machine_info(statistics)). %:machine
4367 eval_command("files",show_machine_info(files)). %:files
4368 eval_command("syntax",syntax_help). % :syntax
4369 eval_command("open",open_file). % :open
4370 eval_command("version",print_version(full)). %:version
4371
4372 available_commands(SLC) :-
4373 findall(Cmd,(eval_command(Cs,_),atom_codes(Cmd,[58|Cs])), LC),
4374 sort(LC,SLC).
4375
4376 eval_command_help(exit,[],'Exit ProB').
4377 eval_command_help(find,['P'],'Find state in state-space which makes LTL atomic proposition P true; LTL Propositions: {B-Pred}, e(Op), [Op], true, false, sink').
4378 eval_command_help(ltl(starthere),['F'],'Check LTL formula F starting from current state').
4379 eval_command_help(ltl,['F'],'Check LTL formula F; LTL Operators: G,F,X,U,W,R,not,&,or,=>; LTL Propositions: {B-Pred}, e(Op), [Op], true, false, sink; Past-LTL Operators: Y,H,O,S,T (dual to X,G,F,U,R)').
4380 eval_command_help(ctl(starthere),['F'],'Check CTL formula F starting from current state').
4381 eval_command_help(ctl(_),['F'],'Check CTL formula F in all initial states; CTL Syntax: ExUy,EXx,AXx,EFx,AGx,EX[Op]x,e(Op),{B-Pred}').
4382 eval_command_help(pctl(starthere),['F'],'Check PCTL formula F starting from current state').
4383 eval_command_help(pctl(_),['F'],'Check PCTL formula F; PCTL Operators: not, &, or, =>, {B-Pred}, e(Op), [Op], true, false, sink, P op {Exp} [PathFormula] with op in {<,<=,>=,>,=}; Path operators: X, U, F, G, U<=Bound, F<=Bound, G<=Bound').
4384 eval_command_help(browse,opt('PAT'),'Browse available constants, variables, sets and lets introduced in REPL').
4385 eval_command_help(apropos,['PAT'],'Find constant or variable whose names contains PAT').
4386 eval_command_help(hbrowse,['PAT'],'Browse machine hierarchy for all identifiers whose names contains PAT').
4387 eval_command_help(hshow,[],'Show machine inclusion hierarchy using topological sorting').
4388 eval_command_help(show_components,[],'Show components of PROPERTIES').
4389 eval_command_help(abstract_constants,[],'Show ABSTRACT_CONSTANTS and check if can be fully evaluated').
4390 eval_command_help(det_check_constants,[],'Check if values of CONSTANTS are forced and explain if they are').
4391 eval_command_help(show_last_as_table,[],'Show last evaluated expression in tabular form').
4392 eval_command_help(show_last_as_dot(_),['F'],'Show expression or predicate F as dot graph').
4393 eval_command_help(unsat_core,[],'Compute Unsatisfiable Core of last evaluated predicate').
4394 eval_command_help(help,opt('CMD'),'Provide help about REPL command CMD').
4395 eval_command_help(replay_repl_file,['FILE'],'Replay FILE of REPL commands').
4396 eval_command_help(reset_animator(_),[],'Reset history and statespace of animator').
4397 eval_command_help(show_source,['ID'],'Show origin and source code definition of identifier ID').
4398 eval_command_help(show_origin,['ID'],'Show origin of identifier ID and try opening in EDITOR').
4399 eval_command_help(show_machine_info(_),[],'Show statistics about loaded machine and files').
4400 eval_command_help(state_space_stats,[],'Show statistics about state space').
4401 eval_command_help(state_space_display,[],'Show complete state space transitions (could be very big !)').
4402 eval_command_help(show_state_info(_),[],'Show current state').
4403 eval_command_help(statistics,[],'Show statistics about last evaluation').
4404 % -machine_stats : cli_print_machine_info(statistics) -machine_files : cli_print_machine_info(files)
4405 eval_command_help(trim,[],'Trim memory usage of probcli (try and give memory back to the OS)').
4406 % implemented in eval_strings:
4407 eval_command_help(type,['E'],'Show type of expression E').
4408 eval_command_help(cvc5,['P'],'Solve predicate P using cvc5 solver (formerly CVC4)').
4409 eval_command_help(kodkod,['P'],'Solve predicate P using SAT solver via Kodkod').
4410 eval_command_help(z3,['P'],'Solve predicate P using Z3 solver').
4411 eval_command_help('z3-free',['P'],'Solve predicate P using Z3 solver (ignoring current state)').
4412 eval_command_help('z3-file',['F'],'Solve predicate in File F using Z3 solver').
4413 eval_command_help('z3-free-file',['F'],'Solve predicate in File F using Z3 solver (ignoring current state)').
4414 eval_command_help(cdclt,['P'],'Solve predicate P using Prolog CDCL(T) solver').
4415 eval_command_help(cdclt-free,['P'],'Solve predicate P using Prolog CDCL(T) solver (ignoring current state)').
4416 eval_command_help(prob,['P'],'Solve predicate P using ProB solver (ignoring current state)').
4417 eval_command_help('prob-file',['F'],'Solve predicate in File F using ProB solver (ignoring current state)').
4418 eval_command_help(edit_main_file,opt('ID'),'Edit main file (or origin of identifier ID) using EDITOR (path_to_text_editor preference)').
4419 eval_command_help(comment,['STRING'],'provide STRING as a comment (mainly useful for :replay files)').
4420 eval_command_help(syntax_help,[],'Show a summary of the B syntax accepted by the REPL').
4421 eval_command_help(open_file,['FILE'],'Open FILE in preferred application.').
4422
4423 print_eval_command_help(Codes) :-
4424 eval_command(Codes,Cmd),
4425 eval_command_help(Cmd,Args,Descr),
4426 (Args = []
4427 -> format('Command ~w~n Syntax :~s~n ~w~n',[Cmd,Codes,Descr])
4428 ; Args=[Arg] -> format('Command ~w~n Syntax :~s ~w~n ~w~n',[Cmd,Codes,Arg,Descr])
4429 ; Args=opt(Arg) -> format('Command ~w~n Syntax :~s [~w]~n ~w~n',[Cmd,Codes,Arg,Descr])
4430 ; format('Command ~w~n Syntax :~s ~w~n ~w~n',[Cmd,Codes,Args,Descr])).
4431
4432 :- use_module(tools_commands,[show_dot_file/1, show_pdf_file/1, gen_dot_output/4]).
4433 :- use_module(state_space,[transition/4]).
4434 :- use_module(b_machine_hierarchy,[print_machine_topological_order/0]).
4435 exec_eval_command(quit,_) :- !, halt_exception(0).
4436 exec_eval_command(exit,_) :- !,halt.
4437 exec_eval_command(browse,CodesToMatch) :- !,
4438 (CodesToMatch=[] -> browse % maybe merge with apropos functionality
4439 ; exec_eval_command(apropos,CodesToMatch)).
4440 exec_eval_command(find,FORMULA) :-
4441 atom_codes(APF,FORMULA),cli_find_ltl_ap(APF).
4442 exec_eval_command(apropos,CodesToMatch) :- /* :* Pattern (apropos command) */
4443 browse_machine(CodesToMatch).
4444 exec_eval_command(hbrowse,CodesToMatch) :- /* :* Pattern (hbrowse command) */
4445 browse_all_machines(CodesToMatch).
4446 exec_eval_command(hshow,_) :- /* show inclusion hierarhcy */
4447 print_machine_topological_order.
4448 exec_eval_command(show_components,_) :-
4449 print_property_partitions.
4450 exec_eval_command(check_abstract_constants,_) :-
4451 check_abstract_constants.
4452 exec_eval_command(det_check_constants,_) :-
4453 det_check_constants.
4454 exec_eval_command(help,Arg) :-
4455 (Arg=[] -> eval_help
4456 ; print_eval_command_help(Arg) -> true
4457 ; (Arg=[58|RA],print_eval_command_help(RA)) -> true % remove : at front
4458 ; format('Cannot provide help about ~s~n',[Arg]),
4459 available_commands(LC), format('Available commands: ~w~n',[LC])
4460 ).
4461 exec_eval_command(ctl(Mode),FORMULA) :- % :ctl or :ctlh for ctl here
4462 atom_codes(F,FORMULA),
4463 (cli_ctl_model_check(F,Mode,_,Status)
4464 -> (Status=false -> write_history_to_user_output([show_init,show_states]) ; true)
4465 ; print('CTL Syntax: ExUy,EXx,AXx,EFx,AGx,EX[Op]x,e(Op),{B-Pred}'),nl).
4466 exec_eval_command(ltl(Mode),FORMULA) :- % :ltl or :ltlh with Mode = init or starthere
4467 atom_codes(F,FORMULA),
4468 (cli_ltl_model_check(F,Mode,_,Status)
4469 -> (Status=no -> write_history_to_user_output([show_init,show_states]) ; true)
4470 ; print('LTL Operators: G,F,X,U,W,R,not,&,or,=>,<=>'),nl,
4471 print('LTL Propositions: {B-Pred}, e(Op), [Op], true, false, sink'),nl,
4472 print('Past-LTL Operators: Y,H,O,S,T (dual to X,G,F,U,R)'),nl
4473 ).
4474 exec_eval_command(pctl(Mode),FORMULA) :- % :pctl or :pctlh with Mode = init or starthere
4475 atom_codes(F,FORMULA),
4476 (cli_pctl_model_check(F,Mode,_,Status)
4477 -> (Status=no -> write_history_to_user_output([show_init,show_states]) ; true)
4478 ; print('PCTL Propositional Operators: not, &, or, =>'),nl,
4479 print('PCTL State Formula: P op {Exp} [PathFormula] with op in {<,<=,>=,>,=}'),nl,
4480 print('PCTL Path Formulas: X phi, phi1 U phi2, F phi, G phi'),nl,
4481 print('PCTL Bounded Path Formulas: phi1 U<=Bound phi2, F<=Bound phi, G<=Bound phi'),nl,
4482 print('PCTL Propositions: {B-Pred}, e(Op), [Op], true, false, sink'),nl
4483 ).
4484 exec_eval_command(reset_animator(Hard),_) :- !,
4485 get_state_space_stats(TotalNodeSum,TotalTransSum,_,_),
4486 (Hard=hard ->
4487 format('Resetting statespace (~w states, ~w transitions)~n',[TotalNodeSum,TotalTransSum]),
4488 reset_animator
4489 ; format('Resetting animation history (keeping statespace: ~w states, ~w transitions)~n',[TotalNodeSum,TotalTransSum]),
4490 tcltk_reset % only resets animation history,...
4491 ).
4492 exec_eval_command(statistics,_) :- !, print_last_info.
4493 exec_eval_command(state_space_stats,_) :- !, % :states
4494 get_state_space_stats(TotalNodeSum,TotalTransSum,Processed,Ignored),
4495 (Ignored>0
4496 -> format('Statespace: ~w states (~w processed, ~w ignored) and ~w transitions.~n',
4497 [TotalNodeSum,Processed,Ignored,TotalTransSum])
4498 ; format('Statespace: ~w states (~w processed) and ~w transitions.~n',[TotalNodeSum,Processed,TotalTransSum])).
4499 exec_eval_command(state_space_display,_) :- !, % :statespace
4500 ( visited_expression(ID,State),
4501 functor(State,F,N),
4502 format('State ID ~w (~w/~w)~n',[ID,F,N]),
4503 transition(ID,OperationTerm,_OpID,ToID),
4504 get_operation_name(OperationTerm,OpName),
4505 format(' -> ~w (~w)~n',[ToID,OpName]),
4506 fail
4507 ;
4508 current_state_id(ID),
4509 format('Current State ID ~w~n',[ID])
4510 ).
4511 exec_eval_command(show_state_info(Limit),_) :- !, % :state
4512 (current_expression(ID,CurState)
4513 ->
4514 expand_const_and_vars_to_full_store(CurState,EState),
4515 format('Current state id ~w : ~n',[ID]), % MAX_DISPLAY_SET
4516 translate:print_bstate_limited(EState,Limit,-1),nl,
4517 (\+ not_all_transitions_added(ID),
4518 format('Outgoing transitions of state id ~w:~n',[ID]),
4519 transition(ID,OperationTerm,_OpID,ToID),
4520 get_operation_name(OperationTerm,OpName),
4521 format(' -> ~w (~w)~n',[ToID,OpName]),
4522 fail
4523 ; true)
4524 ; print_red('No current state available!'),nl
4525 ).
4526 exec_eval_command(unsat_core,_) :- !, % :core :u
4527 unsat_core_last_expression.
4528 exec_eval_command(trimcore,_) :- !, % :trim
4529 prob_trimcore_verbose.
4530 exec_eval_command(show_last_as_table,_) :- !, % :show
4531 show_last_expression_as_table.
4532 exec_eval_command(syntax_help,_) :- !, % :syntax
4533 syntax_help.
4534 exec_eval_command(show_last_as_dot(Show),Arg) :- !,
4535 (Arg = [] -> print('*** :dot requires an expression or predicate as argument.'),nl
4536 ; safe_absolute_file_name('~/probcli_repl.dot',AFile),
4537 set_eval_dot_file(AFile),
4538 format('Displaying evaluation result in: ~w~n',[AFile]),
4539 (eval_codes(Arg,exists,_,_,_,_) -> true ; true), unset_eval_dot_file,
4540 ( Show=no_dot_viewing -> true
4541 ; Show=dotty -> show_dot_file(AFile)
4542 ; safe_absolute_file_name('~/probcli_repl.pdf',PDFFile),
4543 gen_dot_output(AFile,Show,pdf,PDFFile),
4544 show_pdf_file(PDFFile)
4545 )).
4546 exec_eval_command(replay_repl_file,FILEC) :- !, % :replay
4547 atom_codes(File,FILEC),
4548 set_repl_input_file(not_verbose,File).
4549 exec_eval_command(show_source,IDC) :- !, % :src
4550 trim_id_back_quotes(IDC,TIDC),atom_codes(ID,TIDC),
4551 show_source(ID).
4552 exec_eval_command(show_origin,IDC) :- !, % :origin
4553 trim_id_back_quotes(IDC,TIDC),atom_codes(ID,TIDC),
4554 show_origin(ID).
4555 exec_eval_command(show_machine_info(X),_) :- !, % :machine
4556 cli_print_machine_info(X).
4557 exec_eval_command(edit_main_file,Arg) :- !, % :e
4558 (Arg=[] -> edit_main_file
4559 ; trim_quotes(Arg,FC), atom_codes(File,FC), file_exists(File) -> edit_file(File,unknown)
4560 ; exec_eval_command(show_origin,Arg)).
4561 exec_eval_command(open_file,FILEC) :- !, % :open
4562 (FILEC=[] -> open_file('.')
4563 ; atom_codes(File,FILEC),
4564 open_file(File)
4565 ).
4566 exec_eval_command(comment,_Arg) :- !. % do nothing; argument was a comment; mainly useful for :replay files
4567 exec_eval_command(print_version(V),_Arg) :- !, print_version(V).
4568
4569
4570 trim_id_back_quotes([96|T],Res) :- append(Res,[96],T),!.
4571 trim_id_back_quotes(R,R).
4572
4573 trim_quotes([34|T],Res) :- append(Res,[34],T),!. % double quotes
4574 trim_quotes([39|T],Res) :- append(Res,[39],T),!. % single quotes
4575 trim_quotes(R,R).
4576
4577 :- use_module(tools_commands,[edit_file/2, open_file/1]).
4578 edit_main_file :- last_repl_error(File,Line),
4579 \+ functor(File,unknown,_), % File \= unknown(_),
4580 !,
4581 format('Showing first error from last command~n',[]),
4582 edit_file(File,Line).
4583 % Note: for the bbedit command we can also specify line numbers bbedit +LINE FILE
4584 edit_main_file :- file_loaded(_,MainFile), \+ empty_machine_loaded,
4585 !,edit_file(MainFile,unknown).
4586 edit_main_file :- format_with_colour_nl(user_error,[red],'No file loaded, cannot open EDITOR!',[]).
4587
4588
4589
4590 :- use_module(probsrc(error_manager),[extract_file_line_col/6]).
4591 open_file_at_position(OriginTerm) :-
4592 extract_file_line_col(OriginTerm,FILE,LINE,_COL,_Erow,_Ecol),
4593 edit_file(FILE,LINE).
4594
4595
4596 :- use_module(probsrc(bmachine),[source_code_for_identifier/6]).
4597 show_source(ID) :- source_code_for_identifier(ID,Kind,_Type,OriginStr,OriginTerm,Source),!,
4598 translate:translate_subst_or_bexpr(Source,PPS),
4599 %format('~w: ~w (Type: ~w)~norigin: ~w~nsource: ~w~n',[Kind,ID,_Type,Origin,PPS]).
4600 format('~w: ~w~norigin: ~w~nsource: ~w~n',[Kind,ID,OriginStr,PPS]),
4601 (OriginTerm=b(_,_,_),get_texpr_description(OriginTerm,Description)
4602 -> format('description: ~w~n',[Description]) ; true).
4603 show_source(ID) :- format_error_with_nl('! Could not find source for ~w',[ID]).
4604
4605 show_origin('') :- last_repl_error(_,_),!, % error occured: show error in editor like :e would
4606 edit_main_file.
4607 show_origin('') :- !,format_error_with_nl('! You need to provided an identifier',[]).
4608 show_origin(ID) :- source_code_for_identifier(ID,Kind,_Type,OriginStr,OriginTerm,_Source),!,
4609 format('~w: ~w~norigin: ~w~n',[Kind,ID,OriginStr]),
4610 open_file_at_position(OriginTerm).
4611 show_origin(ID) :- format_error_with_nl('! Could not find origin for ~w',[ID]).
4612
4613 profiling_on :- set_prolog_flag(profiling,on), print('% PROFILING ON'),nl.
4614 profiling_off :- set_prolog_flag(profiling,off), print('% PROFILING OFF'),nl.
4615
4616 % find a state satisfying LTL atomic property
4617 cli_find_ltl_ap(APF) :-
4618 if(ltl:find_atomic_property_formula(APF,ID),
4619 (format('Found state (id = ~w) satisfying LTL atomic property.~n',[ID]),
4620 tcltk_goto_state('LTL FIND',ID)),
4621 format('No explored state satsifies LTL atomic property.~n',[])).
4622
4623 eval_help :-
4624 print('ProB Interactive Expression and Predicate Evaluator '), nl,
4625 print('Type a valid B expressions or predicates, followed by RETURN or ENTER.'),nl,
4626 print('You can spread input over multiple lines by ending lines with "\\".'),nl,
4627 browse_machine([]),
4628 print('You can also type one of the following commands: '),nl,
4629 (option_verbose ->
4630 print(' + to save last expression to ProB unit tests.'),nl,
4631 print(' ! to go to deterministic propagation only mode.'),nl,
4632 print(' $ to print evaluation time for last expression.'),nl,
4633 print(' $$ to pretty-print last expression and its type.'),nl,
4634 print(' $$$ to pretty-print last expression in nested fashion.'),nl,
4635 print(' !p to toggle performance messages.'),nl,
4636 print(' !norm to toggle normalisation of results.'),nl,
4637 print(' :col to toggle colorizing of results.'),nl
4638 ; true),
4639 print(' :let x = E to define a new local variable x'),nl, % : optional for let
4640 print(' :unlet x to un-define a local variable'),nl,
4641 print(' #file=MYFILE to evaluate the formula in MYFILE'),nl,
4642 print(' @INVARIANT to evaluate or obtain invariant predicate'),nl,
4643 print(' @PROPERTIES, @GUARD-OpName ditto for properties and guards'),nl, % @FUZZ, @RANDOMISE also exist
4644 print(' :b or :b Prefix to browse the available identifiers'),nl,
4645 print(' :t E to get the type of an expression'),nl, % :type also works
4646 print(' :r to reload the machine'),nl,
4647 print(' :show to display the last result as a table (if possible)'),nl,
4648 print(' :list CAT to display information with CAT : {files,variables,help,...}'),nl,
4649 print(' :* P to display constants/variables containing pattern P'),nl,
4650 print(' :core Pred to compute the unsat core for Pred'),nl,
4651 print(' :u to compute the unsat core for last evaluated result'),nl,
4652 print(' :stats to print the type and evaluation time for last query'),nl,
4653 print(' -PROBCLIARGS to pass command-line probcli arguments to the REPL'),nl,
4654 print(' (e.g., -v to switch to verbose mode or -p PREF VAL to set a preference)'),nl,
4655 print(' :ctl F or :ltl F to check a CTL or LTL formula.'),nl,
4656 print(' :f F to find a state satisfying LTL atomic property.'),nl,
4657 print(' :find-value PAT to find a value in current state matching PAT.'),nl,
4658 print(' :find-value OPT "String" same with OPT = prefix, infix, suffix or fuzzy.'),nl,
4659 print(' :exec S to execute an operation or substitution S.'),nl,
4660 print(' :replay FILE to replay a file of commands.'),nl,
4661 print(' :z3 P, :cvc5 P, :kodkod P to solve predicate P using alternate solver'),nl,
4662 print(' :forall P to prove predicate P as universally quantified with default solver'),nl,
4663 print(' :prove P to prove predicate P using ProB\'s own WD prover'),nl,
4664 (option_verbose ->
4665 print(' :krt P, :pp P, :ml P to prove predicate P using Atelier-B provers if installed'),nl
4666 ; true),
4667 print(' :print P to pretty print predicate in a nested fashion'),nl,
4668 print(' :min P, :max P to find a minimal/maximal model for predicate P or %x.(P|E)'),nl,
4669 print(' :prefs to print current value of preferences'),nl,
4670 print(' :reset to reset the state space of the animator.'),nl, % :reset-history only resets history
4671 print(' :help CMD to obtain more help about a command.'),nl,
4672 print(' :state, :statespace, :states,'),nl,
4673 print(' :machine, :files, :source, :orgin, :machine-stats,'),nl,
4674 print(' :apropos, :hbrowse, :abstract_constants, :det_check_constants,'),nl,
4675 print(' :dot, :dotty, :sfdp, :trim, :comp - use :help CMD for more info'),nl,
4676 print(' :syntax to show a summary of the B syntax accepted by the REPL'),nl,
4677 print(' :q to exit.'),nl.
4678
4679 :- use_module(tools,[read_atom_from_file/3]).
4680 :- dynamic prob_summary/1.
4681
4682 :- read_atom_from_file(tclsrc('prob_summary.txt'),utf8,T), assertz(prob_summary(T)).
4683 % TODO: we could just include a shorter version with predicates and expressions
4684 % TODO: provide :syntax LTL or :syntax CTL help commands
4685 syntax_help :- prob_summary(S),
4686 format(user_output,'~w',S).
4687
4688
4689 browse :- browse_machine([]), browse_repl_lets.
4690
4691 :- use_module(bmachine,[get_machine_identifiers/2]).
4692 % the CodesToMatch parameters mimics the apropos command of the Clojure-REPL
4693 browse_machine(CodesToMatch) :-
4694 get_machine_identifiers(machines,MN), display_match('MACHINES',CodesToMatch,MN),
4695 (CodesToMatch =[] -> print_sets
4696 ; get_machine_identifiers(sets,SN), display_match('SETS',CodesToMatch,SN),
4697 get_machine_identifiers(set_constants,SCN), display_match('SETS-ELEMENTS',CodesToMatch,SCN)
4698 ),
4699 get_machine_identifiers(definition_files,DFN),
4700 (DFN=[] -> true ; display_match('DEFINITIONS FILES',CodesToMatch,DFN)),
4701 get_machine_identifiers(definitions,DN),
4702 (DN=[] -> true ; display_match('DEFINITIONS',CodesToMatch,DN)),
4703 get_machine_identifiers(constants,CN),
4704 display_match('CONSTANTS',CodesToMatch,CN),
4705 get_machine_identifiers(variables,VN),
4706 display_match('VARIABLES',CodesToMatch,VN),
4707 get_machine_identifiers(operations,Ops),
4708 display_match('OPERATIONS',CodesToMatch,Ops).
4709
4710 display_match(KIND,CodesToMatch,Ids) :- display_match(KIND,CodesToMatch,Ids,show_empty).
4711 display_match(KIND,CodesToMatch,Ids,ShowEmpty) :-
4712 include(prob_cli:atom_contains_codes(CodesToMatch),Ids,MatchingIds),
4713 length(MatchingIds,LenMIds),
4714 (LenMIds=0, ShowEmpty=show_only_if_match -> true
4715 ; sort(MatchingIds,SMatchingIds),
4716 (CodesToMatch=[]
4717 -> format(' ~w: ~w ~w~n',[KIND,LenMIds,SMatchingIds])
4718 ; length(Ids,LenIds),
4719 format('Matching ~w: ~w/~w ~w~n',[KIND,LenMIds,LenIds,SMatchingIds]))
4720 ).
4721
4722 % check if an atom contains a list of codes in its name
4723 atom_contains_codes([],_) :- !.
4724 atom_contains_codes(Codes,Name) :- atom_codes(Name,NC),
4725 append([_,Codes,_],NC).
4726
4727 :- use_module(b_global_sets,[b_global_set/1]).
4728 print_sets :- print('Available SETS: '), b_global_set(GS), print_set(GS),fail.
4729 print_sets :- nl.
4730
4731 :- use_module(probsrc(b_global_sets),[is_b_global_constant/3]).
4732 print_set(GS) :- print(GS), \+ is_b_global_constant(GS,_,_),!, print(' ').
4733 print_set(GS) :- print(' = {'), is_b_global_constant(GS,_,Cst), print(Cst), print(' '),fail.
4734 print_set(_) :- print(' } ').
4735
4736 :- use_module(b_machine_hierarchy,[get_machine_identifier_names/7]).
4737 % browse all machines, shows identifiers maybe not visible at top-level
4738 browse_all_machines(CodesToMatch) :-
4739 format('Searching machine hierarchy for identifiers matching ~s~n',[CodesToMatch]),
4740 get_machine_identifier_names(Name,Params,Sets,AVars,CVars,AConsts,CConsts),
4741 format('~nMACHINE ~w~n',[Name]),
4742 display_match('PARAMS',CodesToMatch,Params,show_only_if_match),
4743 display_match('SETS',CodesToMatch,Sets,show_only_if_match),
4744 display_match('ABSTRACT_VARIABLES',CodesToMatch,AVars,show_only_if_match),
4745 display_match('CONCRETE_VARIABLES',CodesToMatch,CVars,show_only_if_match),
4746 display_match('ABSTRACT_CONSTANTS',CodesToMatch,AConsts,show_only_if_match),
4747 display_match('CONCRETE_CONSTANTS',CodesToMatch,CConsts,show_only_if_match),
4748 fail.
4749 browse_all_machines(_).
4750
4751
4752 :- use_module(bmachine,[b_get_properties_from_machine/1]).
4753 print_property_partitions :- print('PARTITIONS OF PROPERTIES'),nl,
4754 b_get_properties_from_machine(Properties),
4755 predicate_components(Properties,Comp),
4756 length(Comp,Len), print(Len), print(' components found in PROPERTIES'),nl,
4757 nth1(Nr,Comp,component(P,Vars)),
4758 format('~n& // Component ~w/~w over identifiers ~w~n',[Nr,Len,Vars]),
4759 translate:print_bexpr(P),nl,fail.
4760 print_property_partitions :- nl, print(' ============== '),nl.
4761
4762 :- use_module(store,[lookup_value_for_existing_id/3]).
4763 :- use_module(b_machine_hierarchy,[abstract_constant/2]).
4764 check_abstract_constants :-
4765 format('Checking whether abstract constants can be expanded:~n',[]),
4766 current_expression(_ID,CurState),
4767 expand_const_and_vars_to_full_store(CurState,EState),
4768 abstract_constant(AID,_),
4769 lookup_value_for_existing_id(AID,EState,Val),
4770 get_value_type(Val,VF),
4771 format(user_output,'~n*** Evaluating ABSTRACT_CONSTANT (stored value: ~w):~n',[VF]),
4772 format_with_colour_nl(user_output,[blue],' ~w',[AID]),
4773 (debug_mode(off) -> true
4774 ; translate:translate_bvalue(Val,VS), format_with_colour_nl(user_output,[blue],' Stored value = ~w',[VS])),
4775 atom_codes(AID,C),
4776 % TO DO: provide info if value symbolic and can be expanded fully + add timing
4777 % term_size, unique in state space
4778 % this command is deprecated compared to -csv constants_analysis (i.e., tcltk_analyse_constants)
4779 eval_codes(C,exists,_,_EnumWarning,_LS,_),nl, % TO DO: call try_expand_and_convert_to_avl_with_check(Val)
4780 fail.
4781 check_abstract_constants.
4782
4783 :- use_module(probsrc(custom_explicit_sets),[is_interval_closure/3]).
4784 get_value_type(CS, Res) :- is_interval_closure(CS,_,_),!, Res = 'interval closure'.
4785 get_value_type(closure(_,_,_),Res) :- !, Res= 'symbolic closure'.
4786 get_value_type(avl_set(_), Res) :- !, Res= 'explicit AVL set'.
4787 get_value_type(Val,VF) :- functor(Val,VF,_).
4788
4789 :- use_module(b_state_model_check,[cbc_constants_det_check/1]).
4790 det_check_constants :- \+ current_state_corresponds_to_setup_constants_b_machine, !,
4791 format_with_colour_nl(user_error,[red],'This command requires to setup the constants first!',[]).
4792 det_check_constants :-
4793 current_state_id(ID),
4794 %format('Checking whether constants are forced in state ~w:~n',[ID]),
4795 cbc_constants_det_check(ID).
4796
4797 % showing relations as tables:
4798
4799 :- use_module(extrasrc(table_tools),[print_value_as_table/2]).
4800 show_last_expression_as_table :- \+ last_expression(_,_Expr),!,
4801 print_red('Please evaluate an expression or predicate first.'),nl.
4802 show_last_expression_as_table :-
4803 get_last_result_value(Expr,_,Value),
4804 print_value_as_table(Expr,Value).
4805
4806
4807 % a few definitions so that probcli commands work in REPL:
4808 :- use_module(specfile,[get_internal_representation/1]).
4809 :- use_module(tools_files,[write_to_utf8_file_or_user_output/2]).
4810 :- use_module(translate,[set_unicode_mode/0, unset_unicode_mode/0, set_atelierb_mode/1, unset_atelierb_mode/0, with_translation_mode/2]).
4811 :- public pretty_print_internal_rep/4, pretty_print_internal_rep_to_B/1.
4812 pretty_print_internal_rep(PPFILE,MachName,TYPES,TransMode) :-
4813 b_or_z_mode, !,
4814 pretty_print_internal_rep_b(PPFILE,MachName,TYPES,TransMode).
4815 pretty_print_internal_rep(PPFILE,_MachName,_TYPES,TransMode) :-
4816 with_translation_mode(TransMode,get_internal_representation(PP)),
4817 write_to_utf8_file_or_user_output(PPFILE,PP).
4818
4819 pretty_print_internal_rep_b(PPFILE,MachName,TYPES,unicode) :- !,
4820 set_unicode_mode,
4821 call_cleanup(b_write_machine_representation_to_file(MachName,TYPES,PPFILE),unset_unicode_mode).
4822 pretty_print_internal_rep_b(PPFILE,'$auto',_TYPES,atelierb) :- animation_minor_mode(eventb),!,
4823 b_write_eventb_machine_to_classicalb_to_file(PPFILE). % old -ppB option:
4824 pretty_print_internal_rep_b(PPFILE,MachName,TYPES,atelierb) :- !,
4825 set_atelierb_mode(native),
4826 call_cleanup(b_write_machine_representation_to_file(MachName,TYPES,PPFILE),unset_atelierb_mode).
4827 pretty_print_internal_rep_b(PPFILE,MachName,TYPES,camille) :-
4828 with_translation_mode(camille,b_write_machine_representation_to_file(MachName,TYPES,PPFILE)).
4829 pretty_print_internal_rep_b(PPFILE,MachName,TYPES,_) :-
4830 b_write_machine_representation_to_file(MachName,TYPES,PPFILE).
4831
4832 % -ppB option:
4833 pretty_print_internal_rep_to_B(PPFILE) :- b_write_eventb_machine_to_classicalb_to_file(PPFILE).
4834
4835 :- use_module(tools_printing,[tcltk_nested_read_prolog_file_as_codes/2]).
4836 % -pppl option: internal developer utility to pretty-print a Prolog file in nested fashion
4837 % can be useful to inspecting .prob AST files or .P XTL files
4838 pretty_print_prolog_file(PPFILE) :-
4839 file_loaded(_,MainFile),
4840 (loaded_main_file(Ext,_), \+( (Ext='P' ; Ext='prob' ; Ext= 'pl') )
4841 -> add_warning(probcli,'The -pppl command is designed to work with Prolog files (.P, .prob or .pl), not with: ',Ext) ; true),
4842 pretty_print_prolog_file(MainFile,PPFILE).
4843
4844 pretty_print_prolog_file(File,File) :- !,
4845 add_error(probcli,'Output file must be different from input Prolog file:',File).
4846 pretty_print_prolog_file(MainFile,PPFILE) :-
4847 format('Pretty-Printing Prolog file ~w to ~w~n',[MainFile,PPFILE]),
4848 tcltk_nested_read_prolog_file_as_codes(MainFile,list(Codes)),
4849 safe_intelligent_open_file(PPFILE,write,Stream),
4850 format(Stream,'~s~n',[Codes]),
4851 close(Stream).
4852
4853 :- use_module(extrasrc(source_indenter),[indent_b_file_to_codes/3]).
4854 indent_main_b_file(PPFILE) :-
4855 file_loaded(_,MainFile),
4856 indent_b_file_to_file(MainFile,PPFILE,[]).
4857
4858 indent_b_file_to_file(File,PPFILE,_) :-
4859 absolute_file_name(File,AbsFile), absolute_file_name(PPFILE,AbsFile), !, % same file, possibly spelled differently
4860 add_error(probcli,'Output file must be different from input B file:',File).
4861 indent_b_file_to_file(MainFile,PPFILE,Options) :-
4862 format('Indenting B file ~w to ~w~n',[MainFile,PPFILE]), flush_output,
4863 % read and indent the complete input before opening (and truncating) the output file,
4864 % so that the input is never lost, e.g., if both are the same file via a symbolic link
4865 indent_b_file_to_codes(MainFile,Codes,Options),
4866 safe_intelligent_open_file(PPFILE,write,OutStream),
4867 call_cleanup(format(OutStream,'~s',[Codes]),close(OutStream)).
4868
4869
4870 % Simple Animator
4871
4872 interactive_animate_machine :-
4873 nl,print('IMPORTANT: Do not use this mode for automatic tools.'),nl,
4874 print('The output format can change arbitrarily in future versions.'),nl,
4875 print('Please terminate your input with a dot (.) and then type return.'),nl,nl,
4876 animate_machine2.
4877 animate_machine2 :-
4878 print_current_state,
4879 cli_computeOperations(Ops),
4880 length(Ops,Max),
4881 print('Enabled Operations: '),nl,
4882 print_options(Ops,1),
4883 print(' ==> '),!,
4884 read(Nr),
4885 (number(Nr),Nr>0,Nr=<Max
4886 -> cli_animateOperationNr(Nr,Ops,0)
4887 ; fail
4888 ),!,
4889 animate_machine2.
4890 animate_machine2.
4891
4892 print_current_state :- current_state_id(CurID), print('ID ==> '), print(CurID),nl,
4893 getStateValues(CurID,State),
4894 print_bindings(State),
4895 (specfile:b_or_z_mode,\+is_initialised_state(CurID)
4896 -> print_red(' Not yet initialised.'),print_mode_info, debug_println(10,state(State)) ; nl).
4897
4898 print_mode_info :- animation_mode(M), (animation_minor_mode(MM) -> true ; MM=''),
4899 format('Animation Mode = ~w [~w]~n',[M,MM]).
4900
4901 cli_computeOperations(Ops) :- option(animate_stats),!, % provide statistics about the animation
4902 nl,
4903 start_probcli_timer(Timer),
4904 current_state_id(CurID),
4905 tcltk_get_options(list(Ops)),
4906 ajoin(['Time to compute all operations in state ',CurID,': '],Msg),
4907 stop_probcli_timer(Timer,Msg).
4908 cli_computeOperations(Ops) :- tcltk_get_options(list(Ops)).
4909
4910 cli_animateOperationNr(Nr,Options,StepNr) :-
4911 (option(animate_stats)
4912 -> nth1(Nr,Options,Action),
4913 truncate_animate_action(Action,TA),
4914 (StepNr>1 -> format('performing step ~w : ~w~n',[StepNr,TA])
4915 ; format('performing ~w~n',[TA]))
4916 ; true),
4917 tcltk_perform_nr(Nr).
4918
4919 :- use_module(tools_strings,[truncate_atom/3]).
4920 % optionally truncate animation action atom for printing:
4921 truncate_animate_action(Action,TA) :-
4922 (option_verbose -> TA = Action
4923 ; \+ atom(Action) -> TA = Action
4924 ; truncate_atom(Action,100,TA)).
4925
4926 perform_random_step(StepNr) :- perform_random_step(_Ops,_Len,_RanChoice,StepNr).
4927 perform_random_step(Ops,Len,RanChoice,StepNr) :-
4928 cli_computeOperations(Ops),
4929 current_state_id(CurID), check_for_errors(CurID,StepNr),
4930 length(Ops,Len), Len>0,
4931 debug_println(20,perform_random_step(Len,StepNr)),
4932 L1 is Len+1,
4933 (do_det_checking, Len>1
4934 -> print_error('Non-deterministic step in animate or init'),
4935 print_error('State:'),
4936 print_current_state, print_error('Enabled Operations: '), print_options(Ops,1),
4937 error_occurred(det_check)
4938 ; true),
4939 random(1,L1,RanChoice),
4940 debug_println(20,random(L1,RanChoice)),
4941 cli_animateOperationNr(RanChoice,Ops,StepNr).
4942
4943 :- use_module(state_space,[visited_expression/2]).
4944 check_for_errors(CurID,StepNr) :- invariant_violated(CurID),
4945 \+ option(no_invariant_violations),
4946 get_preference(do_invariant_checking,true),
4947 ajoin(['INVARIANT VIOLATED after ',StepNr,' steps (state id ',CurID,').'],ErrMsg),
4948 format('~w~n',[ErrMsg]),
4949 visited_expression(CurID,CurState), print_state_silent(CurState),
4950 error_occurred_with_msg(invariant_violation,ErrMsg),
4951 fail.
4952 check_for_errors(CurID,_) :- get_state_errors(CurID).
4953 % TO DO: also check for assertion errors, goal, state_errors with abort
4954
4955 :- use_module(bmachine,[b_machine_has_constants_or_properties/0]).
4956 do_det_checking :- option(det_check),!.
4957 do_det_checking :- option(det_constants_check),current_state_id(root),
4958 b_or_z_mode, b_machine_has_constants_or_properties.
4959
4960 perform_random_steps(Nr,_) :- \+ number(Nr),!,
4961 print_error('Argument to animate not a number'), print_error(Nr),error_occurred(animate).
4962 perform_random_steps(Nr,_) :- Nr<0, !,
4963 print_error('Argument to animate is a negative number'), print_error(Nr),error_occurred(animate).
4964 perform_random_steps(0,_) :- !.
4965 perform_random_steps(Nr,ErrorOnDeadlock) :-
4966 (perform_random_initialisation_if_necessary(Steps) % if Nr=1 we currently will also execute the INITIALISATION ! TO DO: fix
4967 -> perform_random_steps_aux(Steps,Nr,ErrorOnDeadlock)
4968 ; % we have setup_constants_fails or initialisation_fails
4969 print_error('Could not initialise model for animation')
4970 ).
4971
4972 perform_random_steps_aux(Nr,Max,_) :- Nr >= Max,!, debug_println(9,performed_random_steps(Nr)).
4973 perform_random_steps_aux(Nr,Max,ErrorOnDeadlock) :-
4974 N1 is Nr+1,
4975 (perform_random_step(N1)
4976 -> perform_random_steps_aux(N1,Max,ErrorOnDeadlock)
4977 ; /* deadlock */
4978 write_xml_element_to_log(deadlock_found,[step/Nr]),
4979 (ErrorOnDeadlock=true, \+ option(no_deadlocks)) ->
4980 print_error('Deadlock occurred during -animate, at step number:'), print_error(Nr),
4981 error_occurred(animate)
4982 ; print('% Deadlock occurred during -animate, at step number:'), print(Nr),nl
4983 ).
4984
4985 perform_random_initialisation_if_necessary(Steps) :-
4986 b_or_z_mode, current_state_id(State), State=root,!, perform_random_initialisation(Steps).
4987 perform_random_initialisation_if_necessary(0).
4988
4989 perform_random_initialisation :- perform_random_initialisation(_).
4990 perform_random_initialisation(Steps) :- current_state_id(State), State \= root, !,
4991 print_error('init can only be used in initial state'), print_error(State),error_occurred(initialisation),
4992 Steps=0.
4993 perform_random_initialisation(Steps) :- b_mode, b_machine_has_constants_or_properties,!,
4994 (perform_random_step(Ops,_Len,RanChoice,1)
4995 -> nth1(RanChoice,Ops,Choice), %print(Choice),nl,
4996 (Choice = 'PARTIAL_SETUP_CONSTANTS'
4997 -> error_occurred(setup_constants_inconsistent)
4998 ; true)
4999 ; error_occurred(setup_constants_fails),fail), % $setup_constants TODO: properties unknown or unsat
5000 perform_random_init_after_setup_constants, Steps=2. % $initialise_machine
5001 perform_random_initialisation(Steps) :- (perform_random_step(1) -> Steps=1 ; error_occurred(initialisation_fails),fail).
5002
5003
5004 perform_random_init_after_setup_constants :- \+ option(initialise), we_need_only_static_assertions(_),!,
5005 printsilent('% NOT INITIALISING MACHINE (not required)'),nls.
5006 % debug_println(20,'% NOT INITIALISING MACHINE (not required)').
5007 perform_random_init_after_setup_constants :-
5008 (perform_random_step(2) % 2 is the step nr not the number of steps
5009 -> true
5010 ; error_occurred(initialisation_fails),
5011 fail).
5012
5013 :- use_module(cbcsrc(enabling_analysis),[tcltk_cbc_enabling_analysis/1, print_enable_table/1, is_timeout_enabling_result/1]).
5014 do_enabling_analysis_csv(EnablingCsvFile,NOW) :-
5015 start_probcli_timer(Timer1),
5016 start_xml_feature(enabling_analysis,file,EnablingCsvFile,FINFO),
5017 tcltk_cbc_enabling_analysis(list(R)),
5018 stop_probcli_timer(Timer1,'% Finished CBC Enabling Analysis',_TotWallTime),
5019 print_cbc_stats(R,NOW),
5020 debug_println(9,writing_to_file(EnablingCsvFile)),
5021 my_tell(EnablingCsvFile),
5022 print_enable_table(R),
5023 told,!,
5024 stop_xml_feature(enabling_analysis,FINFO).
5025 do_enabling_analysis_csv(EnablingCsvFile,_) :-
5026 add_error(enabling_analysis,'Enabling analysis failed',EnablingCsvFile),
5027 stop_xml_group_in_log(enabling_analysis).
5028
5029 print_cbc_stats(Res,_NOW) :- length(Res,Len), Ops is Len-2, % Header + Init
5030 CBC_Calls is Ops*(Ops+1), % +1 for INITIALISATION
5031 findall(TO,(member(list([_|T]),Res), member(TO,T),is_timeout_enabling_result(TO)),TOS),
5032 length(TOS,NrTOS),
5033 format('% CBC Enabling Stats:~n% Nr of events: ~w~n% Nr of cbc calls: ~w, Timeout results: ~w~n',[Ops,CBC_Calls,NrTOS]),
5034 write_xml_element_to_log(cbc_enabling_stats,[nr_events/Ops,cbc_calls/CBC_Calls,nr_timeouts/NrTOS]).
5035
5036
5037 :- use_module(cbcsrc(enabling_analysis),[feasible_operation_with_timeout/3]).
5038 do_feasibility_analysis(ATimeOut,EnablingCsvFile) :-
5039 arg_is_number(ATimeOut,TimeOut),
5040 start_xml_feature(feasibility_analysis,file,EnablingCsvFile,FINFO),
5041 findall(list([Op,Res]),feasible_operation_with_timeout(Op,TimeOut,Res),R),
5042 debug_println(9,writing_to_file(EnablingCsvFile)),
5043 my_tell(EnablingCsvFile),
5044 print_enable_table([list(['Event','Feasibility'])|R]),
5045 told,!,
5046 stop_xml_feature(feasibility_analysis,FINFO).
5047 do_feasibility_analysis(_,EnablingCsvFile) :-
5048 add_error(feasibility_analysis,'Feasibility analysis failed',EnablingCsvFile),
5049 stop_xml_group_in_log(feasibility_analysis).
5050
5051 :- use_module(b_read_write_info,[tcltk_read_write_matrix/1]).
5052 generate_read_write_matrix(CsvFile) :-
5053 tcltk_read_write_matrix(list(Matrix)),
5054 my_tell(CsvFile),
5055 print_enable_table(Matrix),
5056 told,!.
5057 generate_read_write_matrix(CsvFile) :-
5058 add_error(read_write_matrix,'Generating Read-Write-Matrix failed',CsvFile).
5059
5060
5061 my_tell(File) :-
5062 catch(
5063 tell(File),
5064 error(_E,_), % existence_error(_,_)
5065 add_error_fail(tell,'File cannot be written to: ',File)).
5066
5067 print_options([],_).
5068 print_options([H|T],N) :-
5069 print(' '), print(N), print(':'), print(H),nl,
5070 N1 is N+1,
5071 print_options(T,N1).
5072
5073 print_nr_list(List) :- print_nr_list(List,0,1,no_repeats).
5074
5075 print_nr_list([],NM1,_,Repeats) :- !, print_repeats(NM1,Repeats).
5076 print_nr_list([H|T],_,N,repeated(H,SinceN)) :- !, N1 is N+1,
5077 print_nr_list(T,N,N1,repeated(H,SinceN)).
5078 print_nr_list([H|T],NM1,N,Repeats) :- !,
5079 print_repeats(NM1,Repeats),
5080 N1 is N+1,
5081 print_nr_list(T,N,N1,repeated(H,N)).
5082 print_nr_list(X,_,_,_) :- print('### not a list: '), print(X),nl.
5083
5084 print_repeats(N,repeated(H,N)) :- !,
5085 format(' ~w: ~w~n',[N,H]).
5086 print_repeats(N,repeated(H,Since)) :- !, Repeats is 1+N-Since,
5087 format(' ~w - ~w: ~w (~w repetitions)~n',[Since,N,H,Repeats]).
5088 print_repeats(_,_).
5089
5090 print_bindings([]) :- !.
5091 print_bindings([binding(Var,_,PPV)|T]) :- !, print(Var),print('='),print(PPV),
5092 (T=[] -> true ; print(', '), print_bindings(T)).
5093 print_bindings([binding(Var,_,PPV,_Tag)|T]) :- !, print(Var),print('='),print(PPV),
5094 (T=[] -> true ; print(', '), print_bindings(T)).
5095 print_bindings(X) :- print('### Internal Error: illegal binding list: '), print(X),nl.
5096
5097 :- dynamic expected_error_occurred/1.
5098 :- dynamic error_did_not_occur/1.
5099 reset_expected_error_occurred :- retractall(expected_error_occurred(_)).
5100 check_all_expected_errors_occurred(NOW) :-
5101 %error_manager:display_error_statistics,
5102 get_errors, get_state_space_errors,
5103 retractall(error_did_not_occur(_)),
5104 expected_error(Type),
5105 \+ expected_error_occurred(Type),
5106 format_with_colour_nl(user_error,[red],'*** Expected Error of following type to occur: ~w',[Type]),
5107 writeln_log_time(expected_error_did_not_occur(NOW,Type)),
5108 assertz(error_did_not_occur(Type)),
5109 (option(strict_raise_error) -> definite_error_occurred ; fail).
5110 check_all_expected_errors_occurred(_NOW) :-
5111 findall(1,expected_error(_),EE), length(EE,NrExpected),
5112 (NrExpected>0
5113 -> findall(1,error_did_not_occur(_),EDNO), length(EDNO,NrNotOcc),
5114 (NrNotOcc>0
5115 -> format_with_colour_nl(user_error,[red],'*** Some expected errors (~w/~w) did NOT occur!',[NrNotOcc,NrExpected])
5116 ; format_with_colour_nl(user_output,[green],'All expected errors (~w) occurred.',[NrExpected])
5117 )
5118 ; true).
5119
5120 expected_error(Type) :- option(expect_error(Type)).
5121 expected_error(Type) :- option(expect_error_pos(Type,_Line,_Col)).
5122
5123 error_occurred(warning(Type)) :- !, error_occurred(Type,warning).
5124 error_occurred(Type) :- error_occurred(Type,error).
5125
5126 get_error_category_and_type(warning(Cat),Category,Type) :- !, Category=Cat,Type=warning.
5127 get_error_category_and_type(C,C,error).
5128
5129 error_occurred_with_msg(Type,Msg) :- error_occurred_with_msg(Type,Msg,not_yet_extracted).
5130 error_occurred_with_msg(warning(Type),Msg,Span) :- !, error_occurred(Type,warning,Span,Msg).
5131 error_occurred_with_msg(Type,Msg,Span) :- error_occurred(Type,error,Span,Msg).
5132
5133 error_occurred(Type,ErrOrWarn) :- error_occurred(Type,ErrOrWarn,not_yet_extracted,'').
5134
5135 error_occurred(Type,ErrOrWarning,ExtractedSpan,Msg) :-
5136 option(expect_error_pos(Type,Line,Col)),!,
5137 write_xml_element_to_log(expected_error_occurred,[category/Type, (type)/ErrOrWarning, message/Msg]),
5138 assertz(expected_error_occurred(Type)),
5139 (get_error_or_warning_span(ExtractedSpan,Type,EL,EC)
5140 -> (option(expect_error_pos(Type,EL,EC))
5141 -> debug_println(9,expect_error_pos_ok(Type,EL,EC))
5142 ; format('*** Unexpected line ~w and column ~w for error ~w!~n*** Expected line ~w and column ~w.~n',[EL,EC,Type,Line,Col]),
5143 definite_error_occurred
5144 )
5145 ; format('*** Could not obtain position information for error ~w! Expected line ~w and column ~w.~n',[Type,Line,Col]),
5146 %display_error_statistics,
5147 definite_error_occurred).
5148 error_occurred(Type,ErrOrWarning,ExtractedSpan,Msg) :-
5149 functor(Type,FType,_),
5150 option(expect_error(FType)),!,
5151 inc_counter(cli_expected_errors),
5152 get_xml_span(ExtractedSpan,XML),
5153 write_xml_element_to_log(expected_error_occurred,[category/Type, (type)/ErrOrWarning, message/Msg|XML]),
5154 assertz(expected_error_occurred(FType)).
5155 error_occurred(Type,ErrOrWarning,ExtractedSpan,Msg) :-
5156 (probcli_time_stamp(NOW) -> true ; NOW=unknown),
5157 writeln_log(error_occurred(NOW,Type)),
5158 get_xml_span(ExtractedSpan,XML),
5159 (functor(Type,FType,_),option(optional_error(FType)) ->
5160 write_xml_element_to_log(optional_error_occurred,[category/FType, (type)/ErrOrWarning, message/Msg|XML]),
5161 formatsilent('% Optional error occured: ~w~n',[Type])
5162 ;
5163 write_xml_element_to_log(error_occurred,[category/Type, (type)/ErrOrWarning, message/Msg|XML]),
5164 (ErrOrWarning = warning -> safe_inc_counter(cli_warnings) ; safe_inc_counter(cli_errors)),
5165 flush_output, % ensure we can later associate position of error message
5166 (option(strict_raise_error) ->
5167 print_error('*** Unexpected error occurred ***'),
5168 print_error(Type),
5169 findall(Err,option(expect_error(Err)),Ls), (Ls=[] -> true ; print_error(expected(Ls))),
5170 definite_error_occurred
5171 ; ErrOrWarning=error,serious_error(Type)
5172 -> print_error('*** Serious error occurred ***'),
5173 print_error(Type),
5174 definite_error_occurred
5175 ; print_probcli_error_non_strict(Type,ErrOrWarning)
5176 )
5177 ).
5178
5179 safe_inc_counter(Counter) :-
5180 catch(inc_counter(Counter), E,
5181 format(user_error,'~n*** Exception in counter library, probably not yet initialized: ~w.~n~n',[E])).
5182
5183
5184 get_xml_span(Span,XML) :- extract_file_line_col(Span,FullFilename,Line,Col,EndLine,EndCol),!,
5185 XML = [file/FullFilename,start_line/Line,end_line/EndLine,start_col/Col,end_col/EndCol|XT],
5186 get_xml_add_description(Span,XT).
5187 get_xml_span(Span,XML) :- get_xml_add_description(Span,XML).
5188
5189 get_xml_add_description(Span,XML) :-
5190 extract_additional_description(Span,Msg),!,
5191 XML = [additional_description/Msg].
5192 get_xml_add_description(_,[]).
5193
5194 get_error_or_warning_span(not_yet_extracted,Type,EL,EC) :- check_error_span_file_linecol(Type,_File,EL,EC,_,_).
5195 get_error_or_warning_span(not_yet_extracted,Type,EL,EC) :- check_error_span_file_linecol(warning(Type),_File,EL,EC,_,_).
5196 get_error_or_warning_span(Span,_,EL,EC) :- Span \= not_yet_extracted, extract_line_col(Span,EL,EC,_,_).
5197
5198
5199 % a list of serious errors: if these occur; then return code different from 0 even in non-strict mode
5200 serious_error(get_java_command_path).
5201 serious_error(internal_error(_)).
5202
5203 print_probcli_error_non_strict(parse_machine_predicate_error,_) :-
5204 !. % have already been reported
5205 print_probcli_error_non_strict(Type,ErrOrWarning) :-
5206 (ErrOrWarning=warning -> print_error('*** warning occurred ***')
5207 ; print_error('*** error occurred ***')),
5208 print_error(Type).
5209
5210 definite_error_occurred :- print_error('*** Abnormal termination of probcli !'),
5211 (file_loaded(_,File) -> print_error('*** for_file'(File)) ; true),
5212 (current_probcli_command(Cmd) -> print_error('*** for_command'(Cmd)) ; true),
5213 (probcli_time_stamp(NOW) -> halt_prob(NOW,1)
5214 ; writeln_log(halt(1)),
5215 halt_exception(1)
5216 ).
5217
5218 :- dynamic current_probcli_command/1.
5219 set_current_probcli_command(X) :- retractall(current_probcli_command(_)),
5220 assertz(current_probcli_command(X)).
5221 unset_current_probcli_command :- retractall(current_probcli_command(_)).
5222
5223 halt_prob(ExitCode) :-
5224 (probcli_time_stamp(NOW) -> halt_prob(NOW,ExitCode) ; halt_prob(0,ExitCode)).
5225 halt_prob(NOW,ExitCode) :-
5226 write_xml_element_to_log(probcli_halted_prematurely,[now/NOW]),
5227 close_all_xml_groups_in_log_until('probcli-run'),
5228 print_accumulated_infos_if_necessary,
5229 stop_xml_probcli_run(NOW),
5230 halt_exception(ExitCode). % will announce stop_prob event
5231
5232
5233 :- dynamic accumulated_infos/3, individual_file_infos/3, merged_individual_file_infos/3.
5234 accumulate_infos(Context,Infos) :-
5235 (option(benchmark_info_csv_output(_,_,_)) -> true % -bench_csv
5236 ; option(expect_accumulated_info(_)) -> true), % -bench_expect
5237 file_loaded(_,File),
5238 get_additional_infos(Infos,Infos2), % additional infos if -machine_stats provided
5239 sort(Infos2,SInfos), % infos is a list of the form Info-Value
5240 assert_individual_file_infos(File,Context,SInfos),
5241 fail.
5242 accumulate_infos(Context,Infos) :- accumulate_infos_2(Context,Infos).
5243
5244 % accumulate some default infos like .prob loading time if no command has accumulated anything yet
5245 accumulate_default_infos :- file_loaded(_,File), \+ individual_file_infos(File,_,_),!,
5246 accumulate_infos(no_command,[]).
5247 accumulate_default_infos.
5248
5249 assert_individual_file_infos(File,Context,SInfos) :-
5250 debug_println(19,assert_file_infos(File,Context,SInfos)),
5251 assertz(individual_file_infos(File,Context,SInfos)), % store for later csv summary printing
5252 check_required_info_options(SInfos,Context).
5253
5254 % useful if this is not related to a loaded file, like -eval_file:
5255 accumulate_file_infos(File,Context,Infos) :-
5256 get_additional_stats(Infos,Infos2),
5257 sort(Infos2,SInfos), % infos is a list of the form Info-Value
5258 assert_individual_file_infos(File,Context,SInfos).
5259
5260 % join/merge accumulated infos for multiple runs (benchmarking) for a particular context/category
5261 % currently we support this for model-checking
5262 merge_accumulated_infos(Context) :- individual_file_infos(File,Context,_),!,
5263 findall(Infos,individual_file_infos(File,Context,Infos),[Infos1|RestInfos]),
5264 merge_acc(Infos1,RestInfos,1,Result),
5265 assertz(merged_individual_file_infos(File,Context,Result)).
5266
5267 merge_acc(Cur,[],_,Cur).
5268 merge_acc(Cur,[Next|T],Nr,Res) :-
5269 N1 is Nr+1,
5270 merge_acc_infos(Cur,Next,N1,NextCur),
5271 merge_acc(NextCur,T,N1,Res).
5272
5273 % merge two accumulated infos lists
5274 merge_acc_infos([],S,_,Res) :- !, Res=S.
5275 merge_acc_infos(S,[],_,Res) :- !, Res=S.
5276 merge_acc_infos([C1|T1],[C2|T2],Nr,[Cat-ResVal|MT]) :-
5277 get_accumulated_info(C1,Cat,Val1), get_accumulated_info(C2,Cat,Val2),
5278 merge_value(Cat,Val1,Val2,Nr,ResVal),!,
5279 merge_acc_infos(T1,T2,Nr,MT).
5280 merge_acc_infos([C1|T1],T2,Nr,[C1|MT]) :-
5281 add_warning(merge_acc_infos,'Missing value: ',C1),
5282 merge_acc_infos(T1,T2,Nr,MT).
5283
5284 % merge individual values
5285 merge_value(Cat,Val1,_Val2,_,ResVal) :- keep_first_value(Cat),!, ResVal=Val1.
5286 merge_value(_,Val,Val,_,ResVal) :- !, ResVal=Val.
5287 merge_value(Cat,Val1,Val2,Nr,ResVal) :- compute_average(Cat),!, ResVal is (Val1*(Nr-1)/Nr) + (Val2 / Nr).
5288 merge_value(Cat,Val1,Val2,Nr,ResVal) :-
5289 add_warning(merge_value,'Differing values: ',val(Cat,Val1,Val2)),
5290 ResVal is (Val1*(Nr-1)/Nr) + (Val2 / Nr).
5291
5292 compute_average(runtime).
5293 compute_average(total_runtime).
5294 compute_average(walltime).
5295
5296 keep_first_value(memory_used). % memory consumption of the first run is relevant
5297
5298
5299 % also store additional infos if -machine_stats provided; useful for benchmarking/articles
5300 :- use_module(covsrc(hit_profiler),[retract_profile_stats/2]).
5301 get_additional_infos(I,Res) :- option(cli_print_machine_info(statistics)),!,
5302 findall(Key-Nr,b_machine_statistics(Key,Nr),I2,I),
5303 get_additional_stats(I2,Res).
5304 get_additional_infos(I,Res) :- get_additional_stats(I,Res).
5305 get_additional_stats(I,Res) :-
5306 findall(Key-Nr,retract_profile_stats(Key,Nr),Res,I). % include additional profiling stats and retract/reset them
5307
5308 accumulate_infos_2(_,[]).
5309 accumulate_infos_2(Context,[Info|T]) :- get_accumulated_info(Info,FF,Nr),
5310 (number(Nr) -> Nr>0 ; add_internal_error('Can only accumulate numbers:',FF-Nr),fail), !,
5311 (retract(accumulated_infos(Context,FF,OldNr)) ->true ; OldNr=0),
5312 N1 is OldNr+Nr,
5313 assertz(accumulated_infos(Context,FF,N1)),
5314 accumulate_infos_2(Context,T).
5315 accumulate_infos_2(Context,[_|T]) :- accumulate_infos_2(Context,T).
5316 get_accumulated_info(FF-Nr,FF,Nr).
5317 get_accumulated_info(FF/Nr,FF,Nr).
5318
5319 :- use_module(tools_io,[safe_intelligent_open_file/3]).
5320 print_accumulated_infos(NrFilesProcessed) :-
5321 (option(benchmark_info_csv_output(File,FileMode,CSVMode)) % TODO: allow multiple entries
5322 -> safe_intelligent_open_file(File,FileMode,Stream), % FileMode is write or append
5323 formatsilent('Generating benchmark output ~w for ~w files, mode=~w~n',[File,NrFilesProcessed,CSVMode])
5324 ; Stream=user_output, CSVMode=csv
5325 ),
5326 call_cleanup(pr_acc_infos_aux(Stream,NrFilesProcessed,FileMode,CSVMode),
5327 close(Stream)), !.
5328 print_accumulated_infos(NrFilesProcessed) :-
5329 add_internal_error('Call failed:',print_accumulated_infos(NrFilesProcessed)).
5330
5331 %get_csv_mode(csv,csv).
5332 %get_csv_mode(tex,latex).
5333 %get_csv_mode(latex,latex).
5334
5335 %:- use_module(library(system),[ datime/1]).
5336 pr_acc_infos_aux(Stream,NrFilesProcessed,FileMode,CSVMode) :-
5337 (NrFilesProcessed>1,accumulated_infos(_,_,_) -> true ; option(benchmark_info_csv_output(_,_,_))),!,
5338 print_individual_file_infos_csv(Stream,FileMode,CSVMode),
5339 start_xml_group_in_log(summary,files_processed,NrFilesProcessed),
5340 ((FileMode = append ; NrFilesProcessed = 1)
5341 -> true % do not print accumulated info line
5342 ; print_summary_file_infos_csv(Stream,FileMode,CSVMode,NrFilesProcessed),
5343 findall(Context-F-Nr,accumulated_infos(Context,F,Nr),L), sort(L,SL), % supported for model_checking only
5344 (SL=[] -> true
5345 ; format(Stream,'Analysis summary (~w files processed): ',[NrFilesProcessed]),
5346 maplist(prob_cli:pracc(Stream),SL),nl(Stream)
5347 )
5348 ),
5349 % TO DO: write infos to XML log
5350 (option(print_version(VERSIONKIND)) ->
5351 datime(datime(Year,Month,Day,Hour,Min,_Sec)),
5352 format(Stream,'CSV file generated at ~w:~w on the date ~w/~w/~w using probcli:~n',[Hour,Min,Year,Month,Day]),
5353 print_version(VERSIONKIND,Stream),
5354 print_csv_prefs(Stream)
5355 ; true),
5356 (option(cli_print_statistics(memory)) -> print_memory_statistics(Stream) ; true),
5357 stop_xml_group_in_log_no_statistics(summary).
5358 pr_acc_infos_aux(_,_NrFilesProcessed,_Mode,_).
5359
5360 print_csv_prefs(Stream) :- \+ \+ option(set_preference_group(_,_)),
5361 format(Stream,'PREFERENCE GROUP,Setting~n',[]),
5362 option(set_preference_group(P,V)),
5363 format(Stream,'~w,~w~n',[P,V]),
5364 fail.
5365 print_csv_prefs(Stream) :- \+ \+ option(set_pref(_,_)),
5366 format(Stream,'PREFERENCE,Value~n',[]),
5367 option(set_pref(P,V)),
5368 format(Stream,'~w,~w~n',[P,V]),
5369 fail.
5370 print_csv_prefs(_).
5371
5372 pracc(Stream,Context-F-Nr) :- format(Stream,'~w:~w:~w ',[Context,F,Nr]).
5373 :- use_module(probsrc(tools),[gen_relative_path_to_cur_dir/2]).
5374 % print CSV summary of run
5375 print_individual_file_infos_csv(Stream,FileMode,CSVMode) :-
5376 retractall(accumulated_file_infos(_,_)), % reset sum info
5377 findall(C,individual_file_infos(_,C,_),All), sort(All,AllContexts),
5378 member(Context,AllContexts), % iterate over all Contexts
5379 (individual_file_infos(_,Context,HInfos) -> true), % pick one as header
5380 (FileMode=append
5381 -> true % do not print header line, we append to an existing table
5382 ; format(Stream,'~nFILE,ANALYSIS,',[]),
5383 print_titles(HInfos,CSVMode,Stream),nl(Stream)
5384 ),
5385 % TO DO: ensure Infos and SHInfos identical, else add 0 for missing categories
5386 (merged_individual_file_infos(File,Context,Infos)
5387 -> true % just print averages
5388 ; individual_file_infos(File,Context,Infos)
5389 ),
5390 gen_relative_path_to_cur_dir(File,RelFile),
5391 format(Stream,'~w,~w,',[RelFile,Context]),
5392 print_vals(Infos,HInfos,CSVMode,Stream),nl(Stream),
5393 fail.
5394 print_individual_file_infos_csv(_,_,_).
5395
5396 % print a line with the total sum of accumulated_file_infos
5397 print_summary_file_infos_csv(Stream,_FileMode,CSVMode,NrFilesProcessed) :-
5398 (individual_file_infos(_,_Context,HInfos) -> true), % pick one as header
5399 format(Stream,'Total (~w files),\'-\',',[NrFilesProcessed]),
5400 findall(Header-Count,accumulated_file_infos(Header,Count),SumInfo),
5401 print_vals(SumInfo,HInfos,CSVMode,Stream),nl(Stream).
5402
5403
5404 % print file infos list
5405 print_vals(_,[],_,_) :- !.
5406 print_vals([H|T],[Header|HT],Mode,Stream) :- get_accumulated_info(Header,Title,_),
5407 get_accumulated_info(H,Title,Nr), !,
5408 write_atom(Mode,Stream,Nr),
5409 update_accumulated_file_infos(Title,Nr),
5410 (T=[] -> write_csv_terminator(Mode,Stream) ; write_csv_sep(Mode,Stream), print_vals(T,HT,Mode,Stream)).
5411 print_vals(Vals,[_|HT],Mode,Stream) :- % a value is missing for this file
5412 write(Stream,'-'),
5413 (HT=[] -> write_csv_terminator(Mode,Stream) ; write_csv_sep(Mode,Stream), print_vals(Vals,HT,Mode,Stream)).
5414 print_titles([],_,_).
5415 print_titles([H|T],Mode,Stream) :- get_accumulated_info(H,FF,_),
5416 write_atom(Mode,Stream,FF),
5417 (T=[] -> write_csv_terminator(Mode,Stream) ; write_csv_sep(Mode,Stream), print_titles(T,Mode,Stream)).
5418
5419 :- dynamic accumulated_file_infos/2.
5420 update_accumulated_file_infos(Header,Count) :-
5421 (retract(accumulated_file_infos(Header,Old)) -> true ; Old=0),
5422 (number(Count), number(Old) -> New is Old+Count ; New = '-'),
5423 assert(accumulated_file_infos(Header,New)).
5424
5425 :- use_module(probsrc(tools),[latex_escape_atom/2]).
5426 write_atom(latex,Stream,Atom) :- atom(Atom), latex_escape_atom(Atom,EAtom),!,
5427 write(Stream,EAtom).
5428 write_atom(_,Stream,Term) :- write(Stream,Term).
5429
5430 write_csv_sep(latex,Stream) :- !,write(Stream,' & ').
5431 write_csv_sep(_,Stream) :- write(Stream,',').
5432 write_csv_terminator(latex,Stream) :- !,write(Stream,' \\\\').
5433 write_csv_terminator(_,_).
5434
5435 write_important_xml_element_to_log(Category,Infos) :-
5436 include(prob_cli:important_info,Infos,II),
5437 write_xml_element_to_log(Category,II).
5438 important_info(FF/Nr) :-
5439 \+ irrelevant_xml_info(FF),
5440 (Nr=0 -> \+ irrelevant_xml_if_zero(FF) ; true).
5441 irrelevant_xml_info(true_after_expansion).
5442 irrelevant_xml_info(false_after_expansion).
5443 irrelevant_xml_info(unknown_after_expansion).
5444 irrelevant_xml_info(total_after_expansion).
5445 irrelevant_xml_if_zero(timeout).
5446 irrelevant_xml_if_zero(enum_warning).
5447
5448 % check that accumulated infos for a given run correspond to expected values provided by user (-bench_expect Label Nr)
5449 check_required_info_options(Infos,ErrType) :-
5450 option(expect_accumulated_info(Expected)), % Typically Expected = Label-Nr
5451 check_required_infos([Expected],Infos,ErrType),
5452 fail.
5453 check_required_info_options(_,_).
5454
5455 % check_required_infos(ExpectedInfos,ActualInfos,ErrType)
5456 check_required_infos([],_,_).
5457 check_required_infos([H|T],Infos,ErrType) :-
5458 (check_single_info(H,Infos)
5459 -> check_required_infos(T,Infos,ErrType)
5460 ; translate_err_type(ErrType,ES),
5461 format_with_colour_nl(user_error,[red],
5462 '*** Unexpected result while checking: ~w~n*** expected : ~w~n*** in : ~w',
5463 [ES,H,Infos]),
5464 error_occurred(ErrType)).
5465 translate_err_type(check_assertions,'ASSERTIONS') :- !.
5466 translate_err_type(cli_check_assertions,'ASSERTIONS') :- !.
5467 translate_err_type(check_goal,'GOAL') :- !.
5468 translate_err_type(load_po_file,'PROOF OBLIGATIONS') :- !.
5469 translate_err_type(cli_wd_check,'WD PROOF OBLIGATIONS') :- !.
5470 translate_err_type(check_cache_stats,'CACHE STATISTICS') :- !.
5471 translate_err_type(X,X).
5472
5473 check_single_info(Label-Nr,Infos) :- !, member(Label-ActualNr,Infos),
5474 match_info(Nr,ActualNr).
5475 check_single_info(H,List) :- member(H,List).
5476 match_info(X,X).
5477 match_info(comparison_operator(Comp,Nr),ActualNr) :-
5478 number(Nr), number(ActualNr),call(Comp,ActualNr,Nr).
5479
5480 :- use_module(tools_platform, [max_tagged_integer/1]).
5481 :- public mc_ok_arg/2.
5482 mc_ok_arg(Arg,X) :- Arg==all,!,max_tagged_integer(X).
5483 mc_ok_arg(Arg,N) :- arg_is_number(Arg,N).
5484
5485
5486 :- dynamic option/1.
5487 assert_all_options([]).
5488 assert_all_options([Opt|T]) :- assert_option(Opt),
5489 assert_all_options(T).
5490
5491 :- use_module(pathes_extensions_db,[probcli_command_requires_extension/2]).
5492 cli_option_not_available(Opt,ProBExtension,Reason) :-
5493 probcli_command_requires_extension(Opt,ProBExtension),
5494 unavailable_extension(ProBExtension,Reason).
5495
5496 check_unavailable_options :-
5497 ? option(Opt),
5498 cli_option_not_available(Opt,ProBExtension,Reason),
5499 (recognised_option(Name,Opt,_,_) -> true ; Name=Opt),
5500 ajoin(['probcli command ', Name,' cannot be performed because extension not available (',Reason,'):'],Msg),
5501 add_error(probcli,Msg,ProBExtension),
5502 fail.
5503 check_unavailable_options.
5504
5505 assert_option(silent) :- option(force_no_silent),!. % ignoring silent flag
5506 assert_option(Opt) :- assertz(option(Opt)), treat_option(Opt).
5507
5508 :- use_module(tools_printing,[set_no_color/1, reset_no_color_to_default/0]).
5509 treat_option(silent) :- !, set_silent_mode(on),set_error_manager_silent_mode(on).
5510 treat_option(force_no_silent) :- !, set_silent_mode(off),set_error_manager_silent_mode(off).
5511 treat_option(no_color) :- !, set_no_color(true).
5512 treat_option(_).
5513
5514 option_silent_set :- option(silent), \+ option(force_no_silent).
5515
5516 reset_options :- retractall(option(_)),
5517 set_silent_mode(off), set_error_manager_silent_mode(off),
5518 reset_no_color_to_default.
5519
5520 % replace a leading double-dash -- by a single dash and replace inner dashes by underscores
5521 normalise_option_atom(X,RX) :- atom(X),!,
5522 atom_codes(X,CodesX),
5523 % remove leading dash
5524 (CodesX=[45,45,H|T], H\=45 % Double dash --Option
5525 -> maplist(prob_cli:convert_dash_to_underscore,[H|T],HT2),
5526 RXCodes=[45|HT2]
5527 ; CodesX = [Dash|T], is_dash(Dash) % single dash
5528 -> maplist(prob_cli:convert_dash_to_underscore,T,T2),
5529 RXCodes=[45|T2]
5530 ; maplist(prob_cli:convert_dash_to_underscore,CodesX,RXCodes)
5531 ),
5532 atom_codes(RX,RXCodes).
5533 normalise_option_atom(T,T).
5534
5535 is_dash(45). % regular dash
5536 is_dash(8212). % Unicode double dash; sometimes automatically generated from -- by e.g., macOS Mail program
5537
5538 :- public normalise_pref_name/2. % called via recognised_option
5539 % replace dashes by underscores
5540 normalise_pref_name(X,RX) :- atom(X),!,
5541 atom_codes(X,CodesX),
5542 maplist(prob_cli:convert_dash_to_underscore,CodesX,C2),
5543 atom_codes(RX,C2).
5544 normalise_pref_name(T,T).
5545
5546 convert_dash_to_underscore(45,R) :- !, R=95.
5547 convert_dash_to_underscore(X,X).
5548
5549 recognised_cli_option(X,Opt,Args,Condition) :- normalise_option_atom(X,RX),
5550 ? recognised_option(RX,Opt,Args,Condition).
5551
5552 % get a list of all options
5553 get_all_options(SOpts) :-
5554 findall(O, recognised_option(O,_,_,_), Opts),
5555 sort(Opts,SOpts).
5556
5557 :- use_module(tools_matching,[fuzzy_match_codes_lower_case/2]).
5558 % compute a set of possible fuzzy matches
5559 get_possible_fuzzy_match_options(Option,FuzzyMatches) :-
5560 normalise_option_atom(Option,RX),
5561 atom_codes(RX,OCodes),
5562 get_all_options(SOpts),
5563 findall(Target,(member(Target,SOpts),atom_codes(Target,TargetCodes),
5564 fuzzy_match_codes_lower_case(OCodes,TargetCodes)),FuzzyMatches).
5565
5566 :- use_module(tools_matching,[get_possible_completions_msg/3]).
5567 get_possible_options_completion_msg(Option,Msg) :-
5568 normalise_option_atom(Option,RX),
5569 get_all_options(SOpts),
5570 get_possible_completions_msg(RX,SOpts,Msg).
5571
5572 recognised_option(X,Opt,[],true) :- recognised_option(X,Opt). % options without arguments
5573 recognised_option(X,Opt,Args,true) :- recognised_option(X,Opt,Args). % options with arguments but no code needed to check arguments
5574
5575 recognised_option('-mc',cli_mc(N,[]),[Arg],prob_cli:mc_ok_arg(Arg,N)).
5576 recognised_option('-bench_model_check',cli_mc(LimitNr,[reset_state_space,repeat(Rep)]),[Arg],tools:arg_is_number(Arg,Rep)) :- max_tagged_integer(LimitNr).
5577 recognised_option('-model_check',cli_mc(LimitNr,[]),[],true) :- max_tagged_integer(LimitNr).
5578 recognised_option('-timeout',timeout(N),[Arg],tools:arg_is_number(Arg,N)). % for model checking, refinement checking and for disprover per PO
5579 recognised_option('-time_out',timeout(N),[Arg],tools:arg_is_number(Arg,N)).
5580 recognised_option('-global_time_out',timeout(N),[Arg],tools:arg_is_number(Arg,N)). % better name, to avoid conflict with -p timeout N which also works
5581 recognised_option('-s',socket(S,true),[Arg],tools:arg_is_number(Arg,S)).
5582 recognised_option('-cc',coverage(N,N2,just_check_stats),[Arg,Arg2],
5583 (arg_is_number_or_wildcard(Arg,N),arg_is_number_or_wildcard(Arg2,N2))).
5584 recognised_option('-csp_guide',add_csp_guide(File),[File],
5585 prob_cli:check_file_arg(File,'csp_guide')).
5586 recognised_option('-prologOut',csp_translate_to_file(PlFile),[PlFile],
5587 prob_cli:check_file_arg(PlFile,'prologOut')).
5588 recognised_option('-load_state',load_state(Filename),[Filename],
5589 prob_cli:check_file_arg(Filename,'load_state')).
5590 recognised_option('-refchk',refinement_check(Filename,trace,100000),[Filename],
5591 prob_cli:check_file_arg(Filename,'refchk')).
5592 recognised_option('-ref_check',refinement_check(Filename,FailuresModel,100000),[Shortcut,Filename],
5593 (prob_cli:check_file_arg(Filename,'ref_check'),
5594 prob_cli:check_failures_mode(Shortcut,FailuresModel))).
5595 recognised_option('-refinement_check',Option,Args,Code) :- recognised_option('-refchk',Option,Args,Code).
5596 recognised_option('-hash',check_statespace_hash(H,_),[Arg],tools:arg_is_number(Arg,H)).
5597 recognised_option('-hash64',check_statespace_hash(H,'64bit'),[Arg],tools:arg_is_number(Arg,H)).
5598 recognised_option('-hash32',check_statespace_hash(H,'32bit'),[Arg],tools:arg_is_number(Arg,H)).
5599 recognised_option('-check_op_cache_stats',
5600 check_op_cache([next_state_calls-H1,inv_check_calls-H2,
5601 operations_cached-H3,invariants_cached-H4]),[Arg1,Arg2,Arg3,Arg4],
5602 (tools:arg_is_number_or_wildcard(Arg1,H1), tools:arg_is_number_or_wildcard(Arg2,H2),
5603 tools:arg_is_number_or_wildcard(Arg3,H3), tools:arg_is_number_or_wildcard(Arg4,H4))).
5604 recognised_option('-check_cbc_sequence_solutions',check_cbc_sequence_solutions(Nr),[Arg], tools:arg_is_number(Arg,Nr)).
5605 recognised_option('-ltllimit',ltl_limit(Nr),[Arg], tools:arg_is_number(Arg,Nr)).
5606 recognised_option('-ltlfile',ltl_file(Filename),[Filename],
5607 prob_cli:check_file_arg(Filename,'ltlfile')).
5608 recognised_option('-check_disprover_result',cli_check_disprover_result([true-TNr,false-FNr,unknown-UNr,failure-0]),[T,F,U],
5609 (arg_is_number_or_wildcard(T,TNr),arg_is_number_or_wildcard(F,FNr),arg_is_number_or_wildcard(U,UNr))).
5610 recognised_option('-aa',cli_check_assertions(all,[true/TNr,false/FNr,unknown/UNr]),[T,F,U],
5611 (arg_is_number_or_wildcard(T,TNr),arg_is_number_or_wildcard(F,FNr),arg_is_number_or_wildcard(U,UNr))).
5612 recognised_option('-ma',cli_check_assertions(main,[true/TNr,false/FNr,unknown/UNr]),[T,F,U],
5613 (arg_is_number_or_wildcard(T,TNr),arg_is_number_or_wildcard(F,FNr),arg_is_number_or_wildcard(U,UNr))).
5614 recognised_option('-wd',cli_wd_check(DNr,TNr),[D,T],
5615 (arg_is_number_or_wildcard(T,TNr),arg_is_number_or_wildcard(D,DNr))).
5616 recognised_option('-check_cache_stats',cli_cache_stats_check([value_persistance_reused_transitions-RNr,
5617 value_persistance_stored_transitions-SNr]),[R,S],
5618 (arg_is_number_or_wildcard(S,SNr),arg_is_number_or_wildcard(R,RNr))).
5619 recognised_option('-check_cache_refresh_stats',cli_cache_stats_check([value_persistance_refresh_transitions-RNr]),[R],
5620 arg_is_number_or_wildcard(R,RNr)). % number of transitions written when refreshing .probops files
5621 recognised_option('-check_cache_init_stats',cli_cache_stats_check([value_persistance_reused_initialisations-RNr,
5622 value_persistance_stored_initialisations-SNr]),[R,S],
5623 (arg_is_number_or_wildcard(S,SNr),arg_is_number_or_wildcard(R,RNr))). % reused INITIALISATION calls and stored INITIALISATION transitions
5624 recognised_option('-check_cache_constants_stats',cli_cache_stats_check([value_persistance_constants_loaded-MNr,
5625 value_persistance_ref_constants_loaded-RNr]),[M,R],
5626 (arg_is_number_or_wildcard(M,MNr),arg_is_number_or_wildcard(R,RNr))).
5627 recognised_option('-kodkod_comparision',kodkod_comparision(Nr),[Arg],tools:arg_is_number(Arg,Nr)).
5628 recognised_option('-kodkod_performance',kodkod_performance(File,Nr),[File,Arg],tools:arg_is_number(Arg,Nr)).
5629 recognised_option('-animate',cli_random_animate(N,true),[Steps],tools:arg_is_number(Steps,N)).
5630 recognised_option('-simulate',cli_simulate(File,1,N,[]),[File,Steps],tools:arg_is_number(Steps,N)).
5631 recognised_option('-rt_simulate',cli_simulate(File,1,N,[simulation_speed/1]),[File,Steps],tools:arg_is_number(Steps,N)).
5632 recognised_option('-mc_simulate',cli_simulate(File,R,N,[]),[File,Reps,Steps],(tools:arg_is_number(Steps,N),tools:arg_is_number(Reps,R))).
5633 recognised_option('-simb_profile',cli_print_statistics(simb_profile),[],true).
5634 recognised_option('-simulate_until_ltl_ap',simb_ltl_stop_condition(LTL_Stop_AsAtom),[LTL_Stop_AsAtom],true).
5635 recognised_option('-simulate_until_time',simb_option(max_simulation_time(T)),[Time],tools:arg_is_number(Time,T)).
5636 recognised_option('-execute',execute(N,true,current_state(1)),[Steps],tools:arg_is_number(Steps,N)).
5637 recognised_option('-execute_repeat',execute(N,true,current_state(R)),[Steps,Rep],
5638 (tools:arg_is_number(Steps,N),tools:arg_is_number(Rep,R))).
5639 recognised_option('-execute_expect_steps',execute_expect_steps(N),[Steps],tools:arg_is_number(Steps,N)).
5640 recognised_option('-logxml_write_vars',logxml_write_ids(variables,Prefix),[Prefix],true).
5641 recognised_option('-logxml_write_ids',logxml_write_ids(all,Prefix),[Prefix],true).
5642 recognised_option('-zmq_master',zmq_master(Identifier),[Identifier], true).
5643 recognised_option('-cbc_tests', cbc_tests(Depth,EndPred,Output),[Depth,EndPred,Output],
5644 prob_cli:check_file_arg(Output,'cbc_tests')).
5645 recognised_option('-mcm_tests', mcm_tests(Depth,MaxStates,EndPred,Output),[Depth,MaxStates,EndPred,Output],
5646 prob_cli:check_file_arg(Output,'mcm_tests')).
5647 recognised_option('-test_description', test_description(File), [File],
5648 prob_cli:check_file_arg(File,'test_description')).
5649 recognised_option('-all_paths', all_deadlocking_paths(File), [File],
5650 prob_cli:check_file_arg(File,'all_paths')).
5651 recognised_option('-dot',dot_command(Category,File,default),[Category,File],
5652 prob_cli:check_file_arg(File,'dot')).
5653 recognised_option('-spdot',dot_command(state_space,File,default),[File], prob_cli:check_file_arg(File,'spdot')). % we keep this : it is shown in Wiki
5654 % recognised_option('-spmdot',dot_command(signature_merge,File,default),[File], prob_cli:check_file_arg(File,'spmdot')).
5655 % recognised_option('-spddot',dot_command(dfa_merge,File,default),[File], prob_cli:check_file_arg(File,'spddot')).
5656 % recognised_option('-sgdot',dot_command(state_as_graph,File,default),[File], prob_cli:check_file_arg(File,'sgdot')).
5657 recognised_option('-dotexpr',dot_command_for_expr(Category,Expr,File,[],default),[Category,Expr,File],
5658 prob_cli:check_file_arg(File,'dotexpr')).
5659 recognised_option('-dot_expr',Opt,Args,Call) :- recognised_option('-dotexpr',Opt,Args,Call).
5660 %recognised_option('-sgedot',dot_command_for_expr(expr_as_graph,Expr,File,[],default),[Expr,File], prob_cli:check_file_arg(File,'sgedot')).
5661 % recognised_option('-sptdot',dot_command_for_expr(transition_diagram,Expr,File,[],default),[Expr,File],prob_cli:check_file_arg(File,'sptdot')).
5662 %recognised_option('-invdot',dot_command(invariant,File,default),[File], prob_cli:check_file_arg(File,'invdot')).
5663 %recognised_option('-propdot',dot_command(properties,File,default),[File], prob_cli:check_file_arg(File,'propdot')).
5664 %recognised_option('-assdot',dot_command(assertions,File,default),[File], prob_cli:check_file_arg(File,'assdot')).
5665 %recognised_option('-deaddot',dot_command(deadlock,File,default)(File),[File], prob_cli:check_file_arg(File,'deaddot')).
5666 recognised_option('-puml',plantuml_command(Category,File),[Category,File],
5667 prob_cli:check_file_arg(File,'plantuml')).
5668 recognised_option('-pumlexpr',plantuml_command(Category,File,[Expr]),[Category,Expr,File],
5669 prob_cli:check_file_arg(File,'plantuml')).
5670 recognised_option('-puml_expr',Opt,Args,Call) :- recognised_option('-pumlexpr',Opt,Args,Call).
5671 recognised_option('-csv',csv_table_command(Category,[],[],File),[Category,File],
5672 prob_cli:check_file_arg(File,'csv')).
5673 recognised_option('-csvexpr',csv_table_command(Category,[Expr],[],File),[Category,Expr,File],
5674 prob_cli:check_file_arg(File,'csvexpr')).
5675 recognised_option('-csv_expr',Opt,Args,Call) :- recognised_option('-csvexpr',Opt,Args,Call).
5676 recognised_option('-csv_hist',Opt,Args,Call) :- recognised_option('-csvhist',Opt,Args,Call).
5677 recognised_option('-csvhist',evaluate_expression_over_history_to_csv_file(Expr,File),[Expr,File],
5678 prob_cli:check_file_arg(File,'csvhist')).
5679 %recognised_option('-get_min_max_coverage',csv_table_command(minmax_table,[],[text_output],File),[File]). % deprecated
5680 recognised_option('-min_max_coverage',csv_table_command(minmax_table,[],[text_output],File),[File],
5681 prob_cli:check_file_arg(File,'min_max_coverage')).
5682 recognised_option('-get_coverage_information',get_coverage_information(File),[File],
5683 prob_cli:check_file_arg(File,'get_coverage_information')).
5684 %recognised_option('-vc',csv_table_command(minmax_table,[],[text_output],user_output)).
5685 recognised_option('-read_write_matrix_csv',generate_read_write_matrix_csv(CsvFile),
5686 [CsvFile],
5687 prob_cli:check_file_arg(CsvFile,'read_write_matrix_csv')).
5688 recognised_option('-feasibility_analysis_csv',feasibility_analysis_csv(TimeOut,EnablingCsvFile),
5689 [TimeOut,EnablingCsvFile],
5690 prob_cli:check_file_arg(EnablingCsvFile,'feasibility_analysis_csv')).
5691 recognised_option('-l',log(Log,prolog),[Log],
5692 prob_cli:check_file_arg(Log,'l')).
5693 recognised_option('-log',log(Log,prolog),[Log],
5694 prob_cli:check_file_arg(Log,'log')).
5695 recognised_option('-logxml',log(Log,xml),[Log],
5696 prob_cli:check_file_arg(Log,'logxml')). % see cli_start_logging
5697 recognised_option('-logtlc',logtlc(Log),[Log],
5698 prob_cli:check_file_arg(Log,'logtlc')).
5699 recognised_option('-pp',pretty_print_internal_rep(File,'$auto',needed,ascii),[File],
5700 prob_cli:check_file_arg(File,'pp')).
5701 recognised_option('-ppunicode',pretty_print_internal_rep(File,'$auto',needed,unicode),[File],
5702 prob_cli:check_file_arg(File,'pp')).
5703 recognised_option('-ppf',pretty_print_internal_rep(File,'$auto',all,ascii),[File],
5704 prob_cli:check_file_arg(File,'ppf')).
5705 recognised_option('-ppAB',pretty_print_internal_rep(File,'$auto',all,atelierb),[File],
5706 prob_cli:check_file_arg(File,'ppAB')).
5707 recognised_option('-ppEB',pretty_print_internal_rep(File,'$auto',all,camille),[File], % Event-B for Camille
5708 prob_cli:check_file_arg(File,'ppEB')).
5709 recognised_option('-pp_with_name',pretty_print_internal_rep(File,MachName,all,ascii),[MachName,File],
5710 prob_cli:check_file_arg(File,'pp_with_name')). % provide explicit machine name
5711 recognised_option('-ppB',pretty_print_internal_rep_to_B(File),[File],
5712 prob_cli:check_file_arg(File,'ppB')). % deprecated; is now superseded by ppAB for Event-B machines
5713 recognised_option('-pppl',pretty_print_prolog_file(File),[File],
5714 prob_cli:check_file_arg(File,'pppl')).
5715 recognised_option('-pp_pl_file',pretty_print_prolog_file(File,OutFile),[File,OutFile],
5716 (prob_cli:check_file_arg(File,'pp_pl_file'),prob_cli:check_file_arg(OutFile,'pp_pl_file'))).
5717 recognised_option('-ppi',indent_main_b_file(File),[File],
5718 prob_cli:check_file_arg(File,'ppi')).
5719 recognised_option('-indent_b_file',indent_b_file_to_file(BFile,OutFile,[]),[BFile,OutFile], % indent some other file
5720 (prob_cli:check_file_arg(BFile,'indent_b_file'),prob_cli:check_file_arg(OutFile,'indent_b_file'))).
5721 recognised_option('-reformat_b_file',indent_b_file_to_file(BFile,OutFile,
5722 [insert_new_lines_before_keywords,insert_new_lines_after_keywords]),[BFile,OutFile], % reformat some other file
5723 (prob_cli:check_file_arg(BFile,'indent_b_file'),prob_cli:check_file_arg(OutFile,'indent_b_file'))).
5724 recognised_option('-save_state',save_state_space(Filename),[Filename],
5725 prob_cli:check_file_arg(Filename,'save_state')). % possibly save_state_space would be a better name
5726 recognised_option('-save',save_state_for_refinement(Filename),[Filename],
5727 prob_cli:check_file_arg(Filename,'save')).
5728 recognised_option('-sptxt',print_values(Filename),[Filename],
5729 prob_cli:check_file_arg(Filename,'sptxt')).
5730 recognised_option('-sstxt',print_all_values(Dirname),[Dirname],
5731 prob_cli:check_file_arg(Dirname,'sstxt')).
5732 recognised_option('-latex',process_latex_file(In,Out),[In,Out],
5733 (prob_cli:check_file_arg(In,'latex'),prob_cli:check_file_arg(Out,'latex'))).
5734 recognised_option('-bench_csv',benchmark_info_csv_output(File,write,csv),[File],prob_cli:check_file_arg(File,'bench_csv')).
5735 recognised_option('-bench_csv_append',benchmark_info_csv_output(File,append,csv),[File],prob_cli:check_file_arg(File,'bench_csv')).
5736 recognised_option('-bench_tex',benchmark_info_csv_output(File,write,latex),[File],prob_cli:check_file_arg(File,'bench_tex')).
5737 recognised_option('-bench_expect',expect_accumulated_info(Label-Nr),[Label,SNr],tools:(arg_is_number(SNr,Nr))).
5738 recognised_option('-trace_replay',trace_check(Style,File,default_trace_replay),[Style,File],prob_cli:check_file_arg(File,'trace_replay')). % Style can be json, prolog or B
5739 recognised_option('-det_trace_replay',trace_check(Style,File,deterministic_trace_replay),[Style,File],prob_cli:check_file_arg(File,'det_trace_replay')).
5740 recognised_option('-replay',eval_repl([File]),[File],prob_cli:check_file_arg(File,'replay')). % used to be -eval
5741 recognised_option('-state_trace',state_trace(File),[File],prob_cli:check_file_arg(File,'state_trace')).
5742 recognised_option('-typecheckertest',typechecker_test(File),[File],prob_cli:check_file_arg(File,'typecheckertest')).
5743 recognised_option('-enabling_analysis_csv',enabling_analysis_csv(EnablingCsvFile),[EnablingCsvFile],
5744 prob_cli:check_file_arg(EnablingCsvFile,'enabling_analysis_csv')).
5745 recognised_option('-dot_output',dot_analyse_output_prefix(Path),[Path],prob_cli:check_file_arg(Path,'dot_output')).
5746 recognised_option('-evaldot',evaldot(File),[File],prob_cli:check_file_arg(File,'evaldot')).
5747 recognised_option('-his',history(File),[File],prob_cli:check_file_arg(File,'his')).
5748 recognised_option('-visb_click',visb_click(SVGID),[SVGID],true).
5749 recognised_option('-visb',visb_history(JSONFile,HTMLFile,[]),[JSONFile,HTMLFile],
5750 (prob_cli:check_file_arg(JSONFile,'visb'),prob_cli:check_file_arg(HTMLFile,'visb'))).
5751 recognised_option('-visb_with_vars',
5752 visb_history(JSONFile,HTMLFile,[show_constants(all),show_sets(all),show_variables(all)]),
5753 [JSONFile,HTMLFile],
5754 (prob_cli:check_file_arg(JSONFile,'visb_with_vars'),prob_cli:check_file_arg(HTMLFile,'visb_with_vars'))).
5755 recognised_option('-rule_report',rule_report(File), [File], prob_cli:check_file_arg(File,'rule_report')).
5756 recognised_option('-proof_export',proof_export(Style,File), [Style,File], prob_cli:check_file_arg(File,'proof_export')). % Style can be html, bpr or a dot output format
5757 recognised_option('-bench_alloy_cmd',run_benchmark(alloy,CmdNames,AlloyFilePath),[CmdNames,AlloyFilePath],prob_cli:check_file_arg(AlloyFilePath,'bench_alloy_cmd')).
5758 recognised_option('-bench_smt_cbc_inv',run_benchmark(smt,cbc_inv,Folder),[Folder],prob_cli:check_file_arg(Folder,'bench_smt_cbc_inv')).
5759 recognised_option('-bench_smt_cbc_deadlock',run_benchmark(smt,cbc_deadlock,Folder),[Folder],prob_cli:check_file_arg(Folder,'bench_smt_cbc_deadlock')).
5760 recognised_option('-bench_smt_bmc',run_benchmark(smt,bmc,Folder),[Folder],prob_cli:check_file_arg(Folder,'bench_smt_bmc')).
5761 recognised_option('-eval_file',eval_string_or_file(file(default),F,exists,_ANY,norecheck),[F],prob_cli:check_file_arg(F,'eval_file')).
5762 recognised_option('-evalt_file',eval_string_or_file(file(default),F,exists,'TRUE',norecheck),[F],prob_cli:check_file_arg(F,'evalt_file')).
5763 recognised_option('-eval_rule_file',eval_string_or_file(file(default),F,forall,_ANY,norecheck),[F],prob_cli:check_file_arg(F,'eval_rule_file')).
5764 recognised_option('-solve_file',eval_string_or_file(file(Solver),F,exists,_ANY,norecheck),[Solver,F],prob_cli:check_file_arg(F,'eval_file')).
5765
5766 recognised_option('-zmq_assertions',zmq_assertion(Identifier),[Identifier],true).
5767 recognised_option('-zmq_worker',zmq_worker(Identifier),[Identifier], true).
5768 %recognised_option('-zmq_worker2',zmq_worker2(MasterIP, Port, ProxyID, Logfile),[MasterIP, SPort, SProxyID, Logfile],
5769 % tools:(arg_is_number(SPort,Port), arg_is_number(SProxyID, ProxyID))).
5770 recognised_option('-p',set_pref(NPREF,PREFVAL),[PREF,PREFVAL],prob_cli:normalise_pref_name(PREF,NPREF)).
5771 recognised_option('-pref',set_pref(NPREF,PREFVAL),[PREF,PREFVAL],prob_cli:normalise_pref_name(PREF,NPREF)).
5772 recognised_option('-prob_application_type',set_application_type(T),[T],true).
5773 recognised_option('-cbc_redundant_invariants',cbc_redundant_invariants(Nr),[X],tools:arg_is_number(X,Nr)).
5774 recognised_option('-expcterrpos',expect_error_pos(Type,LNr,CNr),[Type,Line,Col],
5775 (tools:arg_is_number(Line,LNr),tools:arg_is_number(Col,CNr))).
5776 recognised_option('-pref_group',set_preference_group(NGroup,Val),[Group,Val],
5777 (prob_cli:normalise_option_atom(Group,NGroup))).
5778 recognised_option('-save_all_traces_until',generate_all_traces_until(Formula,FilePrefix),
5779 [Formula,FilePrefix],
5780 true). % we could check LTL formula and FilePrefix
5781 recognised_option('-check_machine_file_sha',check_machine_file_sha(FILE,SHA1),[FILE,SHA1],
5782 prob_cli:check_file_arg(FILE,'check_machine_file_sha')).
5783 recognised_option('-sha1sum',Command,Args,Call) :-
5784 recognised_option('-check_machine_file_sha',Command,Args,Call).
5785 recognised_option('-animate_until_ltl_steps',animate_until_ltl(Formula,no_loop,ltl_found,Steps),[Formula,A],
5786 tools:arg_is_number(A,Steps)).
5787 recognised_option('-gc_margin',set_gc_margin(Nr),[X], tools:arg_is_number(X,Nr)).
5788 recognised_option('-verbosity',verbose(Nr),[X], tools:arg_is_number(X,Nr)). % set verbose level by number
5789
5790 % recognised_option/3
5791 recognised_option('-prefs',set_prefs_from_file(PREFFILE),[PREFFILE]).
5792 %recognised_option('-plugin',plugin(Plugin), [Plugin]).
5793 recognised_option('-card',set_card(SET,SCOPE),[SET,SCOPE]).
5794 recognised_option('-argv',set_argv(ARGV),[ARGV]).
5795 recognised_option('-goal',set_goal(GOAL),[GOAL]).
5796 recognised_option('-property',add_additional_property(PRED),[PRED]).
5797 recognised_option('-scope',set_searchscope(GOAL),[GOAL]).
5798 recognised_option('-searchscope',set_searchscope(GOAL),[GOAL]).
5799 recognised_option('-search_scope',set_searchscope(GOAL),[GOAL]).
5800 recognised_option('-eval',eval_string_or_file(string,E,exists,_,norecheck),[E]).
5801 recognised_option('-evalt',eval_string_or_file(string,E,exists,'TRUE',norecheck),[E]).
5802 recognised_option('-evalf',eval_string_or_file(string,E,exists,'FALSE',norecheck),[E]).
5803 recognised_option('-evalt_rc',eval_string_or_file(string,E,exists,'TRUE',recheck(ascii)),[E]).
5804 recognised_option('-evalf_rc',eval_string_or_file(string,E,exists,'FALSE',recheck(ascii)),[E]).
5805 recognised_option('-evalu',eval_string_or_file(string,E,exists,'UNKNOWN',norecheck),[E]).
5806 recognised_option('-evalnwd',eval_string_or_file(string,E,exists,'NOT-WELL-DEFINED',norecheck),[E]).
5807 recognised_option('-eval_for_bench_csv',eval_string_or_file(string,E,exists,_,add_to_profile_stats(Cat)),[Cat,E]). % eval and store value for bench_csv
5808 recognised_option('-parsercp',parsercp(L),[L]). % deprecated
5809 recognised_option('-parserport',parserport(L),[L]).
5810 recognised_option('-expcterr',expect_error(Type),[Type]).
5811 recognised_option('-expecterr',expect_error(Type),[Type]).
5812 recognised_option('-expect',expect_error(Type),[Type]).
5813 recognised_option('-opterr',optional_error(Type),[Type]).
5814 recognised_option('-his_option',history_option(Option),[Option]). % trace_file, json, show_init, show_states
5815 recognised_option('-cache',cache_storage(D,strict),[D]). % for value_persistance caching
5816 recognised_option('-ccache',cache_storage(D,create_if_needed),[D]). % ditto
5817 recognised_option('-show_cache',show_cache(default),[]).
5818 recognised_option('-show_cache_verbose',show_cache(verbose),[]).
5819 recognised_option('-cache_statistics',cli_print_statistics(value_persistance_stats),[]).
5820 recognised_option('-cache_stats',cli_print_statistics(value_persistance_stats),[]). % synonym
5821 % see also -check_cache_stats
5822 recognised_option('-clear_cache',clear_value_persistance_cache,[]).
5823 recognised_option('-clear_cache_for',clear_value_persistance_cache(Machine),[Machine]).
5824 recognised_option('-ignore_cache_for',ignore_value_persistance_cache_for(Machine),[Machine]).
5825 recognised_option('-hshow',cli_print_statistics(hshow),[]). % machine inclusion hierarchy
5826 recognised_option('-show_inclusion_hierarchy',cli_print_statistics(hshow),[]). % machine inclusion hierarchy
5827
5828 recognised_option('-MAIN',csp_main(ProcessName),[ProcessName]).
5829
5830 recognised_option('-ltlformula',ltl_formula_model_check(Formula,_),[Formula]).
5831 recognised_option('-ltlformulat',ltl_formula_model_check(Formula,true),[Formula]).
5832 recognised_option('-ltlformulaf',ltl_formula_model_check(Formula,false),[Formula]).
5833 recognised_option('-ctlformula',ctl_formula_model_check(Formula,_),[Formula]).
5834 recognised_option('-ctlformulat',ctl_formula_model_check(Formula,true),[Formula]).
5835 recognised_option('-ctlformulaf',ctl_formula_model_check(Formula,false),[Formula]).
5836 recognised_option('-pctlformula',pctl_formula_model_check(Formula,_),[Formula]).
5837 recognised_option('-pctlformulat',pctl_formula_model_check(Formula,true),[Formula]).
5838 recognised_option('-pctlformulaf',pctl_formula_model_check(Formula,false),[Formula]).
5839 recognised_option('-animate_until_ltl',animate_until_ltl(Formula,no_loop,_,_),[Formula]).
5840 recognised_option('-animate_until_ltl_state_property',animate_until_ltl(Formula,ltl_state_property,_,_),[Formula]).
5841
5842
5843 %recognised_option('-cspref',csp_in_situ_refinement_check(assertRef('False',val_of(AbsP1,no_loc_info_available),Type,val_of(ImplP2,no_loc_info_available),no_loc_info_available),'False'),[AbsP1,Type,ImplP2]).
5844 recognised_option('-cspref',csp_in_situ_refinement_check(AbsP1,Type,ImplP2),[AbsP1,Type,ImplP2]).
5845 % -cspref R [F= Q
5846 recognised_option('-cspdeadlock',csp_checkAssertion(Proc,Model,'deadlock free'),[Proc,Model]).
5847 % -cspdeadlock R F
5848 recognised_option('-cspdeterministic',csp_checkAssertion(Proc,Model,'deterministic'),[Proc,Model]).
5849 % -cspdeterministic R F
5850 recognised_option('-csplivelock',csp_checkAssertion(Proc,'FD','livelock free'),[Proc]).
5851 % -csplivelock R
5852 % -csp_assertion "P [F= Q"
5853 recognised_option('-csp_assertion',check_csp_assertion(Assertion),[Assertion]).
5854 recognised_option('-csp_eval', eval_csp_expression(Expr),[Expr]).
5855 recognised_option('-get_csp_assertions_as_string',csp_get_assertions,[]).
5856
5857 recognised_option('-variable_coverage',csv_table_command(variable_coverage,[],[text_output],user_output),[]).
5858 recognised_option('-vacuity_check',vacuity_check,[]).
5859 recognised_option('-wd_check',cli_wd_check(_,_),[]).
5860 recognised_option('-wd_check_all',cli_wd_check(X,X),[]).
5861 recognised_option('-well_definedness_check',cli_wd_check(_,_),[]).
5862 recognised_option('-wd_inv_proof',cli_wd_inv_proof(_,_,_),[]).
5863 recognised_option('-lint',cli_lint,[]). % extended static check (ESC, esc)
5864 recognised_option('-lint_operations',cli_lint(operations),[]).
5865 recognised_option('-lint_variables',cli_lint(variables),[]).
5866 recognised_option('-cbc',constraint_based_check(OpName),[OpName]). % cbc invariant checking
5867 recognised_option('-cbc_invariant',constraint_based_check(OpName),[OpName]).
5868 recognised_option('-cbc_assertions_after',cbc_assertions_after(OpName),[OpName]). % cbc dynamic assertion checking
5869 recognised_option('-cbc_deadlock',cbc_deadlock_check(true),[]).
5870 recognised_option('-cbc_assertions',cbc_assertions(true,[]),[]).
5871 recognised_option('-cbc_main_assertions',cbc_assertions(true,[main_assertions]),[]).
5872 recognised_option('-cbc_assertions_proof',cbc_assertions(false,[]),[]). % do not allow enumeration warnings
5873 recognised_option('-cbc_assertions_tautology_proof',cbc_assertions(false,[tautology_check]),[]). % do not allow enumeration warnings + disregard PROPERTIES, used for Atelier-B proof/disproof; TO DO: also call WD prover
5874 recognised_option('-cbc_assertions_tautology_proof_check',cbc_assertions(false,[tautology_check,contradiction_check]),[]).
5875 recognised_option('-cbc_option',cbc_option(OPT),[OPT]). % should be tautology_check,contradiction_check, unsat_core
5876 recognised_option('-cbc_result_file',cbc_result_file(FILE),[FILE]). % write result to FILE
5877 recognised_option('-cbc_refinement',cbc_refinement,[]).
5878 recognised_option('-cbc_deadlock_pred',cbc_deadlock_check(GoalPred),[GoalPred]).
5879 recognised_option('-cbc_sequence',cbc_sequence(OpSequence,'',single_solution),[OpSequence]).
5880 recognised_option('-cbc_sequence_all',cbc_sequence(OpSequence,'',findall),[OpSequence]).
5881 recognised_option('-cbc_sequence_with_target',cbc_sequence(OpSequence,TargetPredString,single_solution),[OpSequence,TargetPredString]).
5882 recognised_option('-cbc_sequence_with_target_all',cbc_sequence(OpSequence,TargetPredString,findall),[OpSequence,TargetPredString]).
5883 recognised_option('-comment',comment(UserComment),[UserComment]). % not processed by tool, but will be stored in log-file and used by log_analyser
5884 recognised_option('-junit',junit(Dir),[Dir]).
5885 recognised_option('-junit_test_suite',junit_test_suite(Name),[Name]).
5886 recognised_option('-mcm_cover', mcm_cover(Event),[Event]).
5887 recognised_option('-cbc_cover', cbc_cover(Event),[Event]).
5888 recognised_option('-cbc_cover_match', cbc_cover(match_event(Event)),[Event]). % find events which have Event String occuring somewhere in name
5889 recognised_option('-cbc_cover_all', cbc_cover_all,[]). % is now default if no cbc_cover provided
5890 recognised_option('-cbc_cover_final', cbc_cover_final,[]).
5891 recognised_option('-bmc', cbc_tests(Depth,'#not_invariant',''),[Depth]).
5892 recognised_option('-bdc', cbc_tests(Depth,'#deadlock',''),[Depth]).
5893 recognised_option('-enabling_analysis',enabling_analysis_csv(user_output),[]).
5894 recognised_option('-feasibility_analysis',feasibility_analysis_csv(1000,user_output),[]).
5895 recognised_option('-read_write_matrix',generate_read_write_matrix_csv(user_output),[]).
5896 recognised_option('-scc_trace',check_scc_for_ltl_formula(LtlFormula,SCC),[LtlFormula,SCC]).
5897 recognised_option('-selfcheck_module',selfcheck(M,[]),[M]).
5898 recognised_option('-mc_mode',depth_breadth_first_mode(M),[M]). % can be mixed, hash, heuristic
5899 recognised_option('-assertion',cli_check_assertions(specific(X),[false/0,unknown/0]),[X]).
5900 recognised_option('-cbc_assertion',cbc_assertions(true,[specific(X)]),[X]). % check only a specific assertion
5901 recognised_option('-symbolic_model_check', cli_symbolic_model_check(Algorithm), [Algorithm]).
5902 recognised_option('-ltsmin2',ltsmin2(EndpointPath), [EndpointPath]).
5903 recognised_option('-ltsmin_ltl_output',ltsmin_ltl_output(Path), [Path]).
5904 recognised_option('-ltsmin_option', ltsmin_option(X),[X]).
5905 recognised_option('-machine_hash_check',cli_print_machine_info(hash(X)),[X]).
5906 recognised_option('-install',install_prob_lib(X,[]),[X]).
5907 recognised_option('-install_dry_run',install_prob_lib(X,[dryrun]),[X]).
5908 recognised_option('-load_external_library',load_prob_external_library(PrologModuleFile),[PrologModuleFile]).
5909
5910
5911 recognised_option('-dot_all',dot_generate_for_all_formulas). % generate dot also for true formulas
5912 recognised_option('-animate_all',cli_random_animate(2147483647,false)).
5913 recognised_option('-execute_all',execute(2147483647,false,current_state(1))).
5914 recognised_option('-execute_all_inits',execute(2147483647,false,from_all_initial_states)).
5915 recognised_option('-animate_stats',animate_stats).
5916 recognised_option('-execute_monitor',execute_monitoring).
5917 recognised_option('-check_goal',check_goal).
5918 recognised_option('-ltlassertions',ltl_assertions).
5919 recognised_option('-assertions',cli_check_assertions(all,[false/0,unknown/0])).
5920 recognised_option('-main_assertions',cli_check_assertions(main,[false/0,unknown/0])).
5921 recognised_option('-properties',cli_check_properties).
5922 recognised_option('-properties_core',cli_core_properties(_)). % variable as arg: try various algorithms in order
5923 recognised_option('-properties_core_wd',cli_core_properties(wd_prover)).
5924 recognised_option('-properties_core_z2',cli_core_properties(z3_bup(2))).
5925 recognised_option('-properties_core_z3',cli_core_properties(z3_bup(3))).
5926 recognised_option('-selfcheck',selfcheck(_,[])).
5927 recognised_option('-pacheck',pa_check). % predicate analysis for Kodkod
5928 recognised_option('-det_check',det_check). % check if animation is deterministic
5929 recognised_option('-det_constants',det_constants_check). % check if animation for setup_constants is deterministic
5930 recognised_option('-bf',breadth_first).
5931 recognised_option('-breadth',breadth_first).
5932 recognised_option('-df',depth_first).
5933 recognised_option('-depth',depth_first).
5934 recognised_option('-strict',strict_raise_error).
5935 recognised_option('-silent',silent).
5936 recognised_option('-quiet',silent).
5937 recognised_option('-q',silent).
5938 recognised_option('-force_no_silent',force_no_silent). % override provided silent flag; useful for gitlab test debugging
5939 recognised_option('-statistics',cli_print_statistics(full)).
5940 recognised_option('-stats',cli_print_statistics(full)).
5941 recognised_option('-memory_stats',cli_print_statistics(memory)).
5942 recognised_option('-memory_statistics',cli_print_statistics(memory)).
5943 recognised_option('-memory',cli_print_statistics(memory)).
5944 recognised_option('-profile_stats',cli_print_statistics(sicstus_profile)).
5945 recognised_option('-profile_statistics',cli_print_statistics(sicstus_profile)).
5946 recognised_option('-op_cache_profile',cli_print_statistics(op_cache_profile)).
5947 recognised_option('-hit_profile',cli_print_statistics(hit_profile)). % mainly for ProB developers
5948 recognised_option('-reset_profile_statistics',reset_profiler). % mainly for use in REPL
5949 recognised_option('-nodead',no_deadlocks).
5950 recognised_option('-no_dead',no_deadlocks).
5951 recognised_option('-no_deadlocks',no_deadlocks).
5952 recognised_option('-noinv',no_invariant_violations).
5953 recognised_option('-no_inv',no_invariant_violations).
5954 recognised_option('-no_invariant_violations',no_invariant_violations).
5955 recognised_option('-nogoal',no_goal).
5956 recognised_option('-no_goal',no_goal).
5957 recognised_option('-noltl',no_ltl). % just used for TLC at the moment
5958 recognised_option('-no_ltl',no_ltl).
5959 recognised_option('-noass',no_assertion_violations).
5960 recognised_option('-no_ass',no_assertion_violations).
5961 recognised_option('-no_assertion_violations',no_assertion_violations).
5962 recognised_option('-no_state_errors',no_state_errors). % disable checking for general_errors and transition related state_errors
5963 recognised_option('-nocounter',no_counter_examples).
5964 recognised_option('-no_counter_examples',no_counter_examples).
5965 recognised_option('-nocolor',no_color).
5966 recognised_option('-no_color',no_color).
5967 recognised_option('-no_colour',no_color).
5968 recognised_option('-disable_time_out',set_preference_group(time_out,disable_time_out)).
5969 recognised_option('-disable_timeout',set_preference_group(time_out,disable_time_out)).
5970 %recognised_option('-POR',with_reduction).
5971 recognised_option('-i',animate).
5972 recognised_option('-repl',eval_repl([])). % used to be -eval
5973 recognised_option('-c',coverage(false)).
5974 recognised_option('-cs',coverage(just_summary)).
5975 recognised_option('-coverage',coverage(false)).
5976 recognised_option('-coverage_summary',coverage(just_summary)).
5977 recognised_option('-machine_stats',cli_print_machine_info(statistics)).
5978 recognised_option('-machine_statistics',cli_print_machine_info(statistics)).
5979 recognised_option('-machine_files',cli_print_machine_info(files(no_sha))).
5980 recognised_option('-machine_files_sha',cli_print_machine_info(files(with_sha))).
5981 recognised_option('-machine_hash',cli_print_machine_info(hash(_))).
5982 recognised_option('-check_abstract_constants',check_abstract_constants).
5983 recognised_option('-op_cache_stats',check_op_cache([])).
5984 recognised_option('-op_cache_statistics',check_op_cache([])).
5985 recognised_option('-cv',coverage(true)).
5986 recognised_option('-v',verbose(19)).
5987 recognised_option('-vv',verbose(5)).
5988 recognised_option('-vvv',verbose(1)).
5989 recognised_option('-verbose',verbose(19)).
5990 recognised_option('-debug',verbose(19)).
5991 recognised_option('-verbose_off',verbose_off). % mainly useful in REPL
5992 recognised_option('-voff',verbose_off). % mainly useful in REPL
5993 recognised_option('-very_verbose',verbose(5)).
5994 recognised_option('-gc_trace',set_gc_trace(verbose)). % gc_info
5995 recognised_option('-gc_off',set_gc_on_off(off)).
5996 recognised_option('-gc_on',set_gc_on_off(on)).
5997 recognised_option('-profiling_on',profiling_on). % Prolog profiling
5998 recognised_option('-profile',cli_print_statistics(prob_profile)). % ProB Operation profiling
5999 recognised_option('-prob_profile',cli_print_statistics(prob_profile)). % ProB Operation profiling
6000 recognised_option('-prob_statistics',cli_print_statistics(prob_profile)). % synonym
6001 recognised_option('-prob_stats',cli_print_statistics(prob_profile)). % synonym
6002 recognised_option('-version',print_version(full)).
6003 recognised_option('-cpp_version',print_version(cpp)).
6004 recognised_option('-V',print_version(full)).
6005 recognised_option('-svers',print_version(short)).
6006 recognised_option('-short_version',print_version(short)).
6007 recognised_option('-check_lib',print_version(lib)).
6008 recognised_option('-check_java_version',check_java_version).
6009 recognised_option('-java_version',print_version(java)).
6010 recognised_option('-release_java_parser',release_java_parser).
6011 recognised_option('-fast_read_prob',fast_read_prob).
6012 recognised_option('-file_info',file_info).
6013 recognised_option('-t',default_trace_check).
6014 recognised_option('-init',initialise).
6015 recognised_option('-initialise',initialise).
6016 recognised_option('-ll',log('/tmp/prob_cli_debug.log',prolog)). % see cli_start_logging
6017 recognised_option('-ss',socket(9000,true)). % standard socket 9000
6018 recognised_option('-sf',socket(_,true)). % free socket
6019 recognised_option('-local_socketserver',socket(_,true)). % do not allow remote socket connections
6020 recognised_option('-remote_socketserver',socket(_,false)). % allow remote socket connections
6021 recognised_option('-help',help).
6022 recognised_option('-h',help).
6023 recognised_option('-rc',runtimechecking).
6024 recognised_option('-test_mode',test_mode).
6025 recognised_option('-check_complete',check_complete).
6026 recognised_option('-check_complete_operation_coverage', check_complete_operation_coverage).
6027 recognised_option('-mc_with_tlc', cli_start_mc_with_tlc).
6028 recognised_option('-model_check_with_tlc', cli_start_mc_with_tlc).
6029 recognised_option('-mc_with_lts_sym', cli_start_sym_mc_with_lts(symbolic)).
6030 recognised_option('-mc_with_lts_seq', cli_start_sym_mc_with_lts(sequential)).
6031 recognised_option('-core',disprover_options([disprover_option(unsat_core),unsat_core_algorithm/linear])).
6032 recognised_option('-export_po',disprover_options([disprover_option(export_po_as_machine(user_output))])).
6033 recognised_option('-ltsmin',ltsmin).
6034 recognised_option('-trace',prolog_trace). % enter Prolog debugger on development system after starting up ProB
6035
6036 % some utilities to be able to call the above options directly from repl:
6037 :- public silent/0, coverage/1, help/0.
6038 % predicate to set_verbose_mode
6039 %verbose :- tcltk_turn_debugging_on(19).
6040 %very_verbose :- tcltk_turn_debugging_on(5).
6041 verbose(Nr) :- tcltk_turn_debugging_on(Nr),
6042 (Nr<10 -> set_gc_trace(verbose) ; true). % terse is another option for gc_trace
6043 verbose_off :- set_gc_trace(off), tcltk_turn_debugging_off.
6044 file_info :- file_loaded(true,MainFile), print_file_info(MainFile).
6045 coverage(ShowEnabledInfo) :- probcli_time_stamp(NOW), cli_show_coverage(ShowEnabledInfo,NOW).
6046
6047 % Governs global stack garbage collection trace messages
6048 set_gc_trace(X) :- member(X,[off,terse,verbose]),!,set_prolog_flag(gc_trace,X).
6049 set_gc_trace(X) :- add_error(prob_cli,'Illegal value for gc_trace:',X).
6050
6051 % At least Margin kilobytes of free global stack space are guaranteed to exist after a garbage collection
6052 set_gc_margin(Margin) :- set_prolog_flag(gc_margin,Margin).
6053 set_gc_on_off(OnOff) :- set_prolog_flag(gc,OnOff).
6054
6055 silent :- (option(silent) -> true ; assert_option(silent)).
6056 help :- eval_help.
6057 dot_command(DCommand,DotFile,DotEngine) :- call_dot_command_with_engine(DCommand,DotFile,[],DotEngine).
6058 dot_command_for_expr(DECommand,Expr,DotFile,Opts,DotEngine) :-
6059 call_dot_command_with_engine_for_expr(DECommand,Expr,DotFile,Opts,DotEngine).
6060
6061 plantuml_command(PCommand,UmlFile) :- call_plantuml_command(PCommand,UmlFile).
6062 plantuml_command_for_expr(PECommand,Expr,UmlFile,Opts) :-
6063 call_plantuml_command_for_expr(PECommand,Expr,UmlFile,Opts).
6064
6065 :- use_module(tools_io,[safe_intelligent_open_file/3]).
6066 csv_table_command(TCommand,Formulas,Options,CSVFile) :-
6067 append(Formulas,[TableResult],ActualArgs),
6068 OptionalArgs=[],
6069 format_with_colour_nl(user_output,[blue],'Calling table command ~w',[TCommand]),
6070 call_command(table,TCommand,_,ActualArgs,OptionalArgs),
6071 write_table_to_csv_file(CSVFile,Options,TableResult),
6072 format_with_colour_nl(user_output,[blue],'Finished exporting ~w to ~w',[TCommand,CSVFile]).
6073
6074
6075 save_state_space(StateFile) :- debug_println(20,'% Saving state space to file'),
6076 state_space:tcltk_save_state_space(StateFile).
6077 :- public load_state/1. % for REPL
6078 load_state(StateFile) :- debug_println(20,'% Loading state space from file'),
6079 state_space:tcltk_load_state(StateFile).
6080 :- public execute/3. % for REPL
6081 execute(ESteps,ErrOnDeadlock,From) :- cli_execute(ESteps,ErrOnDeadlock,From).
6082
6083 option_verbose :- option(verbose(_)).
6084 option_very_verbose :- debug_level_active_for(5).
6085
6086 set_random_seed_to_deterministic_start_seed :-
6087 % in test_mode we do not change the random number generator's initial seed
6088 true. %getrand(CurrState),setrand(CurrState). % this seems to be a no-op
6089
6090 :- if(predicate_property(set_random(_), _)).
6091 % SWI-Prolog's native API for reinitializing the RNG state.
6092 % The equivalent of this call is also performed automatically by SWI
6093 % when a random number is requested for the first time.
6094 set_new_random_seed :- set_random(seed(random)).
6095 :- else.
6096 % SICStus way of (re)initializing the RNG state.
6097 % Note that on SICStus, the initial RNG state after startup is always the same,
6098 % so it *must* be manually reinitialized like this to get actually random results!
6099 %:- use_module(library(random),[setrand/1]).
6100 set_new_random_seed :-
6101 now(TimeStamp), % getting the unix time
6102 setrand(TimeStamp). % setting new random seed by every execution of probcli
6103 :- endif.
6104
6105 halt_exception :- halt_exception(0).
6106 halt_exception(Code) :-
6107 stop_prob,
6108 throw(halt(Code)).
6109
6110 % -----------------
6111
6112 start_xml_feature(FeatureName,[CErrs1,CWarns1,CEErrs1]) :-
6113 debug_format(20,'% Starting ~w~n',[FeatureName]),
6114 get_counter(cli_errors,CErrs1), get_counter(cli_warnings,CWarns1), get_counter(cli_expected_errors,CEErrs1),
6115 start_xml_group_in_log(FeatureName).
6116
6117 start_xml_feature(FeatureName,Attr,Value,[CErrs1,CWarns1,CEErrs1]) :-
6118 debug_format(20,'% Starting ~w (~w=~w)~n',[FeatureName,Attr,Value]),
6119 get_counter(cli_errors,CErrs1), get_counter(cli_warnings,CWarns1), get_counter(cli_expected_errors,CEErrs1),
6120 start_xml_group_in_log(FeatureName,Attr,Value).
6121
6122 stop_xml_feature(FeatureName,[CErrs1,CWarns1,CEErrs1]) :-
6123 get_counter(cli_errors,CErrs2), get_counter(cli_warnings,CWarns2), get_counter(cli_expected_errors,CEErrs2),
6124 CErrs is CErrs2-CErrs1, CWarns is CWarns2-CWarns1, CEErrs is CEErrs2-CEErrs1,
6125 (CEErrs>0
6126 -> write_xml_element_to_log('probcli-errors',[errors/CErrs,warnings/CWarns,expected_errors/CEErrs])
6127 ; write_xml_element_to_log('probcli-errors',[errors/CErrs,warnings/CWarns])
6128 ),
6129 debug_format(20,'% Finished ~w (errors=~w, warnings=~w, expected_errors=~w)~n',[FeatureName,CErrs,CWarns,CEErrs]),
6130 stop_xml_group_in_log(FeatureName),
6131 !.
6132 stop_xml_feature(FeatureName,L) :-
6133 add_internal_error('Illegal or failed call:',stop_xml_feature(FeatureName,L)).
6134
6135 %(CErrs>0 -> (file_loaded(_,MainFile) -> true ; MainFile=unknown), Time=unknown, % TO DO: determine time
6136 % create_and_print_junit_result(['Feature',MainFile], FeatureName, Time, error) ; true).
6137 % Note: call stop_xml_group_in_log if the feature stops unexpectedly and you do not have the Info list available
6138
6139 % -----------------
6140
6141 :- public user:runtime_entry/1.
6142 user:runtime_entry(start) :- go_cli.
6143
6144 %save :- save_program('probcli.sav').
6145
6146 :- use_module(eventhandling,[announce_event/1]).
6147 :- announce_event(compile_prob).