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