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 :- module(state_space,
6 [get_state_space_stats/3, get_state_space_stats/4,
7 gen_new_state_id/1,
8 history/1, forward_history/1,
9 get_action_trace/1, % old trace/1
10 get_action_trace_with_limit/2,
11 get_action_term_trace/1,
12 op_trace_ids/1, add_to_op_trace_ids/1, remove_from_op_trace_ids/1, reset_op_trace_ids/0,
13 get_state_id_trace/1,
14 current_state_id/1, current_expression/2,
15 set_current_state_id/1,
16 current_options/1, set_current_options/1,
17 get_current_predecessor_state_id/1,
18
19 add_id_at_front/1, add_id_at_end/1,
20 add_id_random/1, /* from state_space_open_nodes_c */
21 add_id_with_weight/2, add_id_to_process/3,
22 pop_id_from_front/1, pop_id_from_end/1, pop_id_oldest/1,
23 retract_open_node/1, open_ids_empty/0,
24 top_front_id/1, top_front_weight/1,
25
26 visited_expression/3, visited_expression/2, visited_expression_id/1,
27 find_hashed_packed_visited_expression/3,
28 retract_visited_expression/2,
29 not_all_transitions_added/1,
30 not_invariant_checked/1, set_invariant_checked/1,
31 invariant_not_yet_checked/1, invariant_still_to_be_checked/1,
32 not_interesting/1, % nodes ignored because they do not satisfy a user-provided scope predicate
33 mark_as_not_interesting/1,
34 max_reached_for_node/1,
35 max_reached_or_timeout_for_node/1,
36 use_no_timeout/1, time_out_for_node/1, time_out_for_node/3, virtual_time_out_for_node/1,
37 hash_to_id/2,id_to_marker/2, hash_to_nauty_id/2,
38 register_back_edge/2, try_compute_depth_of_state_id/2,
39 invariant_violated/1, time_out_for_invariant/1, time_out_for_assertions/1,
40 set_invariant_violated/1,
41
42 state_error_exists/0, state_error/3, store_state_error/3,
43 set_context_state/1, set_context_state/2,
44 update_context_state/1, clear_context_state/0, get_current_context_state/1,
45 store_error_for_context_state/2,
46 copy_current_errors_to_state/2,
47 store_abort_error_for_context_state_if_possible/4,
48 abort_error_exists_in_context_state/1,
49
50 transition/3,transition/4, any_transition/3,
51 store_transition/4,
52 deadlocked_state/1, % no outgoing edge
53 is_initial_state_id/1, is_concrete_constants_state_id/1,
54 multiple_concrete_constants_exist/0,
55 root_sufficiently_explored/0,
56 get_constants_state_for_id/2, get_constants_state_for_id/3,
57 get_constants_state_id_for_id/2,
58 try_get_unique_constants_state/1,
59 get_constants_id_for_state_id/2,
60 get_variables_state_for_id/2,
61 out_degree/2,
62 operation_not_yet_covered/1, operation_name_not_yet_covered/1,
63 get_operation_name_coverage_infos/4,
64 mark_operation_as_covered/1,
65 initialise_operation_not_yet_covered/0,
66
67 transition_info/2, store_transition_infos/2,
68 keep_transition_info/1, check_relevant_transition_info_stored/2,
69 compute_transitions_if_necessary/1,
70
71 state_space_initialise/0, state_space_initialise_with_stats/0,
72 state_space_reset/0,
73 state_space_add/2, state_space_packed_add/2,
74 delete_node/1,
75
76 current_state_corresponds_to_initialised_b_machine/0,
77 current_state_corresponds_to_fully_setup_b_machine/0,
78 current_state_corresponds_to_setup_constants_b_machine/0,
79 visited_state_corresponds_to_initialised_b_machine/1,
80 visited_state_corresponds_to_setup_constants_b_machine/1,
81
82 specialized_inv/2, %reuse_operation/4,
83 assert_max_reached_for_node/1, assert_time_out_for_node/3,
84 assert_time_out_for_invariant/1, assert_time_out_for_assertions/1,
85
86 set_max_nr_of_new_impl_trans_nodes/1,
87 get_max_nr_of_new_impl_trans_nodes/1,
88 impl_trans_term/3, impl_trans_term/4,
89 impl_trans_term_all/2,
90 impl_trans_id/4, impl_trans_not_complete/1,
91 compute_transitions_if_necessary_saved/1,
92 max_nr_of_new_nodes_limit_not_reached/0,
93
94 find_trace_to_initial_state/2, find_initialised_states/1,
95
96 tcltk_save_state_space/1, tcltk_load_state/1,
97 compute_full_state_space_hash/1,
98
99 execute_id_trace_from_current/1, execute_id_trace_from_current/3,
100 set_trace_by_transition_ids/1, try_set_trace_by_transition_ids/1,
101 extend_trace_by_transition_ids/1,
102 extract_term_trace_from_transition_ids/2,
103
104 add_counterexample_node/1, add_counterexample_op/1,
105 reset_counterexample/0, set_counterexample_by_transition_ids/1,
106 counterexample_node/1, counterexample_op/1, % specific predicates to register counter examples
107
108 portray_history/0
109 ]).
110
111 :- use_module(library(lists)).
112
113 :- use_module(self_check).
114 :- use_module(error_manager).
115 :- use_module(gensym).
116 :- use_module(preferences).
117 :- use_module(tools).
118 :- use_module(debug,[debug_println/1, debug_println/2]).
119 %:- use_module(state_space_exploration_modes,[compute_hash/3]).
120
121 :- use_module(extension('counter/counter'),
122 [counter_init/0, new_counter/1, get_counter/2, inc_counter/1, inc_counter/2, inc_counter_by/2, reset_counter/1, set_counter/2]).
123
124 :- use_module(module_information).
125 :- module_info(group,state_space).
126 :- module_info(description,'This module keeps track of the visited states by the animator/model checker.').
127
128 % ----------------------------------
129
130 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
131 :- if((environ(prob_myheap,false) ; \+ predicate_property(load_foreign_resource(_), _))).
132 :- use_module(state_space_open_nodes). %% comment in to use only Prolog datastructures
133 :- else.
134 :- use_module(state_space_open_nodes_c). %% comment in to use C++ multimap queue; can make use of HEURISTIC_FUNCTION
135 :- endif.
136
137 % ----------------------------------
138
139 get_state_space_stats(NrNodes,NrTransitions,ProcessedNodes) :-
140 get_counter(states,N), NrNodes is N+1,
141 get_counter(transitions,NrTransitions),
142 get_counter(processed_nodes,ProcessedNodes).
143
144 get_state_space_stats(NrNodes,NrTransitions,ProcessedNodes,IgnoredNodes) :-
145 get_state_space_stats(NrNodes,NrTransitions,ProcessedNodes),
146 get_counter(not_interesting_nodes,IgnoredNodes).
147
148 gen_new_state_id(Nr) :-
149 inc_counter(states,N1), Nr is N1-1. % only one C call
150 %get_counter(states,Nr), inc_counter(states).
151 reset_state_counter :- reset_counter(states).
152 reset_state_counter(Nr) :- set_counter(states,Nr).
153
154 get_state_id_trace(StateIds) :-
155 history(History),
156 current_state_id(CurID),
157 reverse([CurID|History],StateIds).
158
159 get_current_predecessor_state_id(PriorID) :-
160 history([PriorID|_]).
161
162 :- dynamic history/1.
163 history([]).
164
165
166 :- dynamic forward_history/1.
167
168 :- dynamic current_state_id/1.
169 current_state_id(root).
170 /* INITIAL STATE, third arg: clp(fd) constraints as generated
171 by fd_copy_term */
172
173 current_expression(ID,State) :- current_state_id(ID),
174 visited_expression(ID,State).
175 current_packed_expression(ID,State) :- current_state_id(ID),
176 packed_visited_expression(ID,State).
177
178 :- use_module(specfile,[state_corresponds_to_initialised_b_machine/1,
179 state_corresponds_to_fully_setup_b_machine/1,
180 state_corresponds_to_set_up_constants/1]).
181 current_state_corresponds_to_initialised_b_machine :-
182 current_packed_expression(_,PS), unpack_state_top_level(PS,TLState),
183 state_corresponds_to_initialised_b_machine(TLState).
184 visited_state_corresponds_to_initialised_b_machine(ID) :-
185 packed_visited_expression(ID,PS), unpack_state_top_level(PS,TLState),
186 state_corresponds_to_initialised_b_machine(TLState).
187
188 current_state_corresponds_to_fully_setup_b_machine :-
189 current_packed_expression(_,PS), unpack_state_top_level(PS,TLState),
190 state_corresponds_to_fully_setup_b_machine(TLState).
191
192 current_state_corresponds_to_setup_constants_b_machine :-
193 current_packed_expression(_,PS), unpack_state_top_level(PS,TLState),
194 state_corresponds_to_set_up_constants(TLState).
195
196 visited_state_corresponds_to_setup_constants_b_machine(ID) :-
197 packed_visited_expression(ID,PS), unpack_state_top_level(PS,TLState),
198 state_corresponds_to_set_up_constants(TLState).
199
200 :- dynamic current_options/1.
201 current_options([]).
202
203 set_current_options(Options) :-
204 retractall( current_options(_) ),
205 assertz( current_options(Options) ).
206
207 :- dynamic packed_visited_expression/2.
208 %packed_visited_expression(v_0,true).
209
210 :- use_module(state_packing).
211
212 retract_visited_expression(ID,State) :- retract(packed_visited_expression(ID,PState)),
213 unpack_state(PState,State).
214
215 retractall_visited_expression(ID) :- retractall(packed_visited_expression(ID,_)).
216
217 state_space_packed_add(Id,PackedTerm) :- assertz(packed_visited_expression(Id,PackedTerm)).
218
219 state_space_add(Id,Term) :-
220 (pack_state(Term,PackedTerm) -> assertz(packed_visited_expression(Id,PackedTerm))
221 ; add_internal_error('State packing failed: ',pack_state(Term,_)),
222 assertz(packed_visited_expression(Id,Term))).
223
224 % deprecated:
225 visited_expression(ID,State,true) :- visited_expression(ID,State).
226 % not call(CurBody); for the moment we always have true as last argument
227
228 :- assert_must_succeed((assertz(state_space:packed_visited_expression(sm_test_bad_state,'$cst'(not_a_list))),
229 call_cleanup(\+ state_space:visited_expression(sm_test_bad_state,_),
230 (retractall(state_space:packed_visited_expression(sm_test_bad_state,_)),
231 error_manager:reset_errors, error_manager:reset_real_error_occurred)))).
232 % we fail if unpacking fails: returning an unbound state would match any state pattern of the caller
233 visited_expression(A,B) :- packed_visited_expression(A,PB),
234 (unpack_state(PB,R) -> B=R ; add_internal_error('Unpacking state failed: ',unpack_state(PB,_)),fail).
235
236 %visited_expression_id(A) :- packed_visited_expression(A,_). % avoid unpacking state
237 % even better: not to look up fact at all to avoid constructing state term, this is done below:
238 :- use_module(library(between),[between/3]).
239 visited_expression_id(ID) :- number(ID),!, ID>=0, get_counter(states,N), ID<N.
240 visited_expression_id(ID) :- ID==root,!.
241 visited_expression_id(root).
242 visited_expression_id(Nr) :- Nr \== root, get_counter(states,N), N1 is N-1, between(0,N1,Nr).
243
244 % given a hash and a packed state: find ID (fail if does not exist)
245 find_hashed_packed_visited_expression(Hash,PackedState,ID) :-
246 hash_to_id(Hash,ID),
247 (packed_visited_expression(ID,PackedState)
248 -> true /* warning: may instantiate State if not ground */
249 ; functor(PackedState,concrete_constants,1),
250 preference(maxNrOfInitialisations,Max), Max =< 4
251 -> debug_println(19,hash_collision_for_constants(Hash,ID)),fail
252 % this is not too bad if maxNrOfInitialisations small;
253 % can happen due to depth limit in term_depth_hash in compute_hash
254 ; formatsilent('* hash collision for id=~w hash=~w~n',[ID,Hash]),fail
255 ).
256
257
258 :- dynamic not_invariant_checked/1.
259 set_invariant_checked(ID) :- %print(inv_checked(ID)),nl,
260 retract(not_invariant_checked(ID)).
261
262 invariant_not_yet_checked(ID) :-
263 not_all_transitions_added(ID) ; /* assumption: if not all transitions added then we haven't checked invariant yet */
264 not_invariant_checked(ID) ;
265 not_interesting(ID). % assumption: if a node is marked as not interesting it will not be examined
266
267 % difference with invariant_not_yet_checked: not interesting nodes not reported and cannot be backtracked
268 invariant_still_to_be_checked(ID) :-
269 (not_all_transitions_added(ID) -> true ; not_invariant_checked(ID) -> true).
270
271 :- dynamic not_interesting/1.
272 %not_interesting(v_0).
273
274 :- dynamic max_reached_for_node/1.
275 /* true if not all outgoing transistions were computed due to the limit
276 on the number of operations/initialisations computed */
277 :- dynamic time_out_for_node/3, use_no_timeout/1, time_out_for_invariant/1, time_out_for_assertions/1.
278
279 time_out_for_node(ID) :- (var(ID) -> visited_expression_id(ID) ; true),
280 (time_out_for_node(ID,_,_) -> true ; fail).
281
282 % only succeeds for virtual time_outs
283 virtual_time_out_for_node(ID) :- (var(ID) -> visited_expression_id(ID) ; true),
284 (time_out_for_node(ID,_,virtual_time_out) -> true ; fail).
285
286 :- dynamic transition/4.
287 %transition(v_0,a,1,v_1).
288
289 store_transition(Org,Action,Dest,Id) :-
290 %get_counter(transitions,Id), inc_counter(transitions),
291 inc_counter(transitions,Id1), Id is Id1-1, % only one C call
292 assertz(transition(Org,Action,Id,Dest)).
293
294 deadlocked_state(Origin) :- \+ any_transition(Origin,_,_).
295
296 is_concrete_constants_state_id(ID) :-
297 logical_transition_from_root(ID),
298 packed_visited_expression(ID,PState), % Note: in CSP||B mode there is no csp_and_b wrapper
299 unpack_state_top_level(PState,concrete_constants(_)).
300
301 % get the transition to the first logical successor to root, jumping over start_cspm_MAIN in CSP||B mode
302 logical_transition_from_root(ID) :-
303 transition(root,T,_TransId,ID1),
304 (T=start_cspm_MAIN, csp_with_bz_mode
305 -> transition(ID1,_,_,ID) % the first logical successor of root is a successor of ID1
306 ; ID1=ID
307 ).
308
309 % check if we have explored a successor of root node to find constants (or initial state if no constants exist)
310 % i.e., did we compute successors of root, and in case of CSP||B did we from there set up constants or initialise machine
311 root_sufficiently_explored :-
312 transition(root,T,_TransId,ID1),!,
313 (T=start_cspm_MAIN, csp_with_bz_mode
314 -> \+ not_all_transitions_added(ID1)
315 ; true
316 ).
317
318 % check if we have multiple constant setups
319 multiple_concrete_constants_exist :-
320 is_concrete_constants_state_id(ID),
321 is_concrete_constants_state_id(ID2), ID2 \= ID,!.
322
323
324 is_initial_state_id(InitialStateID) :-
325 logical_transition_from_root(State),
326 packed_visited_expression(State,P),
327 (P = concrete_constants(_) % also covers '$partial_setup_constants'
328 -> state_space:transition(State,_,InitialStateID)
329 ; InitialStateID=State).
330
331 % get the constants for a state (if there are constants), avoid unpacking variables
332 get_constants_state_for_id(ID,CS) :- get_constants_state_for_id(ID,[],CS).
333 get_constants_state_for_id(ID,Opts,ConstantsState) :-
334 packed_visited_expression(ID,PState),
335 unpack_state_top_level(PState,TLState),
336 (get_const_and_vars_id(TLState,CID) -> get_constants_state_for_id(CID,[],ConstantsState)
337 ; unpack_state(PState,UPState),
338 (UPState = concrete_constants(CS) -> ConstantsState=CS
339 ; UPState = [_|_], member(allow_variable_list,Opts),
340 ConstantsState=UPState,
341 % could be that we have a state where constants and variables are mixed in a single list
342 % e.g., ProB2's FindStateCommand does currently not create new intermediate constant states
343 add_message(get_constants_state_for_id,'State is a list of bindings and has no reference to a constant valuation: ',ID)
344 )
345 ).
346
347 get_const_and_vars_id(const_and_vars(CID,_),CID).
348 get_const_and_vars_id(csp_and_b(_,BState),CID) :- get_const_and_vars_id(BState,CID).
349
350 % get the state id for associated constants state for a state (if there are constants)
351 get_constants_state_id_for_id(ID,CstID) :-
352 packed_visited_expression(ID,PState),
353 unpack_state_top_level(PState,TLState),
354 get_constants_id_for_id_aux(TLState,ID,CstID).
355 get_constants_id_for_id_aux(concrete_constants(_),ID,ID).
356 get_constants_id_for_id_aux(const_and_vars(ID,_),_,ID).
357 get_constants_id_for_id_aux(csp_and_b(_,BState),ID,CstID) :- get_constants_id_for_id_aux(BState,ID,CstID).
358
359 get_variables_state_for_id(ID,VarState) :-
360 visited_expression(ID,State),
361 get_vars_aux(State,VarState).
362 %get_vars_aux(concrete_constants(ConstantsState),[]).
363 get_vars_aux(const_and_vars(_,Vars),State) :- !, State=Vars.
364 get_vars_aux([],[]).
365 get_vars_aux([H|T],[H|T]).
366
367 % check if there is a unique constants state:
368 try_get_unique_constants_state(ConstantsState) :-
369 logical_transition_from_root(DestID),
370 \+ (logical_transition_from_root(DestID2), DestID2 \= DestID), % no other transition exists
371 \+ max_reached_or_timeout_for_node(root),
372 DestID \= root, % DestID=root should never happen
373 get_constants_state_for_id(DestID,ConstantsState).
374
375 % returns id of constants state for a state (if it exists)
376 get_constants_id_for_state_id(ID,ConstID) :-
377 packed_visited_expression(ID,PState),
378 get_cstid_from_vars(PState,ConstID).
379
380 get_cstid_from_vars('$cst_vars'(ConstID,_),ConstID). % const_and_vars are always converted to this
381 get_cstid_from_vars(csp_and_b(_,B),ConstID) :- get_cstid_from_vars(B,ConstID).
382
383 any_transition(Origin,TransID,Destination) :- transition(Origin,_,TransID,Destination).
384
385 transition(Origin,Action,Destination) :- transition(Origin,Action,_TransID,Destination).
386
387 :- dynamic transition_info/2.
388 store_transition_infos([],_TransId).
389 store_transition_infos([Info|Irest],TransId) :-
390 store_transition_info(Info,TransId),
391 store_transition_infos(Irest,TransId).
392 store_transition_info(Info,TransId) :- %print(info(Info,TransId)),nl,
393 (keep_transition_info(Info)
394 -> assertz(transition_info(TransId,Info))
395 ; true).
396
397 % Do not store path info by default
398 keep_transition_info(path(_)) :- !,
399 preference(eventtrace,true). % STORE_DETAILED_TRANSITION_INFOS
400 keep_transition_info(eventtrace(_)) :- !,preference(eventtrace,true).
401 keep_transition_info(event(_)) :- !,
402 preference(store_event_transinfo,true). % store info about parameters and abstract Rodin events
403 keep_transition_info(_). % store everything else
404
405 % check if all relevant transition infos have been stored for a transition
406 check_relevant_transition_info_stored([],_).
407 check_relevant_transition_info_stored([Info|Irest],TransId) :-
408 (keep_transition_info(Info) -> transition_info(TransId,Info) ; true),
409 check_relevant_transition_info_stored(Irest,TransId).
410
411
412 reset_transition_store :-
413 retractall(transition(_,_,_,_)),
414 retractall(transition_info(_,_)),
415 reset_counter(transitions),
416 reset_counterexample.
417
418 /*
419 Version with packing of transitions:
420 store_transition(Org,Action,Dest,Id) :-
421 retract(transition_counter(Id)),
422 NewId is Id+1,
423 assertz(transition_counter(NewId)),
424 Action =.. [ActionName|Parameters],
425 pack_values(Parameters,PackedParameters),
426 assertz(packed_transition(Org,ActionName,PackedParameters,Id,Dest)).
427
428 transition(Origin,Action,TransID,Destination) :- nonvar(Action),!,
429 Action =.. [ActionName|Parameters],
430 packed_transition(Origin,ActionName,PackedParameters,TransID,Destination),
431 unpack_values(PackedParameters,Parameters).
432 transition(Origin,Action,TransID,Destination) :-
433 packed_transition(Origin,ActionName,PackedParameters,TransID,Destination),
434 unpack_values(PackedParameters,Parameters),
435 Action =.. [ActionName|Parameters].
436 any_transition(Origin,TransID,Destination) :- packed_transition(Origin,_,_,TransID,Destination).
437 */
438
439 % compute out-degree of a node
440 out_degree(ID,OutDegree) :- findall(0, transition(ID,_,_,_), L), length(L,OutDegree).
441
442 operation_name_not_yet_covered(OpName) :- operation_not_yet_covered(OpName).
443
444
445 get_operation_name_coverage_infos(PossibleNr,FeasibleNr,UncovNr,UncoveredList) :-
446 findall(ON, specfile:get_possible_event(ON), Possible), length(Possible,PossibleNr),
447 findall(OF, specfile:get_feasible_event(OF), Feasible), length(Feasible,FeasibleNr),
448 findall(OpName, state_space: operation_name_not_yet_covered(OpName), UncoveredList),
449 length(UncoveredList,UncovNr).
450
451
452 :- dynamic operation_not_yet_covered/1.
453 %operation_not_yet_covered(b).
454
455 :- use_module(probsrc(debug),[formatsilent/2]).
456 mark_operation_as_covered(OpName) :-
457 (operation_not_yet_covered(OpName), % small improvement in B/PerformanceTests/ModelChecking/EnumSetLookups.mch
458 retract(operation_not_yet_covered(OpName))
459 -> (preferences:get_preference(provide_trace_information,true)
460 -> formatsilent('Covered ~w~n',[OpName])
461 ; true),
462 (operation_not_yet_covered(_) -> true ; formatsilent('~nALL OPERATIONS COVERED~n',[]))
463 ; true
464 ).
465
466 :- use_module(bmachine,[b_top_level_operation/1]).
467 :- use_module(probcspsrc(haskell_csp),[channel/2]).
468 initialise_operation_not_yet_covered :- retractall(operation_not_yet_covered(_)),
469 b_or_z_mode,
470 ? b_top_level_operation(Name),
471 % b_get_machine_operation(Name,_,Par,_), length(Par,Arity), functor(Op,Name,Arity),
472 % Note: no '-->' added
473 assertz(operation_not_yet_covered(Name)),
474 fail.
475 /* Missing: treat operations with return values */
476 initialise_operation_not_yet_covered :- csp_mode, \+ csp_with_bz_mode,
477 channel(Name,_),
478 assertz(operation_not_yet_covered(Name)),
479 fail.
480 initialise_operation_not_yet_covered.
481
482 state_error_exists :- state_error(_,_,_),!.
483 :- dynamic state_error/3.
484
485 %state_error([],invariant_violated).
486
487 reset_next_state_error_id_counter :- reset_counter(next_state_error_id).
488 :- use_module(tools_printing, [print_error/1, format_error_with_nl/2]).
489 :- use_module(error_manager,[print_error_span/1]).
490 store_state_error(State,Error,Id) :- state_error(State,Id,Error),!. % do not store identical error twice
491 store_state_error(State,Error,Id) :-
492 %retract( next_state_error_id(Id) ),
493 inc_counter(next_state_error_id,Id),
494 % tools_printing:print_term_summary(Error),nl, tools_printing:nested_print_term(Error),nl,
495 assertz( state_error(State,Id,Error) ).
496 store_error_for_context_state(Error,Id) :-
497 ( context_state(State,Errs) ->
498 (Errs<25
499 -> store_state_error(State,Error,Id), E1 is Errs+1,
500 %assertz(context_state(State,E1))
501 set_context_number_of_errors(E1)
502 ; store_state_error(State,max_state_errors_reached(25),Id)
503 )
504 ;
505 add_internal_error('No known context when calling store_error_for_context_state: ',store_error_for_context_state(Error,Id)),
506 fail).
507
508 % check if we already have a certain type of error in the current context state
509 abort_error_exists_in_context_state(ErrType) :- get_current_context_state(State),
510 Error = abort_error(ErrType,_Msg,_Term,_Pos),
511 state_error(State,_Id,Error).
512
513 % copy current errors from error_manager to state errors
514 copy_current_errors_to_state(StateID,Context) :-
515 % error_manager:logged_error(Source,ErrMsg,_Context,Span), % will not retract
516 error_manager:get_error_with_span(Source,ErrMsg,Span), % will retract
517 store_state_error(StateID,abort_error(Source,ErrMsg,'',span_context(Span,Context)),SID),
518 % TO DO: use other error class
519 debug_println(4,stored_state_error(Source,SID,_Context,ErrMsg)),
520 fail.
521 copy_current_errors_to_state(_,_).
522
523 store_abort_error_for_context_state_if_possible(ErrType,Msg,Term,Span) :-
524 %print(store(Msg,Term,Span)),nl,
525 ( get_current_context_state(State) ->
526 error_manager:get_error_context(Context),
527 (abort_error_for_same_location_exists(State,Id1,ErrType,Msg,Span),
528 abort_error_for_same_location_exists(State,Id2,ErrType,Msg,Span),
529 Id2>Id1
530 -> /* two errors of same type, for same state and same source location exists */
531 /* TO DO: maybe merge state errors */
532 simplify_span(Span,Span1),
533 compress_span(Span1,Span2),
534 store_state_error(State,abort_error(ErrType,'Further identical errors occurred (not stored !)',Term,span_context(Span2,Context)),_)
535 ;
536 format_error_with_nl('! An error occurred in state ~w: ~w !',[State,ErrType]),
537 % usual errors: precondition_error, while_invariant_violation, while_variant_error,
538 % assert_error, well_definedness_error, card_overflow_error
539 print_error(Msg),
540 print_error_term(Term,Span),
541 % print_error(context_state_id(State)), % printed by print_error_context
542 print_error_context,
543 (debug_mode(on),visited_expression(State,S) -> translate:translate_bstate(S,O),print_error(O) ; true),
544 compress_span(Span,Span2),
545 print_error_span(Span2),
546 store_state_error(State,abort_error(ErrType,Msg,Term,span_context(Span2,Context)),_)
547 ),
548 (add_new_event_in_error_scope(abort_error(ErrType)) -> true ; true), % should we use well_definedness_error?
549 assert_real_error_occurred(abort_error) % Note that in this case the error manager list of errors maybe empty even though real_error_occured is true. (see ProB2 kernel test de.prob.cli.integration.rules.RulesMachineTest > testReuseStateSpace)
550 ; % no current context_state exists:
551 compress_span(Span,Span2),
552 add_error(ErrType,Msg,Term,Span2)
553 ).
554
555
556 :- use_module(bsyntaxtree, [find_identifier_uses/3]).
557 compress_span(span_context(Span,C),span_context(CS,C)) :- !,
558 compress_span(Span,CS).
559 compress_span(pos_context(Span1,C,Span2),pos_context(CS1,C,CS2)) :- !,
560 compress_span(Span1,CS1),
561 compress_span(Span2,CS2).
562 compress_span(span_predicate(Pred,LS,S),Res) :- find_identifier_uses(Pred,[],Ids),
563 sort(Ids,SIds),
564 filter_state(LS,SIds,FLS),
565 filter_state(S,SIds,FS), % TODO: do we need to store the global state? we can reconstruct it ?
566 % format('Compressed span_predicate (~w)~n',[Ids]),
567 !,
568 Res = span_predicate(Pred,FLS,FS).
569 compress_span(S,S).
570 % avoid storing large useless values
571 % TO DO: probably we should stop storing spans when a certain threshold of number of errors is reached
572
573
574 :- use_module(library(ordsets),[ord_member/2]).
575 filter_state([],_,[]).
576 filter_state([bind(ID,L)|T],Vars,Res) :-
577 (ord_member(ID,Vars) -> Res = [bind(ID,L)|RT] ; Res=RT),
578 filter_state(T,Vars,RT).
579
580
581 :- use_module(translate, [translate_error_term/3]).
582 print_error_term(T,S) :- (var(T);var(S)),!,
583 print_error('### VARIABLE error term or span:'), print_error(print_error_term(T,S)).
584 print_error_term(Term,Span) :- translate_error_term(Term,Span,S),
585 (S='' -> true ; print_error(S)).
586
587 abort_error_for_same_location_exists(State,Id,ErrType,Msg,Span) :-
588 state_error(State,Id,abort_error(ErrType,Msg,_Term2,span_context(Span2,_Ctxt2))),
589 same_span_location(Span2,Span).
590 % should be moved to error_manager ?
591 same_span_location(span_context(Span1,C),span_context(Span2,C)) :- !, same_span_location(Span1,Span2).
592 same_span_location(pos_context(Span1,C,_),pos_context(Span2,C,_)) :- !,
593 same_span_location(Span1,Span2). % should we check second span?
594 same_span_location(span_predicate(Pred1,_,_),span_predicate(Pred2,_,_)) :- !,Pred1=Pred2.
595 same_span_location(X,X).
596
597 :- dynamic saved_nested_context_state/2.
598 save_nested_context_state(_S) :-
599 bb_get(state_space_context_state,ID),
600 bb_get(state_space_context_errors,Errs),!,
601 %print(saving_context_state(_S,ID,Errs)),nl,
602 asserta(saved_nested_context_state(ID,Errs)).
603 save_nested_context_state(_).
604
605 % actually pops context state
606 clear_context_state :-
607 retract(saved_nested_context_state(ID,Errs)),!, %print(restoring_nested(ID,Errs)),nl,
608 bb_put(state_space_context_state,ID),
609 bb_put(state_space_context_errors,Errs).
610 clear_context_state :-
611 (bb_delete(state_space_context_state,_) -> true ; true).
612 %(retract(context_state(_,_)) -> true ; true). % retractall seems to be slowing down with use
613
614 % Note: Each Prolog module maintains its own blackboard for bb_get/bb_put
615 context_state(ID,Errs) :-
616 bb_get(state_space_context_state,ID), bb_get(state_space_context_errors,Errs).
617
618 % sets a new context state; pushing the previous one if necessary
619 set_context_state(State) :- %print(set_id(State)),nl,
620 save_nested_context_state(State),
621 bb_put(state_space_context_state,State),
622 bb_put(state_space_context_errors,0).
623
624 set_context_state(State,_Context) :- % Context can be used for debugging later
625 set_context_state(State).
626
627 % update current context state, without storing nested states
628 update_context_state(State) :-
629 bb_put(state_space_context_state,State),
630 bb_put(state_space_context_errors,0).
631
632 get_current_context_state(ID) :- bb_get(state_space_context_state,ID).
633 %get_current_context_state(ID) :- context_state(ID,_).
634
635 set_context_number_of_errors(Errs) :- bb_put(state_space_context_errors,Errs).
636
637 retractall_invariant_violated(State) :-
638 retractall(state_error(State,_,invariant_violated)).
639 invariant_violated(State) :-
640 state_error(State,_,invariant_violated).
641 set_invariant_violated(State) :-
642 ( invariant_violated(State) -> true
643 ; time_out_for_invariant(State) % only a time-out for this state matters, not for other states
644 -> write('Timeout for node: '), print(State),nl,
645 write('Not setting invariant violation status'),nl
646 ; store_state_error(State,invariant_violated,_)
647 ).
648
649 %:- set_invariant_violated([]). % why is this ??
650
651
652 :- dynamic hash_to_id/2.
653 :- dynamic id_to_marker/2.
654 :- dynamic id_back_edge/3. % optional facts to keep track where a state was constructed from
655
656 :- dynamic hash_to_nauty_id/2. % used in nauty mode to map nauty id's to hash values
657
658 :- dynamic specialized_inv/2. /* stores whether for a node a specialized invariant
659 version could be computed */
660
661 % :- dynamic reuse_operation/4. /* when for a state and given operation name we can reuse the operation computed for another state */
662 % used to be used for OPERATION_REUSE TRUE
663
664 :- use_module(hashing).
665 state_space_startup :- % call once at startup to ensure all counters exist
666 counter_init,
667 new_counter(states), new_counter(processed_nodes), new_counter(transitions),
668 new_counter(next_state_error_id),
669 new_counter(not_interesting_nodes),
670 reset_open_ids. % also calls myheap init
671 state_space_initialise :- counter_init, reset_gennum, reset_gensym,
672 new_counter(states), new_counter(processed_nodes), new_counter(transitions),
673 new_counter(next_state_error_id), new_counter(not_interesting_nodes),
674 reset_state_counter, reset_processed_nodes_counter, reset_next_state_error_id_counter,
675 retractall_visited_expression(_),
676 reset_open_ids,
677 reset_stored_values, % state_packing
678 retractall(not_invariant_checked(_)),
679 reset_not_interesting,
680 retractall(max_reached_for_node(_)),
681 retractall(time_out_for_node(_,_,_)),
682 retractall(time_out_for_invariant(_)),
683 retractall(time_out_for_assertions(_)),
684 retractall(use_no_timeout(_)),
685 retractall(state_error(_,_,_)),
686 clear_context_state,
687 reset_transition_store,
688 retractall(operation_not_yet_covered(_)),
689 retractall(hash_to_id(_,_)),
690 retractall(id_back_edge(_,_,_)),
691 retractall(hash_to_nauty_id(_,_)),
692 retractall(id_to_marker(_,_)),
693 retractall(specialized_inv(_,_)),
694 %retractall(reuse_operation(_,_,_,_)),
695 state_space_add(root,root),
696 add_id_at_front(root),
697 my_term_hash(root,RootHash),
698 assertz(hash_to_id(RootHash,root)),
699 %assertz(not_invariant_checked(root)),
700 state_space_reset.
701
702 :- use_module(eventhandling,[register_event_listener/3]).
703 :- register_event_listener(startup_prob,state_space_startup,
704 'Initialise Statespace Counters.').
705 :- register_event_listener(reset_specification,state_space_initialise,
706 'Reset Statespace.').
707 :- register_event_listener(change_of_animation_mode,state_space_initialise,
708 'Reset Statespace.').
709 :- register_event_listener(specification_initialised,initialise_operation_not_yet_covered,
710 'Init coverage info.').
711 :- register_event_listener(reset_prob,state_space_initialise,
712 'Reset Statespace.').
713
714 /* A version of reset which checks how much memory is used by each fact */
715 /* state_space:init_with_stats */
716 state_space_initialise_with_stats :-
717 reset_gennum, reset_gensym, reset_state_counter, reset_processed_nodes_counter,
718 reset_next_state_error_id_counter,
719 retract_open_ids_with_statistics,
720 retract_with_statistics(state_space,[packed_visited_expression(_,_),
721 not_invariant_checked(_),
722 not_interesting(_),
723 max_reached_for_node(_),
724 time_out_for_node(_,_,_),
725 time_out_for_invariant(_),
726 time_out_for_assertions(_),
727 use_no_timeout(_),
728 state_error(_,_,_),
729 transition(_,_,_,_),
730 transition_info(_,_),
731 operation_not_yet_covered(_),
732 hash_to_id(_,_),
733 hash_to_nauty_id(_,_),
734 id_to_marker(_,_),
735 specialized_inv(_,_),
736 %reuse_operation(_,_,_,_),
737 history(_), forward_history(_), op_trace_ids(_)]),
738 reset_not_interesting,
739 retract_stored_values_with_statistics,
740 clear_context_state,
741 reset_transition_store,
742 state_space_add(root,root),
743 add_id_at_front(root),
744 %assertz(not_invariant_checked(root)),
745 state_space_reset,
746 initialise_operation_not_yet_covered.
747
748
749
750 :- dynamic op_trace_ids/1.
751 reset_trace :- retractall(op_trace_ids(_)), assertz(op_trace_ids([])).
752 get_action_trace(T) :- trace(T).
753 get_action_term_trace(PT) :- get_action_trace_with_limit(0,T), project_on_action_term(T,PT).
754 trace(Trace) :- get_action_trace_with_limit(500,Trace).
755 get_action_trace_with_limit(Limit,Trace) :-
756 op_trace_ids(IDT), reverse(IDT,RIDT),
757 extract_trace_from_transition_ids(RIDT,root,Limit,[],Trace).
758
759 reset_op_trace_ids :- retractall(op_trace_ids(_)), assertz(op_trace_ids([])).
760 add_to_op_trace_ids(OpID) :- retract(op_trace_ids(OpIDS)), assertz(op_trace_ids([OpID|OpIDS])).
761 remove_from_op_trace_ids(OpID) :- retract(op_trace_ids(OpIDS)),
762 (OpIDS = [R|Rest]
763 -> assertz(op_trace_ids(Rest)), OpID = R
764 ; assertz(op_trace_ids(OpIDS)), fail).
765
766 % translate a list of transition ids (from root) into a list of operation terms
767 extract_term_trace_from_transition_ids(TransIDListFromRoot,Trace) :-
768 extract_trace_from_transition_ids(TransIDListFromRoot,root,0,[],ActionTrace),
769 reverse_and_project_on_action_term(ActionTrace,[],Trace).
770
771 reverse_and_project_on_action_term([],A,A).
772 reverse_and_project_on_action_term([action(_,Term)|T],Acc,Res) :- !,
773 reverse_and_project_on_action_term(T,[Term|Acc],Res).
774 reverse_and_project_on_action_term([H|T],Acc,Res) :-
775 add_error(reverse_and_project_on_action_term,'Illegal action: ',H),
776 reverse_and_project_on_action_term(T,[H|Acc],Res).
777
778 project_on_action_term([],[]).
779 project_on_action_term([action(_,Term)|T],Res) :- !, Res=[Term|TR],
780 project_on_action_term(T,TR).
781 project_on_action_term([H|T],Res) :-
782 add_error(project_on_action_term,'Illegal action: ',H),
783 project_on_action_term(T,Res).
784
785 extract_trace_from_transition_ids([],_CurrentState,_,Trace,Trace).
786 extract_trace_from_transition_ids([TransId|Rest],CurrentState,Limit,AccTrace,Trace) :-
787 compute_op_string(TransId,CurrentState,Limit,OpTerm,OpString,DestState),!,
788 extract_trace_from_transition_ids(Rest,DestState,Limit,
789 [action(OpString,OpTerm)|AccTrace],Trace).
790 extract_trace_from_transition_ids([TransId|_],CurrentState,_,_,_Trace) :-
791 add_error(state_space,'Could not execute transition id: ', TransId:from(CurrentState)),fail.
792
793 :- use_module(translate,[translate_event_with_src_and_target_id/5]).
794 compute_op_string(jump(TO),_CurID,_,Term,String,DestID) :- !, Term=jump,String=jump,DestID=TO.
795 compute_op_string(TransId,CurID,Limit,Term,String,DestID) :- transition(CurID,Term,TransId,DestID),
796 translate_event_with_src_and_target_id(Term,CurID,DestID,Limit,String).
797
798 % reset history and forward history, but not state-space itself
799 state_space_reset :-
800 reset_trace,
801 retractall(history(_)),
802 retractall(forward_history(_)),
803 retractall(current_state_id(_)),
804 retractall(current_options(_)),
805 assertz(history([])),
806 assertz(current_state_id(root)).
807
808 reset_not_interesting :- retractall(not_interesting(_)), reset_counter(not_interesting_nodes).
809
810 mark_as_not_interesting(ID) :- assertz(not_interesting(ID)), inc_counter(not_interesting_nodes).
811
812 set_current_state_id(ID) :- (retract(current_state_id(_)) -> true ; true),
813 assertz(current_state_id(ID)).
814
815 state_space_clean_all :-
816 retractall(state_space_version_in_file(_)),
817 retractall_visited_expression(_),
818 reset_open_ids,
819 retractall(not_invariant_checked(_)),
820 reset_not_interesting,
821 retractall(max_reached_for_node(_)),
822 retractall(time_out_for_node(_,_,_)),
823 retractall(time_out_for_invariant(_)),
824 retractall(time_out_for_assertions(_)),
825 retractall(use_no_timeout(_)),
826 retractall(state_error(_,_,_)),
827 clear_context_state,
828 reset_transition_store,
829 retractall(operation_not_yet_covered(_)),
830 retractall(hash_to_id(_,_)),
831 retractall(id_back_edge(_,_,_)),
832 retractall(hash_to_nauty_id(_,_)),
833 retractall(id_to_marker(_,_)),
834 retractall(specialized_inv(_,_)),
835 %retractall(reuse_operation(_,_,_,_)),
836 retractall(history(_)),
837 retractall(forward_history(_)),
838 retractall(op_trace_ids(_)),
839 retractall(current_state_id(_)),
840 retractall(current_options(_)).
841
842 % this is only used from within the Tcl/Tk animator at the moment:
843 delete_node(ID) :-
844 debug_println(9,deleting(ID)),
845 retractall_visited_expression(ID),
846 retractall_invariant_violated(ID),
847 (retract_open_node_and_update_processed_nodes(ID) -> true ; true), % fails if the node was already processed
848 retractall(not_invariant_checked(ID)),
849 (retract(not_interesting(ID)) -> inc_counter_by(not_interesting_nodes,-1) ; true),
850 retractall(max_reached_for_node(ID)),
851 retractall(time_out_for_node(ID,_,_)),
852 retractall(time_out_for_invariant(ID)),
853 retractall(time_out_for_assertions(ID)),
854 retractall(use_no_timeout(ID)),
855 retractall(state_error(ID,_,_)),
856 retract_transitions_from_or_to(ID),
857 % to do: check if operation_not_yet_covered(_) changes
858 retract_hash(ID),
859 retractall(id_to_marker(ID,_)),
860 retractall(id_back_edge(ID,_,_)).
861
862 % remove outgoing and incoming transitions of a deleted node, together with their transition infos
863 retract_transitions_from_or_to(ID) :-
864 (retract(transition(ID,_,TransId,_)) ; retract(transition(_,_,TransId,ID))),
865 retractall(transition_info(TransId,_)),
866 fail.
867 retract_transitions_from_or_to(_).
868
869 retract_hash(ID) :- retract(hash_to_id(Hash,ID)), retractall(hash_to_nauty_id(_TermHash,Hash)),fail.
870 retract_hash(_).
871
872 % assert max_operations reachoed
873 assert_max_reached_for_node(Id) :- %print_message(max_reached_for_node(Id)),
874 (max_reached_for_node(Id) -> true ; assertz(max_reached_for_node(Id))).
875
876 :- use_module(probsrc(debug),[debug_mode/1]).
877 assert_time_out_for_node(Id,OpName,TypeOfTimeOut) :-
878 (debug_mode(off),functor(TypeOfTimeOut,virtual_time_out,_) -> true % can easily happen when parameters are unbounded
879 ; print_message(time_out_for_node(Id,OpName,TypeOfTimeOut))),
880 (time_out_for_node(Id,OpName,_) -> true ; assertz(time_out_for_node(Id,OpName,TypeOfTimeOut))).
881 assert_time_out_for_invariant(Id) :- print_message(time_out_for_invariant(Id)),
882 (time_out_for_invariant(Id) -> true ; assertz(time_out_for_invariant(Id))).
883 assert_time_out_for_assertions(Id) :- print_message(time_out_for_assertions(Id)),
884 (time_out_for_assertions(Id) -> true ; assertz(time_out_for_assertions(Id))).
885
886 max_reached_or_timeout_for_node(Id) :-
887 (max_reached_for_node(Id) ; time_out_for_node(Id,_,_)).
888 /* ---------------------- */
889 /* state space saving */
890 /* ---------------------- */
891
892 :- dynamic state_space_version_in_file/1. %
893 state_space_version(1).
894
895 check_state_space_version :- state_space_version(V),
896 (state_space_version_in_file(F) -> true ; F=0),
897 (V>F -> add_message(state_space,'Warning: saved state_space may be incompatible with current version: ',F:V) ; true).
898
899 % save all infos of state space (transitions, evaluated invariants, ...)
900 tcltk_save_state_space(File) :-
901 print('% saving full state space to: '), print(File),nl,
902 open(File,write,Stream,[encoding(utf8)]),
903 print_state_space(Stream),
904 close(Stream),
905 print_message(done).
906
907
908 :- use_module(tools_printing, [print_dynamic_fact/2,print_dynamic_pred/4]).
909 print_state_space(Stream) :-
910 state_space_version(V),
911 print_dynamic_fact(Stream,state_space_version_in_file(V)),
912 % TO DO: maybe also save some important preferences, and warn user and/or propose to adapt preferences ?
913 print_dynamic_pred(Stream,state_space,history,1),
914 print_dynamic_pred(Stream,state_space,forward_history,1),
915 print_dynamic_pred(Stream,state_space,op_trace_ids,1),
916 print_dynamic_pred(Stream,state_space,current_state_id,1),
917 print_dynamic_pred(Stream,state_space,current_options,1),
918 print_dynamic_pred(Stream,state_space,packed_visited_expression,2),
919 print_dynamic_pred(Stream,state_space,not_invariant_checked,1),
920 print_dynamic_pred(Stream,state_space,not_interesting,1),
921 print_dynamic_pred(Stream,state_space,max_reached_for_node,1),
922 print_dynamic_pred(Stream,state_space,time_out_for_node,3),
923 print_dynamic_pred(Stream,state_space,time_out_for_invariant,1),
924 print_dynamic_pred(Stream,state_space,time_out_for_assertions,1),
925 print_dynamic_pred(Stream,state_space,id_back_edge,3),
926 print_dynamic_pred(Stream,state_space,use_no_timeout,1),
927 print_dynamic_pred(Stream,state_space,transition,4),
928 print_dynamic_pred(Stream,state_space,transition_info,2),
929 print_dynamic_pred(Stream,state_space,operation_not_yet_covered,1),
930 print_dynamic_pred(Stream,state_space,state_error,3),
931 print_state_space_open_nodes(Stream),
932 print_stored_values(Stream),
933 get_counter(states,X),
934 write_term(Stream,saved_gennum_count(X),[quoted(true)]),write(Stream,'.'),nl(Stream).
935
936 saved_gennum_count(99999).
937
938 /* ---------------------- */
939 /* state space loading */
940 /* ---------------------- */
941
942 tcltk_load_state(File) :- state_space_clean_all,
943 print('Loading: '), print(File),nl,
944 user_consult_without_redefine_warning(File), % this will read in bind_skeleton/2, ..., next_value_id/1
945 check_state_space_version,
946 print('Generating open node info'),nl,
947 transfer_open_node_info,
948 print('Transfer state packing info'),nl,
949 transfer_state_packing_info,
950 print('Recomputing hash index'),nl,
951 recompute_all_hash,
952 (saved_gennum_count(X) -> reset_state_counter(X) ; true),
953 reset_processed_nodes_counter, % TO DO: restore or save it
954 reset_next_state_error_id_counter, % DITTO
955 print('Done'),nl,!.
956 tcltk_load_state(File) :-
957 add_error(tcltk_load_state,'Could not load state from file: ',File),
958 state_space_initialise.
959
960 :- dynamic not_all_z_saved/1, not_all_transitions_added_saved/1.
961 :- dynamic bind_skeleton/2, stored_value/2, stored_value_hash_to_id/2, next_value_id/1.
962
963 % transfer facts read into state_space into other modules:
964 transfer_open_node_info :- retract(not_all_z_saved(X)), %print(not_all_z(X)),nl,
965 assert_not_all_z(X),fail.
966 transfer_open_node_info :- retract(not_all_transitions_added_saved(X)),
967 assert_not_all_transitions_added(X),fail.
968 transfer_open_node_info.
969 % now for transferring to state_packing module info generated by print_stored_values
970 transfer_state_packing_info :- retract(bind_skeleton(X,Y)), %print(skel(X)),nl,
971 assertz(state_packing:bind_skeleton(X,Y)),fail.
972 transfer_state_packing_info :- retract(stored_value(X,Y)),
973 assertz(state_packing:stored_value(X,Y)),fail.
974 transfer_state_packing_info :- retract(stored_value_hash_to_id(X,Y)),
975 assertz(state_packing:stored_value_hash_to_id(X,Y)),fail.
976 transfer_state_packing_info :- retract(next_value_id(X)),
977 state_packing:set_next_value_id(X),fail.
978 transfer_state_packing_info.
979
980 recompute_all_hash :-
981 retractall(hash_to_id(_,_)),retractall(id_to_marker(_,_)),
982 retractall(hash_to_nauty_id(_,_)),
983 visited_expression(ID,StateTemplate),
984 state_space_exploration_modes:compute_hash(StateTemplate,Hash,Marker),
985 assertz(hash_to_id(Hash,ID)),
986 assertz(id_to_marker(ID,Marker)),
987 fail.
988 recompute_all_hash.
989
990 :- use_module(hashing,[my_term_hash/2]).
991 % generates a hash for the entire state space not depending on the order in which states where added
992 compute_full_state_space_hash(Hash) :-
993 %listing(hash_to_id/2), listing(packed_visited_expression/2),
994 findall(Hash,hash_to_id(Hash,_),ListOfHashCodes),
995 sort(ListOfHashCodes,SortedList),
996 my_term_hash(SortedList,Hash).
997 % TO DO: also provide transition hashes
998
999 :- use_module(tools_meta,[safe_on_exception/3]).
1000 user_consult_without_redefine_warning(File) :-
1001 get_set_optional_prolog_flag(redefine_warnings, Old, off),
1002 get_set_optional_prolog_flag(single_var_warnings, Old2, off),
1003 (safe_on_exception(Exc,
1004 %consult(File), %
1005 load_files([File], [load_type(source),compilation_mode(consult),encoding(utf8)]),
1006 (nl,print('Exception occurred:'),print(Exc),nl,fail))
1007 -> OK=true ; OK=false),
1008 get_set_optional_prolog_flag(redefine_warnings, _, Old),
1009 get_set_optional_prolog_flag(single_var_warnings, _, Old2),
1010 OK=true.
1011
1012 % execute a transition id list from current ID and update animator history,...
1013 execute_id_trace_from_current(OperationIDList) :-
1014 current_state_id(CurID),
1015 get_state_list_from_opids(OperationIDList,CurID,StateIDList,NewCurID),
1016 execute_id_trace_from_current(NewCurID,OperationIDList,StateIDList).
1017
1018 get_state_list_from_opids([],CurID,[],CurID).
1019 get_state_list_from_opids([TransId|TO],CurID,[NextCurID|TS],FinalCurID) :-
1020 transition(CurID,_,TransId,NextCurID),
1021 get_state_list_from_opids(TO,NextCurID,TS,FinalCurID).
1022
1023
1024 % execute_id_trace_from_current(NewCurID,OperationIDList,StateIDList)
1025 execute_id_trace_from_current(ID,OpIDL,StateIDList) :-
1026 current_state_id(CurID),
1027 reverse([CurID|StateIDList],Rev),
1028 Rev = [Dest|TRev],
1029 (Dest==ID -> true ; add_internal_error('Last state of trace differs from new current state id: ',not_eq(Dest,ID))),
1030 retract(history(H)),
1031 update_forward_history(OpIDL), % check if OpIDL conforms to forward history and keep it
1032 append(TRev,H,NewH),
1033 assertz(history(NewH)),
1034 retract(op_trace_ids(OldTrace)),
1035 reverse(OpIDL,NewTrace),
1036 append(NewTrace,OldTrace,Trace),
1037 assertz(op_trace_ids(Trace)),
1038 retractall(current_state_id(_)),
1039 assertz(current_state_id(ID)).
1040 %execute_trace_to_node(OpL,StateIDList). /* <----- BOTTLENECK FOR LONG SEQUENCES */
1041 %generate_trace([],Acc,Acc).
1042 %generate_trace([OpTerm|T],Acc,Res) :-
1043 % translate:translate_event(OpTerm,OpString),
1044 % generate_trace(T,[action(OpString,OpTerm)|Acc],Res).
1045
1046 update_forward_history(TransitionIds) :-
1047 (retract(forward_history(Forward)),
1048 prune_forward_history(TransitionIds,Forward,NewForward)
1049 -> assert(forward_history(NewForward))
1050 ; true).
1051 % try and prune forward history if it matches operation trace
1052 prune_forward_history([],ForwardHistory,ForwardHistory).
1053 prune_forward_history([TransID|T],[forward(_,TransID)|TF],Res) :-
1054 prune_forward_history(T,TF,Res).
1055
1056 try_set_trace_by_transition_ids(TransIds) :-
1057 (set_trace_by_transition_ids(TransIds) -> true
1058 ; add_internal_error('Call failed:',set_trace_by_transition_ids(TransIds))).
1059
1060 set_trace_by_transition_ids(TransitionIds) :-
1061 extract_history_from_transition_ids(TransitionIds,root,[],[],Last,History,OpTrace),
1062 %visited_expression(Last,LastState,LastCond),
1063 retractall(history(_)),
1064 retractall(forward_history(_)), % TODO: we could try and recover a new forward history if transition ids match current history^forward history
1065 update_forward_history(TransitionIds),
1066 retractall(current_state_id(_)),
1067 retractall(op_trace_ids(_)),
1068 assertz(history(History)),
1069 assertz(op_trace_ids(OpTrace)),
1070 assertz(current_state_id(Last)).
1071
1072
1073 extract_history_from_transition_ids([],CurrentState,History,Trace,CurrentState,History,Trace).
1074 extract_history_from_transition_ids([TransId|Rest],CurrentState,AccHist,AccTrace,Last,History,Trace) :-
1075 transition(CurrentState,_,TransId,DestState),!,
1076 extract_history_from_transition_ids(Rest,DestState,[CurrentState|AccHist],
1077 [TransId|AccTrace],Last,History,Trace).
1078 extract_history_from_transition_ids([skip|Rest],CurrentState,AccHist,AccTrace,Last,History,Trace) :- !,
1079 extract_history_from_transition_ids(Rest,CurrentState,AccHist,AccTrace,Last,History,Trace).
1080 extract_history_from_transition_ids([TransId|_],CurrentState,_,_,_,_,_Trace) :-
1081 add_error(state_space,'Could not execute transition id: ', TransId:from(CurrentState)),fail.
1082
1083 % extend trace from current state
1084 extend_trace_by_transition_ids(TransitionIds) :-
1085 current_state_id(CurID),
1086 history(OldH), op_trace_ids(OldOT),
1087 extract_history_from_transition_ids(TransitionIds,CurID,OldH,OldOT,Last,History,OpTrace),
1088 retractall(history(_)), retractall(forward_history(_)),
1089 retractall(current_state_id(_)),
1090 retractall(op_trace_ids(_)),
1091 assertz(history(History)),
1092 assertz(op_trace_ids(OpTrace)),
1093 assertz(current_state_id(Last)).
1094
1095 /* --------------------------------- */
1096 :- dynamic max_nr_of_new_nodes/1.
1097
1098 % negative number or non-number signifies no limit
1099 set_max_nr_of_new_impl_trans_nodes(MaxNrOfNewNodes) :-
1100 retractall(max_nr_of_new_nodes(_)),
1101 (number(MaxNrOfNewNodes), MaxNrOfNewNodes>=0
1102 -> assertz(max_nr_of_new_nodes(MaxNrOfNewNodes))
1103 ; true). % no need to store limit; we will explore as much as needed
1104
1105 get_max_nr_of_new_impl_trans_nodes(MaxNrOfNewNodes) :-
1106 (max_nr_of_new_nodes(Max) -> MaxNrOfNewNodes=Max; MaxNrOfNewNodes = 0).
1107
1108 % used e.g., in refinement or ltl checker
1109 impl_trans_term(From,ActionAsTerm,TransID,To) :-
1110 compute_transitions_if_necessary_saved(From),
1111 transition(From,ActionAsTerm,TransID,To).
1112 impl_trans_term(From,ActionAsTerm,To) :-
1113 compute_transitions_if_necessary_saved(From),
1114 transition(From,ActionAsTerm,_TID,To).
1115
1116 % a variation also giving the transition id:
1117 impl_trans_id(From,ActionAsTerm,TransitionID,To) :-
1118 compute_transitions_if_necessary_saved(From),
1119 transition(From,ActionAsTerm,TransitionID,To).
1120
1121 impl_trans_term_all(From,Ops) :-
1122 compute_transitions_if_necessary_saved(From),
1123 findall(op(Id,ActionAsTerm,To),
1124 transition(From,ActionAsTerm,Id,To),
1125 Ops).
1126
1127 % true if e.g., a time-out occurred during computation of all transitions
1128 impl_trans_not_complete(From) :- max_reached_or_timeout_for_node(From).
1129
1130 compute_transitions_if_necessary_saved(From) :-
1131 catch(
1132 compute_transitions_if_necessary(From),
1133 error(forced_interrupt_error('User has interrupted the current execution'),_),
1134 user_interrupts:process_interrupted_error_message).
1135
1136 :- use_module(tcltk_interface,[compute_all_transitions_if_necessary/2]).
1137 compute_transitions_if_necessary(From) :-
1138 not_all_transitions_added(From),!,
1139 decrease_max_nr_of_new_nodes(From),
1140 compute_all_transitions_if_necessary(From,false).
1141 compute_transitions_if_necessary(_From).
1142
1143 decrease_max_nr_of_new_nodes(ID) :-
1144 retract(max_nr_of_new_nodes(Max)),!,
1145 ( Max>0 ->
1146 NewMax is Max-1,
1147 assertz(max_nr_of_new_nodes(NewMax))
1148 ; Max=0 -> NM is -1,
1149 assertz(max_nr_of_new_nodes(NM)),
1150 add_warning(state_space,'Maximum number of new nodes reached for CTL/LTL/refinement check, node id = ',ID),
1151 fail
1152 ; % negative number: re-assert and fail
1153 assertz(max_nr_of_new_nodes(Max)),
1154 fail).
1155 decrease_max_nr_of_new_nodes(_). % no limit stored; just proceed
1156
1157 % will be called from TCL/TK side
1158 max_nr_of_new_nodes_limit_not_reached :-
1159 max_nr_of_new_nodes(N),N>0.
1160
1161 :- use_module(specfile,[b_or_z_mode/0, csp_mode/0, csp_with_bz_mode/0]).
1162 retract_open_node(NodeID) :- retract_open_node_and_update_processed_nodes(NodeID),
1163 (b_or_z_mode -> assertz(not_invariant_checked(NodeID)) ; true).
1164
1165 reset_processed_nodes_counter :- reset_counter(processed_nodes).
1166 %reset_processed_nodes_counter(Nr) :- set_counter(processed_nodes,Nr).
1167
1168 retract_open_node_and_update_processed_nodes(NodeID) :-
1169 retract_open_node_direct(NodeID),
1170 inc_processed.
1171
1172 inc_processed :-
1173 inc_counter(processed_nodes).
1174
1175 pop_id_from_front(ID) :- pop_id_from_front_direct(ID), inc_processed.
1176 pop_id_from_end(ID) :- pop_id_from_end_direct(ID), inc_processed.
1177 pop_id_oldest(ID) :- pop_id_oldest_direct(ID), inc_processed.
1178
1179
1180
1181 /* --------------------------------- */
1182
1183 % find initialised states; very similar to is_initial_state_id/1
1184 % but is used by ltl/ctl/sap
1185 % TO DO: merge these two variations of the same concept
1186
1187 :- use_module(specfile,[animation_mode/1]).
1188
1189 find_initialised_states(Init) :-
1190 animation_mode(Mode),
1191 ( init_states_mode_cst_init(Mode) ->
1192 findall(I,find_init1(root,I,_),Init)
1193 ; init_states_mode_one_step(Mode) ->
1194 next_states_from_root(Init)
1195 ;
1196 fail).
1197
1198 % find trace to some initialised state
1199 find_trace_to_initial_state(Target,Trace) :- animation_mode(Mode),
1200 find_aux(Mode,Target,Trace).
1201 find_aux(Mode,Target,[root,Target]) :-
1202 init_states_mode_one_step(Mode).
1203 find_aux(Mode,Target,[root|Trace]) :-
1204 init_states_mode_cst_init(Mode),
1205 find_init1(root,Target,Trace).
1206
1207
1208 init_states_mode_cst_init(b).
1209 init_states_mode_cst_init(z).
1210 init_states_mode_cst_init(csp_and_b).
1211
1212 init_states_mode_one_step(csp).
1213 init_states_mode_one_step(cspm).
1214 init_states_mode_one_step(xtl).
1215 %init_states_mode_one_step(promela).
1216
1217 next_states_from_root(States) :-
1218 impl_trans_term_all(root,Ops),
1219 findall(S, member(op(_Id,_,S),Ops), States).
1220
1221 find_init1(Start,Init,Trace) :- Start==Init,!,Trace=[]. % usually called with Start=Init=root
1222 find_init1(Start,Init,[State|Rest]) :-
1223 impl_trans_term(Start,O,State),
1224 find_init2(O,State,Init,Rest).
1225 find_init2(O,Init,Init,[]) :-
1226 has_functor_and_maybe_tau(O,'$initialise_machine').
1227 find_init2(O,State,Init,Path) :-
1228 has_functor_and_maybe_tau(O,F),
1229 (F='$setup_constants' ; F='$partial_setup_constants'),
1230 find_init1(State,Init,Path).
1231 find_init2(start_cspm_MAIN,State,Init,Path) :-
1232 find_init1(State,Init,Path).
1233 find_init2(start_cspm(_Proc),State,Init,Path) :-
1234 find_init1(State,Init,Path).
1235
1236 % has_functor_and_maybe_tau(Term,Functor)
1237 % checks if Term has the form "Functor(...)" or "tau(Functor(...))"
1238 % this is used for CSP||B specification where the initialisation is wrapped with
1239 % in a tau operator
1240 has_functor_and_maybe_tau(tau(Term),Functor) :-
1241 has_functor_and_maybe_tau(Term,Functor),!.
1242 has_functor_and_maybe_tau(Term,Functor) :-
1243 functor(Term,Functor,_).
1244
1245 % compute how far the state is from the root node using back_edge markers (if available)
1246 try_compute_depth_of_state_id(root,R) :- !, R=0.
1247 try_compute_depth_of_state_id(Node,Depth) :- id_back_edge(Node,Depth,_Back).
1248
1249 % optional registering of back_edges: to quickly find trace from root and to computed depth/diameter
1250 register_back_edge(ID,FromID) :-
1251 try_compute_depth_of_state_id(FromID,D),!,
1252 D1 is D+1,
1253 assertz(id_back_edge(ID,D1,FromID)).
1254 register_back_edge(ID,FromID) :- debug_println(9,cannot_store_back_edge(ID,FromID)).
1255
1256 /* --------------------------------- */
1257
1258 %
1259 % Code to compute equivalence classes
1260 % using the standard DFA minimization algorithm
1261
1262 :- dynamic equivalent/2.
1263 % state_space:compute_equivalence_classes
1264 :- public compute_equivalence_classes/0.
1265
1266 compute_equivalence_classes :- init_equi,
1267 split_equivalence_classes,nl,
1268 print_equi.
1269
1270 print_equi :- state_space:equivalent(A,B), visited_expression(A,State),
1271 visited_expression(B,StateB),
1272 nl,
1273 print(A), print(' : '), print(State),nl,
1274 print(B), print(' : '), print(StateB),nl,fail.
1275 print_equi.
1276
1277 init_equi :- retractall(equivalent(_,_)),
1278 packed_visited_expression(ID,_State),
1279 \+ not_all_transitions_added(ID),
1280 findall(Action,transition(ID,Action,_,_),List),
1281 packed_visited_expression(ID2,_S2), ID2 @> ID,
1282 \+ not_all_transitions_added(ID2),
1283 findall(Action,transition(ID2,Action,_,_),List),
1284 assertz(equivalent(ID,ID2)), % they have the same signature
1285 %print(equivalent(ID,ID2)),nl,
1286 fail.
1287 init_equi :- print(finished_initialising),nl.
1288
1289 split_equivalence_classes :- retractall(echange),
1290 equivalent(ID1,ID2),
1291 transition(ID1,A,_,Dest1),
1292 transition(ID2,A,_,Dest2),
1293 \+ check_equi(Dest1,Dest2),
1294 retract(equivalent(ID1,ID2)), % splitting class
1295 % print(diff(ID1,ID2, A, Dest1, Dest2)),nl,
1296 assert_echange,
1297 fail.
1298 split_equivalence_classes :- echange -> split_equivalence_classes ; true.
1299
1300 :- dynamic echange/0.
1301 assert_echange :- echange -> true ; assertz(echange),print('.'),flush_output.
1302
1303 check_equi(A,B) :- A=B -> true ; A @<B -> equivalent(A,B) ; equivalent(B,A).
1304
1305 /*
1306 % benchmark how much time it takes to copy the state space state_space:bench_state_space.
1307 bench_state_space :-
1308 statistics(walltime,_),
1309 (state_space:packed_visited_expression(ID,S), assertz(pve(ID,S)),fail ; true),
1310 statistics(walltime,[_,Delta]), format('Time to copy packed_visited_expression: ~w ms~n',[Delta]),
1311 (state_space:transition(A,B,C,D), assertz(tr(A,B,C,D)),fail ; true),
1312 statistics(walltime,[_,Delta2]), format('Time to copy transition: ~w ms~n',[Delta2]),
1313 (state_packing:stored_value(A,B), assertz(sv(A,B)),fail ; true),
1314 (state_packing:stored_value_hash_to_id(A,B), assertz(svhi(A,B)),fail ; true),
1315 statistics(walltime,[_,Delta3]), format('Time to copy stored_value: ~w ms~n',[Delta3]).
1316 */
1317
1318 :- public portray_state_space/0.
1319 portray_state_space :- packed_visited_expression(ID,S), functor(S,F,N),
1320 format('State ~w : ~w/~w~n',[ID,F,N]), fail.
1321 portray_state_space :- transition(ID,Action,TransID,DestID),
1322 format(' ~w: ~w -- ~w --> ~w~n',[TransID,ID,Action,DestID]),fail.
1323 portray_state_space.
1324
1325
1326 portray_history :- op_trace_ids(List), length(List,Len),
1327 format('History of length ~w:~n',[Len]), reverse(List,His),
1328 portray_op_trace_ids(His,1,root).
1329 portray_op_trace_ids([],_,_CurrentState) :- !.
1330 portray_op_trace_ids([TransId|Rest],Step,CurrentState) :-
1331 compute_op_string(TransId,CurrentState,200,_OpTerm,OpString,DestState),!,
1332 format('~w: ~w -- ~w --> ~w : ~w~n',[Step,CurrentState,TransId,DestState,OpString]),
1333 S1 is Step+1,
1334 portray_op_trace_ids(Rest,S1,DestState).
1335 portray_op_trace_ids(L,Step,CurrentState) :-
1336 format('### Cannot print history from step ~w at state ~w:~n~w~n',[Step,CurrentState,L]).
1337
1338 bench_state_space :- statistics(walltime,[W1,_]),
1339 (packed_visited_expression(_,_), fail ; true),
1340 statistics(walltime,[W2,_]), T1 is W2-W1,
1341 format('Time to inspect all states: ~w ms walltime~n',[T1]),
1342 (visited_expression(_,_), fail ; true),
1343 statistics(walltime,[W3,_]), T2 is W3-W2,
1344 format('Time to inspect and unpack all states: ~w ms walltime~n',[T2]),
1345 (transition(_,_,_,_), fail ; true),
1346 statistics(walltime,[W4,_]), T3 is W4-W3,
1347 format('Time to inspect all transitions: ~w ms walltime~n',[T3]),
1348 (visited_expression(_,E), my_term_hash(E,_), fail ; true),
1349 statistics(walltime,[W5,_]), T4 is W5-W4,
1350 format('Time to inspect, unpack and hash all states: ~w ms walltime~n',[T4]).
1351
1352 % ----------------------------
1353 % COUNTER EXAMPLE MANAGEMENT
1354
1355 % store counter example nodes and transition ids; used by LTL model checking for example
1356
1357
1358 :- dynamic counterexample_node/1.
1359 :- dynamic counterexample_op/1.
1360
1361 add_counterexample_node(NodeID) :- assertz(counterexample_node(NodeID)).
1362 add_counterexample_op(TransID) :-
1363 (counterexample_op(TransID) -> true ; assertz(counterexample_op(TransID))).
1364
1365
1366 reset_counterexample :-
1367 retractall(counterexample_node(_)),
1368 retractall(counterexample_op(_)).
1369
1370 :- register_event_listener(play_counterexample,reset_counterexample,
1371 'Reset marked nodes from previous counterexamples.').
1372
1373 set_counterexample_by_transition_ids(TransIds) :-
1374 set_trace_by_transition_ids(TransIds),
1375 maplist(add_counterexample_op,TransIds),
1376 extract_history_from_transition_ids(TransIds,root,[],[],_Last,History,_OpTrace),
1377 maplist(add_counterexample_node,History).