1 % (c) 2021-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(b_intelligent_trace_replay, [get_transition_details/6,
6 perform_single_replay_step/5,
7 replay_json_trace_file/2, replay_json_trace_file/5,
8 read_json_trace_file/3,
9 tcltk_replay_json_trace_file/3,
10 get_replay_table/4,
11 replay_prolog_trace_file/1,
12
13 % API for interactive JSON trace replay:
14 load_json_trace_file_for_ireplay/1,
15 tk_get_stored_json_trace_description/1,
16 get_stored_json_replay_steps/1,
17 get_ireplay_status/3,
18 replay_of_current_step_is_possible/5,
19 replay_of_current_step_is_possible_with_trans/5, replay_of_current_step_is_possible_with_trans/6,
20 replay_current_step/1,
21 replay_current_step_with_trans/6,
22 ireplay_fast_forward/1,
23 ireplay_fast_forward_with_trans/6, ireplay_fast_forward_with_trans/7,
24 skip_current_ireplay_step/1]).
25
26 :- use_module(module_information,[module_info/2]).
27 :- module_info(group,testing).
28 :- module_info(description,'Replay saved (JSON) traces in a flexible way.').
29 % successor to b_trace_checking
30
31 :- meta_predicate exclude_and_collect_errors(2,-,-,-,-).
32
33 :- use_module(state_space,[current_state_id/1, transition/4, visited_expression/2]). % transition(CurID,Term,TransId,DestID)
34
35 :- use_module(tools_strings,[ajoin/2,ajoin_with_sep/3]).
36 :- use_module(specfile,[extract_variables_from_state/2, get_state_for_b_formula/3, b_or_z_mode/0, xtl_mode/0,
37 get_local_states_for_operation_transition/4, create_local_store_for_operation/4,
38 get_operation_name/2, expand_const_and_vars_to_full_store/2]).
39 :- use_module(error_manager).
40 :- use_module(debug).
41 :- use_module(probsrc(state_space), [extend_trace_by_transition_ids/1]).
42 :- use_module(tools_json).
43
44 % A single step is a list of informations about the step
45 % name/OperationName
46 % paras/List of =(Name,Value)
47
48 % TO DO: for match_spec use mutable counter for number of matches instead of used parameter
49
50 :- use_module(tcltk_interface,[compute_all_transitions_if_necessary/2]).
51
52 :- use_module(probsrc(bmachine),[b_get_operation_non_det_modifies/2, b_is_operation_name/1]).
53 :- use_module(probsrc(bsyntaxtree), [def_get_texpr_id/2, get_texpr_ids/2, get_texpr_id/2, get_texpr_type/2]).
54 :- use_module(probsrc(tools_matching), [get_possible_fuzzy_matches_completions_and_inner_msg/3]).
55 :- use_module(probsrc(b_interpreter),[b_test_boolean_expression_for_ground_state/5]).
56
57 perform_single_replay_step(FromID,TransID,DestID,MatchSpec,TransSpec) :-
58 %format('* FROM: ~w ',[FromID]),portray_match_spec(MatchSpec),nl,
59 (match_spec_has_optimize_field(MatchSpec)
60 -> findall(sol(MM,TID,DID),
61 perform_single_replay_step_statespace(FromID,TID,DID,MatchSpec,TransSpec,MM),
62 Sols),
63 mark_match_spec_as_used(MatchSpec),
64 length(Sols,NrSols),
65 min_member(sol(Mismatches,TransID,DestID),Sols),
66 debug_format(19,'Min. nr of mismatches found ~w among ~w candidate steps (starting from state ~w). ~n',[Mismatches,NrSols,FromID])
67 ; % just find first solution:
68 perform_single_replay_step_statespace(FromID,TransID,DestID,MatchSpec,TransSpec,_)
69 ).
70 perform_single_replay_step(FromID,TransID,DestID,MatchSpec,TransSpec) :-
71 perform_single_replay_step_by_pred(FromID,TransID,DestID,MatchSpec,TransSpec).
72
73
74
75
76 % Assumption: ParaStore and ResultStore are sorted
77 % returns the number of mismatches for those Keys marked as optimize
78 perform_single_replay_step_statespace(FromID,TransID,DestID,
79 MatchSpec,
80 transition_spec(OpName, _, ParaStore, ResultStore, DestStore, UnchangedVars, Preds, _Postconditions),
81 Mismatches) :-
82 mark_match_spec_as_used(MatchSpec),
83 get_opt_match_spec_val(opname,MatchSpec,OpMatch),
84 compute_all_transitions_if_necessary(FromID,false), % could be made optional
85 (OpMatch==match -> TOpName=OpName ; true),
86 get_sorted_transition_details(FromID,TransID,DestID,TOpName,FullParaStore,FullResultStore),
87 (xtl_mode
88 -> transition(FromID,OpTerm,TransID,DestID),
89 ground(OpTerm) % if not ground: fail here and try to instantiate non-ground params by replay by predicate
90 ; true),
91 (TOpName=OpName -> MM0 = 0 ; MM0=1, assert_mismatch(OpMatch)),
92 count_store_mismatches(FullParaStore,ParaStore,paras,MatchSpec,MM0,MM1), % check if parameters match
93 count_store_mismatches(FullResultStore,ResultStore,results,MatchSpec,MM1,MM2), % check if operation return values match
94 get_unchanged_store(FromID,UnchangedVars,UnchangedStore),
95 (DestStore=[], UnchangedStore=[]
96 -> MM6=MM2
97 ; % check if variables in destination state match
98 visited_expression(DestID,DestState),
99 get_dest_store(DestState,FullDestStore),
100 count_store_mismatches(FullDestStore,DestStore,dest,MatchSpec,MM2,MM3),
101 count_store_mismatches(FullDestStore,UnchangedStore,unchanged,MatchSpec,MM3,MM4),
102 (b_or_z_mode, get_match_spec_val(nondet_vars,MatchSpec,_)
103 -> b_get_op_non_det_modifies(OpName,NonDetModifies),
104 include(b_intelligent_trace_replay:bind_id_is_element_of(NonDetModifies),DestStore,D1),
105 count_store_mismatches(FullDestStore,D1,nondet_vars,MatchSpec,MM4,MM5),
106 include(b_intelligent_trace_replay:bind_id_is_element_of(NonDetModifies),UnchangedStore,D2),
107 count_store_mismatches(FullDestStore,D2,nondet_vars,MatchSpec,MM5,MM6)
108 ; MM6=MM4
109 )
110 ),
111 Mismatches = MM6,
112 (Preds=[] -> true
113 ; get_match_spec_val(preds,MatchSpec,match)
114 -> bsyntaxtree:conjunct_predicates(Preds,Pred),
115 debug_format(9,'Testing preds in destination state ~w after ~w~n',[DestID,FromID]),
116 % TODO: insert_before_substitution_variables for $0 vars; check that it is consistent with Tcl/Tk and ProB2-UI
117 % maybe use annotate_becomes_such_vars or find_used_primed_ids
118 append(FullResultStore,FullParaStore,LocalStore),
119 % evaluate in the full destination state (with constants); FullDestStore is only computed if the trace step
120 % contains destination or unchanged variables and only contains the variables
121 get_dest_store_for_preds(DestID,PredDestStore),
122 b_test_boolean_expression_for_ground_state(Pred,LocalStore,PredDestStore,'trace replay', OpName)
123 ; true
124 ).
125
126 node_not_fully_explored(FromID,OpName) :-
127 (max_reached_for_node(FromID)
128 ; not_all_transitions_added(FromID)
129 ; not_interesting(FromID)
130 ; time_out_for_node(FromID,OpName,_)).
131
132 :- use_module(probsrc(preferences),[get_time_out_preference_with_factor/2]).
133 % lookup in state space failed; try perform by predicate
134 % Note: does not use optimize keys (yet), only match keys
135 perform_single_replay_step_by_pred(FromID,TransID,DestID,
136 MatchSpec,
137 transition_spec(OpName, _, ParaStore, ResultStore, DestStore, UnchangedVars, Preds,
138 _Postconditions)) :-
139 nonvar(OpName), % we currently cannot execute by predicate without knowing OpName
140 ((node_not_fully_explored(FromID,OpName) ; xtl_mode) -> true % TODO: improve max_reached_for_node for xtl_mode
141 ; debug_format(19,'Node ~w fully explored for ~w; no use in attempting execute by predicate~n',[FromID,OpName]),
142 fail
143 ),
144 mark_match_spec_as_used(MatchSpec),
145 !,
146 (ParaStore \= [], % check parameters of operation
147 get_match_spec_val(paras,MatchSpec,match)
148 -> b_get_operation_typed_paras(OpName,Paras1),
149 (xtl_mode, Paras1=[] % XTL special case: no custom param names found; use default from ParaStore: para1, para2, ...
150 -> findall(b(identifier(Para),string,[]),(member(B,ParaStore),b_intelligent_trace_replay:is_bind(B,Para,_)),Paras2)
151 ; Paras2=Paras1),
152 generate_predicates_from_store(operation_parameters,Paras2,ParaStore,ParaPreds)
153 ; ParaPreds = []),
154 (ResultStore \= [], % check return values of operation
155 get_match_spec_val(results,MatchSpec,match)
156 -> b_get_operation_typed_results(OpName,Results),
157 generate_predicates_from_store(operation_results,Results,ResultStore,ResultPreds)
158 ; ResultPreds = []),
159 get_machine_identifiers(OpName,TVars),
160 (DestStore = [] -> DestPreds=[]
161 ; get_match_spec_val(dest,MatchSpec,match)
162 -> generate_predicates_from_store(dest_variables,TVars,DestStore,DestPreds)
163 ; get_match_spec_val(nondet_vars,MatchSpec,match)
164 -> b_get_op_non_det_modifies(OpName,NonDetModifies),
165 include(b_intelligent_trace_replay:id_is_element_of(NonDetModifies),TVars,NDVars),
166 generate_predicates_from_store(non_det_vars,NDVars,DestStore,DestPreds)
167 ; DestPreds=[]
168 ),
169 get_unchanged_store(FromID,UnchangedVars,UnchangedStore),
170 (UnchangedStore = [] -> UnchangedPreds=[]
171 ; get_match_spec_val(unchanged,MatchSpec,match) ->
172 generate_predicates_from_store(unchanged_vars,TVars,UnchangedStore,UnchangedPreds)
173 ; get_match_spec_val(nondet_vars,MatchSpec,match) ->
174 include(b_intelligent_trace_replay:id_is_element_of(NonDetModifies),TVars,NDVars),
175 generate_predicates_from_store(non_det_vars,NDVars,UnchangedStore,UnchangedPreds)
176 ; UnchangedPreds=[]
177 ),
178 (get_match_spec_val(preds,MatchSpec,match) -> AddPreds=Preds ; AddPreds=[]),
179 append([ParaPreds,ResultPreds,DestPreds,UnchangedPreds,AddPreds],AllPreds),
180 conjunct_predicates(AllPreds,Pred),
181 (debug_mode(off) -> true
182 ; format('Trying to execute ~w in state ~w by predicate: ',[OpName,FromID]),
183 translate:print_bexpr(Pred),nl,flush_output),
184 get_time_out_preference_with_factor(5,TO), % TODO: store this in meta JSON info or options
185 safe_time_out(tcltk_interface:tcltk_add_user_executed_operation_typed(OpName,FromID,_,Pred,TransID,DestID),
186 TO, TimeOutRes),
187 (TimeOutRes = time_out
188 -> format_with_colour(user_output,[orange],'==> Timeout when executing ~w by predicate in state ~w~n',[OpName,FromID]),fail
189 ; true),
190 (xtl_mode
191 -> % In XTL mode we cannot describe the dest state using the DestPreds from above because 'xtl_state' is not a valid identifier.
192 % Preliminary solution: force a precise state match for dest/match as in perform_single_replay_step_statespace.
193 visited_expression(DestID,DestState),
194 get_dest_store(DestState,FullDestStore),
195 count_store_mismatches(FullDestStore,DestStore,dest,MatchSpec,_,_) % fails if there is a mismatch for dest/match
196 ; true).
197
198 get_unchanged_store(_,[],UnchangedStore) :- !, UnchangedStore=[].
199 get_unchanged_store(FromID,UnchangedVars,UnchangedStore) :-
200 % copy old values to UnchangedStore
201 visited_expression(FromID,FromState),
202 extract_variables_from_state(FromState,FullFromStore),
203 sort(FullFromStore,SortedStore),
204 % TODO: generate warning when unchanged variable does not exist?
205 include(b_intelligent_trace_replay:bind_id_is_element_of(UnchangedVars),SortedStore,UnchangedStore).
206
207 :- use_module(library(codesio),[write_term_to_codes/3]).
208 generate_predicate_from_bind(Kind,TypedIDs,json_bind(ID,Val,Type,Pos),b(Res,pred,[])) :-
209 (member(b(identifier(ID),ExpectedType,_),TypedIDs) ->
210 (unify_types_strict(ExpectedType,Type)
211 -> TID = b(identifier(ID),ExpectedType,[]),
212 (xtl_mode
213 -> (write_term_to_codes(Val,ValC,[quoted(true),ignore_ops(true)]),
214 atom_codes(ValA,ValC),
215 TVal = b(external_function_call('STRING_TO_TERM',[b(string(ValA),string,[])]),ExpectedType,[]))
216 ; TVal = b(value(Val),ExpectedType,[])),
217 Res = equal(TID,TVal)
218 ; pretty_type(ExpectedType,ETS), pretty_type(Type,TS), write(clash(Kind,ID,ETS,TS)),nl,
219 % error should probably be caught earlier:
220 add_warning(b_intelligent_trace_replay,'Ignoring value for stored identifier due to type clash: ',ID,Pos),
221 Res = truth
222 )
223 ; % the identifier is not in the list and should be ignored here; sanity checks are made somewhere else
224 Res = truth
225 ).
226 generate_predicate_from_bind(Kind,TypedIDs,bind(ID,Val),R) :- % bind without type infos, e.g., from unchanged store
227 generate_predicate_from_bind(Kind,TypedIDs,json_bind(ID,Val,any,unknown),R).
228
229 generate_predicates_from_store(Kind,TVars,DestStore,DestPreds) :-
230 maplist(b_intelligent_trace_replay:generate_predicate_from_bind(Kind,TVars),DestStore,DestPreds).
231
232 get_machine_identifiers(_,[]) :- \+ b_or_z_mode, !.
233 get_machine_identifiers(Op,TConsts) :- is_setup_constants_op(Op), !, b_get_machine_constants(TConsts).
234 get_machine_identifiers(_,TVars) :- b_get_machine_variables(TVars).
235
236 is_setup_constants_op('$setup_constants').
237 is_setup_constants_op('$partial_setup_constants').
238
239 b_get_op_non_det_modifies(_,[]) :- \+ b_or_z_mode, !.
240 b_get_op_non_det_modifies(Op,NonDetModifies) :- is_setup_constants_op(Op),
241 !,% return all constants as non-det modifies
242 b_get_machine_constants(TConsts),get_texpr_ids(TConsts,ND),
243 sort(ND,NonDetModifies).
244 b_get_op_non_det_modifies(OpName,NonDetModifies) :- b_get_operation_non_det_modifies(OpName,NonDetModifies).
245
246 fix_operation_name(OpName,OpName2) :- \+ b_is_operation_name(OpName),
247 fix_operation_name2(OpName,OpName2).
248 fix_operation_name2('SETUP_CONSTANTS','$setup_constants').
249 fix_operation_name2('INITIALISATION','$initialise_machine').
250 % TODO: maybe provide more automatic fixes, list of automatic re-names when parameters stay identical,...
251
252 % wrappers to deal with a few special transitions; TO DO: extend for CSP||B
253 b_get_operation_typed_results('$setup_constants',Results) :- !,
254 Results=[]. % for trace replay we assume setup_constants to have no result variables
255 b_get_operation_typed_results('$initialise_machine',Results) :- !, Results=[]. % ditto
256 b_get_operation_typed_results('$partial_setup_constants',Results) :- !, Results=[]. % ditto
257 b_get_operation_typed_results(OpName,Results) :- b_or_z_mode, !, b_get_machine_operation_typed_results(OpName,Results).
258 b_get_operation_typed_results(_,[]).
259
260 b_get_operation_typed_paras('$setup_constants',Paras) :- !,
261 Paras=[]. % for trace replay we assume setup_constants to have no parameters
262 b_get_operation_typed_paras('$initialise_machine',Paras) :- !, Paras=[]. % ditto
263 b_get_operation_typed_paras('$partial_setup_constants',Paras) :- !, Paras=[]. % ditto
264 b_get_operation_typed_paras(OpName,Paras) :- b_or_z_mode,!,
265 b_get_machine_operation_typed_parameters_for_animation(OpName,Paras).
266 b_get_operation_typed_paras(OpName,Paras) :- xtl_mode,!,
267 xtl_interface:get_xtl_paras_as_identifiers(OpName,Paras).
268 b_get_operation_typed_paras(OpName,[]) :-
269 add_message(replay_json_trace_file,'Not in B mode, cannot obtain parameter info for: ',OpName).
270
271 % -------------------
272
273 % now a version with multiple MatchSpecs to be tried in order
274 % Flag can be used to see how many alternatives were tried
275 flexible_perform_single_replay_step(FromID,TransID,DestID,[MatchSpec1|TMS],TransitionSpec,MName) :-
276 skip_match_spec(FromID,TransitionSpec,MatchSpec1),!,
277 debug_println(9,skipping_redundant_failing_check(MatchSpec1)),
278 flexible_perform_single_replay_step(FromID,TransID,DestID,TMS,TransitionSpec,MName).
279 flexible_perform_single_replay_step(FromID,TransID,DestID,[MatchSpec1|TMS],TransitionSpec,MName) :-
280 if(perform_single_replay_step(FromID,TransID,DestID,MatchSpec1,TransitionSpec),
281 get_match_spec_txt(MatchSpec1,MName),
282 flexible_perform_single_replay_step(FromID,TransID,DestID,TMS,TransitionSpec,MName)
283 ).
284
285 % -------------------
286
287
288 % we only assert mismatches; if a variable remains untouched we matched perfectly
289 assert_mismatch(Var) :- var(Var),!, Var=optimize.
290 assert_mismatch(require_mismatch). % probably not useful; difficult to support by predicate
291 assert_mismatch(optimize).
292
293 precise_match_spec(match_spec(_,precise,KeyVals)) :-
294 KeyVals = [dest/match,opname/match,paras/match,preds/match,results/match,unchanged/match].
295 ignore_dest_match_spec(match_spec(_,params_and_results,KeyVals)) :-
296 KeyVals = [opname/match,paras/match,preds/match,results/match,nondet_vars/match,dest/optimize,unchanged/optimize].
297 %ignore_return_match_spec(match_spec(_,parameters_only,KeyVals)) :-
298 % KeyVals = [opname/match,paras/match,results/optimize,nondet_vars/optimize].
299 opname_optimize_match_spec(match_spec(_,keep_name,KeyVals)) :-
300 KeyVals = [opname/match,paras/optimize,results/optimize,nondet_vars/optimize,dest/optimize,unchanged/optimize].
301
302 % conditions on when to skip certain match_specs
303 % (we assume that the precise_match_spec was tried before)
304 skip_match_spec(root,TS,match_spec(_,params_and_results,_)) :- get_transition_spec_op(TS,'$setup_constants').
305 % for setup_constants: nondet_vars are all constants; so this is equivalent to precise
306 % for initialise_machine: paras are all variables
307 skip_match_spec(_,TS,match_spec(_,MS,_)) :- MS \= precise,
308 get_transition_spec_meta(TS,Meta),
309 % for an unknown operation we only try a precise replay (e.g., if operation just renamed), otherwise we skip it
310 member(unknown_operation/_,Meta).
311 % TODO: skip parameters_only if an operation has not results and no nondet_vars
312
313 match_spec_was_used(match_spec(UsedFlag,_,_)) :- UsedFlag==used.
314 mark_match_spec_as_used(match_spec(used,_,_)).
315
316 get_match_spec_txt(match_spec(_,Name,_),Name).
317 get_match_spec_val(Key,match_spec(_,_,List),Res) :- member(Key/Val,List),!,Res=Val.
318
319 get_opt_match_spec_val(Key,MS,Res) :- get_match_spec_val(Key,MS,Val),!, Res=Val.
320 get_opt_match_spec_val(_,_,optimize).
321
322 % check if it is useful to optimize the mismatches
323 match_spec_has_optimize_field(match_spec(_,_,KeyVals)) :- member(_/optimize,KeyVals).
324
325 :- public valid_match_spec_key/1.
326 valid_match_spec_key(dest).
327 valid_match_spec_key(nondet_vars).
328 valid_match_spec_key(opname).
329 valid_match_spec_key(paras).
330 valid_match_spec_key(results).
331 valid_match_spec_key(unchanged).
332
333 :- public portray_match_spec/1.
334 portray_match_spec(match_spec(UsedFlag,Name,List)) :-
335 (UsedFlag==used -> U=used ; U=not_yet_used),
336 format('~w (~w): ~w~n',[Name,U,List]).
337
338 % -------------------
339
340 % the store used to evaluate predicates of a trace step in the destination state
341 get_dest_store_for_preds(DestID,Store) :-
342 visited_expression(DestID,DestState),
343 (b_or_z_mode -> expand_const_and_vars_to_full_store(DestState,Store) ; get_dest_store(DestState,Store)).
344
345 get_dest_store(concrete_constants(C),SC) :- !, sort(C,SC).
346 get_dest_store(Store,Vars) :- b_or_z_mode,!, extract_variables_from_state(Store,Vars).
347 get_dest_store(State,XTLState) :- xtl_mode, !, XTLState = [bind(xtl_state,State)]. % special identifier xtl_state only exists in JSON traces
348 get_dest_store(_,[]). % CSP,... has no concept of variables
349
350
351 % count the number of mismatches for a given key and MatchSpec
352 % if MatchSpec requires match (perfect match) it will fail if Mismatches are 0
353 % it accumulates the global number of mismatches in a DCG style accumulator
354 count_store_mismatches(FullStore,PartialStore,Key,MatchSpec,MismatchesIn,MismatchesOut) :-
355 get_match_spec_val(Key,MatchSpec,MatchVal), !,
356 (MatchVal=match
357 -> MismatchesIn=MismatchesOut,
358 count_mismatches(FullStore,Key,PartialStore,0)
359 ; count_mismatches(FullStore,Key,PartialStore,Mismatches),
360 MismatchesOut is MismatchesIn+Mismatches,
361 %print(new_mm(MismatchesOut,Key,MatchVal,Mismatches)),nl,
362 (Mismatches=0 -> true
363 ; assert_mismatch(MatchVal))
364 ).
365 count_store_mismatches(_,_,_Key,_,M,M). % key does not exist; no matching required
366
367 % for maplist, include, exclude:
368 bind_id_is_element_of(Vars,Bind) :- is_bind(Bind,ID,_), member(ID,Vars). % we could use ord_member
369 id_is_element_of(Vars,TID) :- def_get_texpr_id(TID,ID), member(ID,Vars).
370
371 is_bind(bind(ID,Val),ID,Val).
372 is_bind(json_bind(ID,Val,_,_),ID,Val).
373
374 %check_no_mismatches(FullStore,Key,PartialStore) :- count_mismatches(FullStore,Key,PartialStore,0).
375
376 count_mismatches(FullStore,Key,PartialStore,Mismatches) :-
377 count_mismatches_aux(FullStore,Key,PartialStore,0,Mismatches).
378 :- use_module(probsrc(translate), [translate_bvalue_with_limit/3]).
379 % count mismatches in FullStore compared to partial reference store
380 % if result is set to 0, it will fail after first mismatch
381 count_mismatches_aux(_,_,[],Acc,Res) :- !,Res=Acc.
382 count_mismatches_aux([],Key,PartialStore,_,_) :- b_or_z_mode, !,
383 ajoin(['Saved trace step contains unknown bindings for ',Key,': '],Msg),
384 add_error(b_intelligent_trace_replay,Msg,PartialStore),
385 fail.
386 count_mismatches_aux([],[_|_],_,Acc,Res) :- xtl_mode, !, % in XTL mode we can have multiple transitions with the same name => no error, try next for param match
387 inc_mismatches(Acc,Acc1,Res),
388 count_mismatches_aux(_,_,_,Acc1,Res).
389 count_mismatches_aux([Bind1|T],Key,[Bind2|T2],Acc,Res) :-
390 is_bind(Bind1,ID,Val), is_bind(Bind2,ID,Val2),!,
391 (check_value_equal(ID,Val,Val2)
392 -> count_mismatches_aux(T,Key,T2,Acc,Res)
393 ; ((debug_mode(off) ; \+ b_or_z_mode) -> true
394 ; translate_bvalue_with_limit(Val,200,V1), translate_bvalue_with_limit(Val2,200,V2),
395 formatsilent_with_colour(user_output,[red],'==> Mismatch for ~w ~w:~n ~w~n (trace) ~w~n',[Key,ID,V1,V2])
396 %nl,print(Val),nl,nl,print(Val2),nl,nl,
397 ),
398 inc_mismatches(Acc,Acc1,Res),
399 count_mismatches_aux(T,Key,T2,Acc1,Res)
400 ).
401 count_mismatches_aux([_ID|T],Key,PartialStore,Acc,Res) :- count_mismatches_aux(T,Key,PartialStore,Acc,Res).
402
403 inc_mismatches(X,_,Res) :- number(Res),X>Res,!,fail. % we will never reach Res; could be 0 for perfect match
404 inc_mismatches(Acc,Acc1,_) :- Acc1 is Acc+1.
405
406 % check if saved value and actual value is identical
407 :- use_module(kernel_objects,[equal_object/3]).
408 check_value_equal(ID,Val1,Val2) :-
409 temporary_set_preference(allow_enumeration_of_infinite_types,true,OldValueOfPref),
410 call_cleanup(check_value_equal_aux(ID,Val1,Val2),
411 reset_temporary_preference(allow_enumeration_of_infinite_types,OldValueOfPref)).
412
413 % what if trace was saved with different SYMBOLIC pref value?
414 :- use_module(b_ast_cleanup, [clean_up/3]).
415 :- use_module(custom_explicit_sets, [same_closure/2]).
416 :- use_module(debug, [debug_mode/1]).
417 check_value_equal_aux(ID,closure(P1,T1,B1),C2) :- C2 = closure(P2,T2,B2),
418 C1 = closure(P1,T1,B1),
419 !, % we have two symbolic values
420 (same_closure(C1,C2)
421 -> true
422 ; % simple comparison failed, now try and normalize the symbolic values and compare again
423 temporary_set_preference(normalize_ast,true,CHANGE),
424 % normalize_ast_sort_commutative should probably be false, unless we improve the sorting
425 %print(compiling_cur_value(ID)),nl,
426 clean_up(B1,[],B1C),
427 %we could call: b_compiler:b_optimize_closure(closure(P1,T1,B1C),closure(P12,T12,B12),WF),
428 %print(compiling_trace_value(ID)),nl,
429 clean_up(B2,[],B2C),
430 reset_temporary_preference(normalize_ast,CHANGE),
431 (same_closure(closure(P1,T1,B1C),closure(P2,T2,B2C))
432 -> true
433 ; Val=closure(P1,T1,B1C), Val2 = closure(P2,T2,B2C),
434 debug_mode(on),
435 translate_bvalue_with_limit(Val,500,V1), translate_bvalue_with_limit(Val2,500,V2),
436 formatsilent_with_colour(user_output,[red],'==> Symbolic Mismatch for ~w:~n ~w~n (trace) ~w~n',[ID,V1,V2]),
437 % trace, same_closure(closure(P1,T1,B1C),closure(P2,T2,B2C)),
438 fail
439 )
440 ).
441 %check_value_equal_aux(ID,Val1,Val2) :- !, equal_object(Val1,Val2,ID).
442 check_value_equal_aux(ID,Val1,Val2) :-
443 catch(
444 equal_object_time_out(Val1,Val2,ID,2500),
445 enumeration_warning(_A,_B,_C,_D,_E),
446 (format_with_colour(user_output,[red],'==> Enumeration warning when comparing values for ~w~n',[ID]),fail)
447 ).
448 check_value_equal_aux(_ID,Val1,Val2) :- xtl_mode, !,
449 Val1 = Val2.
450
451 :- use_module(tools_meta,[safe_time_out/3]).
452 equal_object_time_out(Val1,Val2,ID,TO) :-
453 safe_time_out(equal_object(Val1,Val2,ID),TO,TimeOutRes),
454 (TimeOutRes = time_out
455 -> format_with_colour(user_output,[red],'==> Timeout when comparing values for ~w~n',[ID]),fail
456 ; true).
457
458
459 :- use_module(specfile,[get_operation_internal_name/2,
460 state_corresponds_to_set_up_constants_only/2]).
461 :- use_module(bmachine,[b_get_machine_operation_parameter_names_for_animation/2,
462 b_get_machine_operation_typed_parameters_for_animation/2,
463 b_get_machine_operation_result_names/2,
464 b_get_machine_operation_typed_results/2,
465 b_get_machine_variables/1, b_get_machine_constants/1,
466 bmachine_is_precompiled/0, b_top_level_operation/1,
467 b_machine_name/1, b_is_variable/1, b_is_variable/2, b_is_constant/1, b_is_constant/2]).
468 :- use_module(probsrc(bsyntaxtree), [conjunct_predicates/2]).
469
470 :- use_module(probsrc(state_space),[max_reached_for_node/1, not_all_transitions_added/1,
471 time_out_for_node/3, not_interesting/1,
472 try_set_trace_by_transition_ids/1]).
473
474 :- use_module(library(lists)).
475
476 % get the information of a B state_space transition in more detailed form
477 % we get a store of parameter values and a store of result values and the operation name
478 get_transition_details(FromID,TransID,DestID,OpName,ParaStore,ResultStore) :-
479 transition(FromID,OperationTerm,TransID,DestID),
480 get_operation_internal_name(OperationTerm,OpName),
481 get_transition_details_aux(OpName,OperationTerm,DestID,ParaStore,ResultStore).
482
483 get_transition_details_aux('$setup_constants',_,DestID,ParaStore,ResultStore) :- !,
484 ResultStore=[],
485 visited_expression(DestID,DestState),
486 state_corresponds_to_set_up_constants_only(DestState,ParaStore).
487 get_transition_details_aux('$initialise_machine',_,DestID,ParaStore,ResultStore) :- !,
488 ResultStore=[],
489 visited_expression(DestID,DestState),
490 extract_variables_from_state(DestState,ParaStore).
491 get_transition_details_aux(OpName,OperationTerm,_,ParaStore,ResultStore) :-
492 get_local_states_for_operation_transition(OpName,OperationTerm,ParaStore,ResultStore).
493
494 get_transition_name(FromID,TransID,OpName) :-
495 transition(FromID,OperationTerm,TransID,_),
496 get_operation_name(OperationTerm,OpName).
497
498
499
500 % a variation where the two stores are sorted according to Prolog order:
501 get_sorted_transition_details(FromID,TransID,DestID,TOpName,SortedPS,SortedRS) :-
502 get_transition_details(FromID,TransID,DestID,TOpName,FullParaStore,FullResultStore),
503 sort(FullParaStore,SortedPS),
504 sort(FullResultStore,SortedRS).
505
506 % ------------------------
507
508 get_transition_spec_op(transition_spec(OpName, _, _, _, _, _, _, _),OpName).
509 get_transition_spec_meta(transition_spec(_, Meta, _, _, _, _, _, _),Meta).
510
511 % get textual representation of transition spec (portray/translate)
512 get_transition_spec_txt(transition_spec(OpName, Meta, ParaStore, ResultStore,
513 _DestStore, _Unchanged, _Preds, _Postconditions),Txt) :-
514 (member(description/Desc,Meta) -> ajoin([Desc,' :: '],DescTxt) ; DescTxt = ''),
515 (nonvar(OpName), OpName \= '' -> OpTxt=OpName
516 ; member(unknown_operation/op(OldOpName,OldParas,OldResults),Meta)
517 -> translate_unknown_operation(OldOpName,OldParas,OldResults,OpTxt)
518 ; OpTxt='?'),
519 (ParaStore = [] -> ParaText1='', ParaText2=''
520 ; ParaText1=' paras: ',
521 maplist(get_bind_txt,ParaStore,Paras),
522 ajoin_with_sep(Paras,',',ParaText2)
523 ),
524 (ResultStore = [] -> ResultText1='', ResultText2=''
525 ; ResultText1=' results: ',
526 maplist(get_bind_txt,ResultStore,Results),
527 ajoin_with_sep(Results,',',ResultText2)
528 ),!,
529 ajoin([DescTxt,OpTxt,ParaText1,ParaText2,ResultText1,ResultText2],Txt).
530 get_transition_spec_txt(TS,'???') :- add_internal_error('Unknown transition spec:',TS).
531
532
533 translate_unknown_operation(OldOpName,OldParas,[],OpTxt) :- !,
534 translate_bindings(OldParas,OPS),
535 append(OPS,[')'],OpParaAtoms),
536 ajoin(['?',OldOpName,'('|OpParaAtoms],OpTxt).
537 translate_unknown_operation(OldOpName,OldParas,OldResults,OpTxt) :-
538 translate_bindings(OldResults,OPR),
539 translate_unknown_operation(OldOpName,OldParas,[],Op1),
540 ajoin([Op1,'-->'|OPR],OpTxt).
541
542 % translate a list of json_bind terms into a list for use with ajoin for pretty-priting
543 translate_bindings([],[]).
544 translate_bindings([json_bind(ID,Val,_Type,_Pos)|TJ],[ID,'=',TVal|TT]) :-
545 translate_bvalue_with_limit(Val,50,TVal),
546 (TJ = [] -> TT=[]
547 ; TT = [','|TT2], translate_bindings(TJ,TT2)).
548
549
550 get_bind_txt(Bind,Txt) :- is_bind(Bind,Id,Val),
551 simple_val(Val), !, % TODO: add parameter for short/long text
552 translate_bvalue_with_limit(Val,100,V1),
553 ajoin([Id,'=',V1],Txt).
554 get_bind_txt(Bind,Id) :- is_bind(Bind,Id,_).
555
556 :- use_module(probsrc(custom_explicit_sets),[singleton_set/2]).
557 simple_val(V) :- var(V),!,fail.
558 simple_val(int(_)).
559 simple_val(term(floating(_))).
560 simple_val(pred_false).
561 simple_val(pred_true).
562 simple_val(string(_)).
563 simple_val(fd(_,_)).
564 simple_val((A,B)) :- simple_val(A), simple_val(B).
565 simple_val([]).
566 simple_val(S) :- singleton_set(S,V), simple_val(V).
567
568
569
570 % perform some static checks on a transition spec: check if operations, parameters, variables exist
571 check_and_adapt_trace_step(transition_spec(OpName, Meta, ParaStore, _, DestStore, UnchangedVars,Preds, Postconditions), Step,
572 transition_spec(OpName, Meta, ParaStore2, [], DestStore2,UnchangedVars2,Preds, Postconditions)) -->
573 {\+ b_or_z_mode},!,
574 exclude_and_collect_errors(unknown_para_binding(OpName,_,'parameter',Step),ParaStore,ParaStore2),
575 exclude_and_collect_errors(unknown_variable_binding(Step,OpName),DestStore,DestStore2),
576 exclude_and_collect_errors(unknown_variable(Step,OpName),UnchangedVars,UnchangedVars2).
577 check_and_adapt_trace_step(transition_spec(OpName, Meta, ParaStore,ResultStore, DestStore, UnchangedVars,Preds, Postconditions),
578 Step,
579 transition_spec(OpName2,Meta2,ParaStore2,ResultStore2,DestStore2,UnchangedVars2,Preds2, Postconditions2)) -->
580 ({fix_operation_name(OpName,OpName2)}
581 -> add_replay_error('Fixed unknown operation name to: ',OpName2) ; {OpName2=OpName}),
582 {b_get_operation_typed_results(OpName2,TOpResults)},
583 {b_get_operation_typed_paras(OpName2,TOpParas)},
584 !,
585 {Meta2=Meta}, % TO DO: include excluded infos
586 {Preds2=Preds}, %TO DO: check if all identifiers bound
587 {Postconditions2=Postconditions}, % TODO Check operation names and predicate identifiers
588 exclude_and_collect_errors(unknown_para_binding(OpName2,TOpParas,'parameter',Step),ParaStore,ParaStore2),
589 exclude_and_collect_errors(unknown_para_binding(OpName2,TOpResults,'result variable',Step),ResultStore,ResultStore2),
590 ({is_setup_constants_op(OpName2)}
591 -> exclude_and_collect_errors(unknown_constant_binding(Step),DestStore,DestStore2),
592 {UnchangedVars2 = []},
593 ({UnchangedVars = []} -> []
594 ; {add_error(b_intelligent_trace_replay,'Illegal unchanged info for SETUP_CONSTANTS',UnchangedVars)}
595 )
596 ; exclude_and_collect_errors(unknown_variable_binding(Step,OpName2),DestStore,DestStore2),
597 exclude_and_collect_errors(unknown_variable(Step,OpName2),UnchangedVars,UnchangedVars2)
598 ).
599 check_and_adapt_trace_step(transition_spec('', Meta, PS, RS, DestStore, UnchangedVars,Preds, Postconditions), Step,
600 transition_spec(_, Meta2, [], [], DestStore2, UnchangedVars2,Preds, Postconditions)) -->
601 % Empty Operation name, treat as wildcard
602 !,
603 {Meta2 = [unknown_operation/op('',PS,RS) | Meta]},
604 ( {PS=[]} -> "" ; add_replay_error('Parameters cannot be checked for unknown operation name: ',PS)),
605 ( {RS=[]} -> "" ; add_replay_error('Result values cannot be checked for unknown operation name: ',PS)),
606 exclude_and_collect_errors(unknown_variable_binding(Step,OpName),DestStore,DestStore2),
607 exclude_and_collect_errors(unknown_variable(Step,OpName),UnchangedVars,UnchangedVars2).
608 check_and_adapt_trace_step(transition_spec(OpName, Meta, PS, RS, DestStore, UnchangedVars,Preds, Postconditions), Step,
609 transition_spec(_, Meta2, [], [], DestStore2, UnchangedVars2,Preds, Postconditions)) -->
610 add_replay_error('Unknown operation: ',OpName), % TODO treat $JUMP
611 {Meta2 = [unknown_operation/op(OpName,PS,RS) | Meta],
612 findall(KOpid,b_top_level_operation(KOpid),Ops),
613 (get_possible_fuzzy_matches_completions_and_inner_msg(OpName,Ops,FMsg)
614 -> ajoin(['Unknown operation in replay step ',Step,' (did you mean the operation ',FMsg,' ?) : '], Msg)
615 ; ajoin(['Unknown operation in replay step ',Step,': '], Msg)),
616 (member(pos/Pos,Meta) -> true ; Pos=unknown),
617 add_error(b_intelligent_trace_replay,Msg,OpName,Pos)
618 },
619 % TODO: maybe do a fuzzy match and check if a new operation not used in the trace file exists
620 exclude_and_collect_errors(unknown_variable_binding(Step,OpName),DestStore,DestStore2),
621 exclude_and_collect_errors(unknown_variable(Step,OpName),UnchangedVars,UnchangedVars2).
622
623 check_step_postconditions(transition_spec(_, _, _, _, _, _, _, Postconditions),StateID) -->
624 check_postconditions(Postconditions,1,StateID).
625
626 check_postconditions([],_,_) --> [].
627 check_postconditions([Postcondition|Postconditions],Nr,StateID) -->
628 check_postcondition(Postcondition,Nr,StateID),
629 {Nr1 is Nr+1},
630 check_postconditions(Postconditions,Nr1,StateID).
631
632 check_postcondition(state_predicate(Pred),Nr,StateID) -->
633 {get_state_for_b_formula(StateID,Pred,State)},
634 ({b_test_boolean_expression_for_ground_state(Pred,[],State,'trace replay postconditions',Nr)} ->
635 []
636 ;
637 add_replay_error('Failed postcondition (predicate):',Nr)
638 ).
639 check_postcondition(operation_enabled(OpName,Pred,Enabled),Nr,StateID) -->
640 {
641 precise_match_spec(MatchSpec),
642 TransitionSpec = transition_spec(OpName,[],[],[],[],[],[Pred],[]),
643 (perform_single_replay_step(StateID,_,_,MatchSpec,TransitionSpec) -> Actual = enabled ; Actual = disabled)
644 },
645 ({Enabled == Actual} ->
646 []
647 ;
648 {ajoin(['Failed postcondition (operation ',OpName,' should be ',Enabled,'):'],Msg)},
649 add_replay_error(Msg,Nr)
650 ).
651
652 % a version of exclude which also collects errors
653 exclude_and_collect_errors(_Pred,[],[]) --> [].
654 exclude_and_collect_errors(Pred,[H|T],Res) --> {call(Pred,H,Error)},!,
655 [Error],
656 exclude_and_collect_errors(Pred,T,Res).
657 exclude_and_collect_errors(Pred,[H|T],[H|Res]) --> % include item
658 exclude_and_collect_errors(Pred,T,Res).
659
660
661 add_replay_error(Msg,Term) --> {gen_replay_error(Msg,Term,Err)}, [Err].
662 gen_replay_error(Msg,Term,rerror(FullMSg)) :- ajoin([Msg,Term],FullMSg).
663 replay_error_occured(Errors) :- member(rerror(_),Errors).
664 get_replay_error(rerror(Msg),Msg).
665
666 :- use_module(probsrc(btypechecker), [unify_types_strict/2]).
667 :- use_module(probsrc(kernel_objects), [infer_value_type/2]).
668 :- use_module(probsrc(translate), [pretty_type/2]).
669 :- use_module(probsrc(kernel_freetypes),[registered_freetype/2, freetype_case_db/3]).
670
671 % check which parameter bindings should be ignored, not checked from trace file
672 ignore_operation_parameter('$setup_constants',ID) :-
673 ( registered_freetype(ID,_) -> add_message(replay_json_trace_file,'Not loading FREETYPE from trace file: ',ID)
674 ; freetype_case_db(ID,_,_) -> add_message(replay_json_trace_file,'Not loading FREETYPE case from trace file: ',ID)
675 ).
676
677 unknown_para_binding(OpName,TParas,Kind,Step,json_bind(ID,Value,ValType,ValPos),ErrorTerm) :- b_or_z_mode, !,
678 ( get_texpr_id(TID,ID),
679 member(TID,TParas), get_texpr_type(TID,Type)
680 -> illegal_type(ID,Type,Value,ValType,ValPos,Kind,Step,ErrorTerm)
681 ; ajoin(['Ignoring unknown ',Kind,' for operation ',OpName,' at step ', Step, ': '],Msg),
682 gen_replay_error(Msg,ID,ErrorTerm)
683 ).
684 unknown_para_binding(OpName,_,Kind,Step,json_bind(ID,_,any,_),ErrorTerm) :- xtl_mode, !,
685 (xtl_interface:xtl_transition_parameters(OpName,ParaIDs)
686 -> \+ memberchk(ID,ParaIDs)
687 ; \+ is_xtl_param(ID)),
688 ajoin(['Ignoring unknown ',Kind,' for operation ',OpName,' at step ', Step, ': '],Msg),
689 gen_replay_error(Msg,ID,ErrorTerm).
690 unknown_variable_binding(Step,_OpName,json_bind(Var,Value,ValType,ValPos),ErrorTerm) :- b_or_z_mode, b_is_variable(Var,Type),!,
691 illegal_type(Var,Type,Value,ValType,ValPos,'variable',Step,ErrorTerm).
692 unknown_variable_binding(Step,OpName,json_bind(Var,_,_,_),ErrorTerm) :- unknown_variable(Step,OpName,Var,ErrorTerm).
693 unknown_variable(Step,OpName,Var,ErrorTerm) :- xtl_mode, !,
694 Var \= xtl_state,
695 ajoin(['Ignoring unknown variable at step ', Step, ' for ', OpName, ': '],Msg),
696 gen_replay_error(Msg,Var,ErrorTerm).
697 unknown_variable(Step,OpName,Var,ErrorTerm) :- \+ b_is_variable(Var),
698 (b_is_constant(Var)
699 -> ajoin(['Ignoring constant at step ', Step, ' for ', OpName, ' (a variable is expected here): '],Msg)
700 ; b_get_machine_variables(TVars),get_texpr_ids(TVars,Vars),
701 get_possible_fuzzy_matches_completions_and_inner_msg(Var,Vars,FMsg)
702 -> ajoin(['Ignoring unknown variable (did you mean ',FMsg,' ?) at step ', Step, ' for ', OpName, ': '],Msg)
703 ; ajoin(['Ignoring unknown variable at step ', Step, ' for ', OpName, ': '],Msg)
704 ),
705 gen_replay_error(Msg,Var,ErrorTerm).
706 unknown_constant_binding(Step,json_bind(Var,Value,ValType,ValPos),ErrorTerm) :- b_is_constant(Var,Type),!,
707 illegal_type(Var,Type,Value,ValType,ValPos,'constant',Step,ErrorTerm).
708 unknown_constant_binding(Step,json_bind(Var,_,_,_),ErrorTerm) :-
709 (b_is_variable(Var)
710 -> ajoin(['Ignoring variable at step ', Step, ' (a constant is expected here): '],Msg)
711 ; b_get_machine_constants(TVars),get_texpr_ids(TVars,Vars),
712 get_possible_fuzzy_matches_completions_and_inner_msg(Var,Vars,FMsg)
713 -> ajoin(['Ignoring unknown constant (did you mean ',FMsg,' ?) at step ', Step, ': '],Msg)
714 ; ajoin(['Ignoring unknown constant at step ', Step, ': '],Msg)
715 ),
716 gen_replay_error(Msg,Var,ErrorTerm).
717
718
719 illegal_type(Var,Type,_Value,ValType,_ValPos,Kind,Step,ErrorTerm) :-
720 \+ unify_types_strict(Type,ValType),
721 pretty_type(ValType,VTS), pretty_type(Type,TS),
722 ajoin(['Ignoring ',Kind, ' at step ', Step,
723 ' due to unexpected type of value (', VTS, ' instead of ',TS,') for: '],ErrMsg),
724 gen_replay_error(ErrMsg,Var,ErrorTerm).
725
726 is_xtl_param(ID) :- atom_chars(ID,['p','a','r','a'|T]), number_chars(_,T).
727 /*
728 | ?- perform_single_replay_step(X,TID,Dest,Match,transition_spec(Op,[],[],[],[active])).
729 X = 3,
730 TID = 86,
731 Dest = 5,
732 Match = match_spec(match,match,match,match,match),
733 Op = new ?
734 yes
735
736 */
737
738 % ------------------
739 %precise_replay_trace(Trace,FromID,TransIds,DestID) :-
740 % precise_match_spec(MatchSpec), % require precise replay
741 % replay_trace(Trace,[MatchSpec],[],1,FromID,TransIds,DestID,[],_). % Todo : check errors
742
743 :- use_module(tools_printing,[format_with_colour/4, check_mark_symbol_codes/1]).
744 :- use_module(probsrc(debug),[formatsilent_with_colour/4]).
745 % Note if we leave RestSpecs as a variable this will always do deterministic replay
746 % to achieve backtracking RestSpecs must be set to []
747 replay_trace([],_MatchSpecs,_Opts,_,ID,[],ID,[],[]).
748 replay_trace([TransSpec|T],MatchSpecs,Options,Step,FromID,TransIds,DestID,RestSpecs,
749 [replay_step(MatchInfo,Errors)|OtherMatches]) :-
750 get_transition_spec_txt(TransSpec,TTxt),
751 formatsilent_with_colour(user_output,[blue],'==> Replay step ~w: from state ~w for ~w~n',[Step,FromID,TTxt]),
752 check_mark_symbol_codes(CheckMark),
753 statistics(walltime,[W1|_]),
754 % first perform static check of step:
755 phrase(check_and_adapt_trace_step(TransSpec,Step,CorrectedTransSpec),Errors,Errors1),
756 if((TransIds=[TransID|TTrans],
757 flexible_perform_single_replay_step(FromID,TransID,ID2,MatchSpecs,CorrectedTransSpec,MatchInfo)),
758 (phrase(check_step_postconditions(CorrectedTransSpec,ID2),Errors1),
759 statistics(walltime,[W2|_]), WTime is W2-W1,
760 get_transition_name(FromID,TransID,OpName), % show operation name used as feedback in case errors occur
761 (Errors == [] ->
762 formatsilent_with_colour(user_output,[green],' ~s Replay step ~w successful (~w, ~w ms) leading to state ~w~n',[CheckMark,Step,MatchInfo,WTime,ID2])
763 ; Errors = [rerror(OneErr)] ->
764 formatsilent_with_colour(user_output,[red,bold],'==> Replay step ~w successful WITH ERROR (~w, ~w, ~w ms) leading to state ~w via ~w~n',[Step,MatchInfo,OneErr,WTime,ID2,OpName])
765 ;
766 length(Errors,NrErrors), Errors = [rerror(OneErr)|_],
767 formatsilent_with_colour(user_output,[red,bold],'==> Replay step ~w successful WITH ERRORS (~w, ~w errors [~w,...], ~w ms) leading to state ~w via ~w~n',[Step,MatchInfo,NrErrors,OneErr,WTime,ID2,OpName])
768 ;
769 length(Errors,NrErrors),
770 formatsilent_with_colour(user_output,[red,bold],'==> Replay step ~w successful WITH ERRORS (~w, ~w errors, ~w ms) leading to state ~w via ~w~n',[Step,MatchInfo,NrErrors,WTime,ID2,OpName])
771 ),
772 (get_preference(deterministic_trace_replay,true) -> !
773 % TO DO: use info from MatchSpec? (e.g., det for perfect match)
774 ; true
775 ; formatsilent_with_colour(user_output,[orange],'==> Backtracking replay step ~w (~w) leading to state ~w~n',[Step,MatchInfo,ID2])),
776 S1 is Step+1,
777 replay_trace(T,MatchSpecs,Options,S1,ID2,TTrans,DestID,RestSpecs,OtherMatches)
778 ),
779 (format_with_colour(user_output,[red,bold],'==> Replay step ~w FAILED~n',[Step]),
780 get_transition_spec_txt(TransSpec,Txt), formatsilent_with_colour(user_output,[red,bold],' ~w~n',[Txt]),
781 Errors1=[],
782 MatchInfo=failed,
783
784 (T = [_|_], nonmember(stop_at_failure,Options)
785 -> % try and skip this step and continue replay
786 RestSpecs=[TransSpec|RT],
787 TransIds=[skip|TTrans], % -1 signifies skipped transition
788 S1 is Step+1,
789 replay_trace(T,MatchSpecs,Options,S1,FromID,TTrans,DestID,RT,OtherMatches)
790 ; RestSpecs=[TransSpec|T], % the steps that were not replayed
791 TransIds=[], DestID=FromID,
792 OtherMatches=[]
793 )
794 )
795 ).
796
797 % ------------------
798
799
800 tcltk_replay_json_trace_file(FileName,ReplayStatus,list([Header|Entries])) :-
801 replay_json_trace_file_with_check(FileName,TransSpecs,ReplayStatus,TransIds,MatchInfoList),
802 try_set_trace_by_transition_ids(TransIds),
803 Header = list(['Step', 'TraceFile','Replayed', 'Match','Mismatches','Errors','State ID']),
804 (tk_get_trace_info(TransSpecs,root,1,TransIds,MatchInfoList,Entries)
805 -> true
806 ; add_internal_error('Could not compute replay table:',TransSpecs), Entries=[]).
807
808
809 :- use_module(probsrc(translate),[translate_event_with_limit/3]).
810
811 tk_get_trace_info([],_,_,_,_,[]).
812 tk_get_trace_info([TransSpec|TS2],CurID,Step,TransIds,MatchInfoList,
813 [list([Step,Txt,OpTxt,MI,list(DeltaList),list(Errors),CurID])|RestInfo]) :-
814 get_from_match_list(MatchInfoList,MI,Errors,MIL2),
815 get_transition_spec_txt(TransSpec,Txt),
816 (TransIds=[TID1|TI2], transition(CurID,OperationTerm,TID1,ToID)
817 -> %get_operation_internal_name(OperationTerm,OpName)
818 translate_event_with_limit(OperationTerm,30,OpTxt),
819 analyse_step_match(TransSpec,CurID,TID1,DeltaList)
820 ; TransIds=[TID1|TI2],
821 (number(TID1) -> TID1<0 ; true) % not a valid transition number; -1 or skip
822 -> ToID=CurID, OpTxt='skipped', DeltaList=[]
823 ; TI2=[], ToID=CurID, OpTxt='-', DeltaList=[]
824 ),
825 Step1 is Step+1,
826 tk_get_trace_info(TS2,ToID,Step1,TI2,MIL2,RestInfo).
827
828 % get_replay_table(+TransSpecs,+TransIds,+MatchInfoList,-Rows)
829 % computes one row per step of a replayed trace file (TransSpecs, as returned by replay_json_trace_file/5):
830 % row(Step,TraceFileTxt,ReplayedTxt,MatchInfo,Mismatches,Errors)
831 % Mismatches is a list of the identifiers whose values differ from the trace file ('Name' if the operation name differs)
832 % used by the ProB Rodin Plugin to explain an imperfect or partial replay
833 get_replay_table(TransSpecs,TransIds,MatchInfoList,Rows) :-
834 tk_get_trace_info(TransSpecs,root,1,TransIds,MatchInfoList,Entries),!,
835 maplist(tk_entry_to_row,Entries,Rows).
836 get_replay_table(TransSpecs,_,_,[]) :-
837 add_internal_error('Could not compute replay table:',TransSpecs).
838
839 tk_entry_to_row(list([Step,Txt,OpTxt,MI,list(Delta),list(Errs),_]), row(Step,Txt,OpTxt,MI,Delta,Errs)).
840
841 get_from_match_list([replay_step(MI,Errors)|T],MatchInfo,TkErrors,T) :-
842 maplist(get_replay_error,Errors,TkErrors),
843 (MI=precise,TkErrors=[_|_] -> MatchInfo=precise_with_errs ; MatchInfo=MI).
844 get_from_match_list([],'-',['-'],[]).
845
846 % analyse how good a step matches the transition spec
847 % useful after replay to provide explanations to the user
848 analyse_step_match(TransSpec,FromID,TransID,DeltaList) :-
849 TransSpec = transition_spec(OpName, _, ParaStore, ResultStore, DestStore, _UnchangedVars, _Preds, _Postconditions),
850 get_sorted_transition_details(FromID,TransID,DestID,TOpName,FullParaStore,FullResultStore),
851 (TOpName=OpName -> DeltaList=DL1 ; DeltaList=['Name'|DL1]),
852 delta_store_match(FullParaStore,paras,ParaStore,DL1,DL2),
853 delta_store_match(FullResultStore,results,ResultStore,DL2,DL3),
854 visited_expression(DestID,DestState),
855 get_dest_store(DestState,FullDestStore),
856 delta_store_match(FullDestStore,dest,DestStore,DL3,DL4),
857 % TO DO: UnchangedVars and _Preds
858 DL4=[],!.
859 analyse_step_match(TransSpec,FromID,TransID,DeltaList) :-
860 add_internal_error('Call failed:',analyse_step_match(TransSpec,FromID,TransID,DeltaList)),
861 DeltaList=['??ERROR??'].
862
863 delta_store_match(_,_,[]) --> !.
864 delta_store_match([],_Key,Rest)
865 --> add_rest(Rest). % these bindings were probably filtered out during replay and error messages were generated
866 delta_store_match([Bind1|T],Key,[Bind2|T2]) -->
867 {is_bind(Bind1,ID,Val), is_bind(Bind2,ID,Val2)},
868 !,
869 ({check_value_equal(ID,Val,Val2)}
870 -> []
871 ; %translate_bvalue_with_limit(Val,100,V1), translate_bvalue_with_limit(Val2,100,V2),
872 [ID] % TO DO: provided detailed explanation using values
873 ),delta_store_match(T,Key,T2).
874 delta_store_match([_ID|T],Key,PartialStore) --> delta_store_match(T,Key,PartialStore).
875
876 add_rest([]) --> [].
877 add_rest([Bind|T]) --> {is_bind(Bind,ID,_)}, [ID], add_rest(T).
878
879 % -----------------------
880
881 replay_json_trace_file(FileName,ReplayStatus) :-
882 replay_json_trace_file_with_check(FileName,_,ReplayStatus,TransIds,_),
883 try_set_trace_by_transition_ids(TransIds).
884
885
886 % generate error/warning for imperfect or partial replay
887 replay_json_trace_file_with_check(FileName,Trace,ReplayStatus,TransIds,MatchInfoList) :-
888 replay_json_trace_file(FileName,Trace,ReplayStatus,TransIds,MatchInfoList),
889 length(TransIds,Steps),
890 length(Trace,AllSteps),
891 check_replay_status(ReplayStatus,Steps,AllSteps).
892
893 check_replay_status(imperfect,Steps,_) :- !,
894 ajoin(['Imperfect replay, steps replayed: '],Msg),
895 add_warning(replay_json_trace_file,Msg, Steps).
896 check_replay_status(partial,Steps,AllSteps) :- !,
897 ajoin(['Replay of all ',AllSteps,' steps not possible, steps replayed: '],Msg),
898 add_error(replay_json_trace_file,Msg, Steps).
899 check_replay_status(perfect,Steps,_) :-
900 add_message(replay_json_trace_file,'Perfect replay possible, steps replayed: ', Steps).
901
902 % ------------
903
904 :- use_module(tools,[start_ms_timer/1, stop_ms_timer_with_silent_msg/2,
905 stop_ms_timer_with_debug_msg/2]).
906 :- use_module(bmachine_construction,[dummy_machine_name/2]).
907
908 replay_json_trace_file(FileName,Trace,ReplayStatus,TransIds,MatchInfoList) :- \+ bmachine_is_precompiled,!,
909 add_error(replay_json_trace_file,'No specification loaded, cannot replay trace file:',FileName),
910 Trace=[], TransIds=[], ReplayStatus=partial, MatchInfoList=[].
911 replay_json_trace_file(FileName,Trace,ReplayStatus,TransIds,MatchInfoList) :-
912 start_ms_timer(T1),
913 read_json_trace_file(FileName,ModelName,Trace),
914 stop_ms_timer_with_debug_msg(T1,'loading JSON trace file'),
915 precise_match_spec(MatchSpec), % require precise replay
916 ignore_dest_match_spec(MS2),
917 opname_optimize_match_spec(MS3),
918 % was ignore_return_match_spec(MS3), % TODO: when no return and no non-det vars: do not try MS3
919 start_ms_timer(T2),
920 temporary_set_preference(deterministic_trace_replay,true,CHNG),
921 replay_trace(Trace,[MatchSpec,MS2,MS3],[],1,root,TransIds,_DestID,RestTrace,MatchInfoList),
922 reset_temporary_preference(deterministic_trace_replay,CHNG),
923 stop_ms_timer_with_silent_msg(T2,'replaying JSON trace file'),
924 !,
925 (RestTrace = []
926 -> ((match_spec_was_used(MS3) % Grade=3
927 ; match_spec_was_used(MS2) %Grade=2
928 ; member(replay_step(_,Errs),MatchInfoList), replay_error_occured(Errs)
929 )
930 -> ReplayStatus=imperfect,
931 check_model_name(ModelName)
932 ; ReplayStatus=perfect
933 )
934 ; ReplayStatus=partial,
935 check_model_name(ModelName)
936 ).
937
938 :- use_module(specfile,[currently_opened_specification_name/1]).
939 check_model_name(ModelName) :-
940 currently_opened_specification_name(CurModelName),!,
941 (CurModelName=ModelName -> true
942 ; dummy_machine_name(ModelName,CurModelName) % CurModelName = MAIN_MACHINE_FOR_...
943 -> true
944 ; ModelName = 'dummy(uses)'
945 -> true % if modelName is "null" this is the value used
946 ; prob2_ui_suffix(ModelName,CurModelName) ->
947 % happens when ProB2-UI saves trace files; sometimes it adds (2), ... suffix, see issue #243
948 add_message(replay_json_trace_file, 'JSON trace file model name has a ProB2-UI suffix: ', ModelName)
949 ; ajoin(['JSON trace file model name ',ModelName,' does not match current model name: '],MMsg),
950 add_warning(replay_json_trace_file, MMsg, CurModelName)
951 ).
952 check_model_name(ModelName) :-
953 add_warning(replay_json_trace_file, 'Cannot determine current model name to check stored name:', ModelName).
954
955 :- set_prolog_flag(double_quotes, codes).
956 :- use_module(self_check).
957 :- assert_must_succeed(b_intelligent_trace_replay:prob2_ui_suffix('b_mch', 'b')).
958 :- assert_must_succeed(b_intelligent_trace_replay:prob2_ui_suffix('b_mch (2)', 'b')).
959 :- assert_must_succeed(b_intelligent_trace_replay:prob2_ui_suffix('b (2)', 'b')).
960 :- assert_must_fail(b_intelligent_trace_replay:prob2_ui_suffix('b', 'bc')).
961 :- assert_must_fail(b_intelligent_trace_replay:prob2_ui_suffix('b (2)', 'bc')).
962 % check if name matches current model name catering for ProB2-UI quirks
963 prob2_ui_suffix(JSONModelName,CurModelName) :-
964 atom_codes(JSONModelName,JCodes),
965 atom_codes(CurModelName,TargetCodes),
966 append(TargetCodes,After,JCodes),
967 (append("_mch",After2,After)
968 -> true % .eventb package file name
969 ; append(".mch",After2,After) -> true
970 ; After2=After),
971 valid_prob2_ui_suffix(After2).
972
973 valid_prob2_ui_suffix([]) :- !.
974 valid_prob2_ui_suffix([32|_]). % we could check that we have (2), ... after; but is it necessary?
975
976
977 error_occured_during_replay(MatchInfoList) :-
978 member(replay_step(_,Errs),MatchInfoList), replay_error_occured(Errs),!.
979
980 % ---------------------------------
981
982 replay_prolog_trace_file(FileName) :-
983 start_ms_timer(T1),
984 read_prolog_trace_file(FileName,_ModelName,Trace),
985 stop_ms_timer_with_debug_msg(T1,'loading Prolog trace file'),
986 replay_prolog2(FileName,Trace).
987
988 replay_prolog2(FileName,Trace) :-
989 precise_match_spec(MatchSpec),
990 start_ms_timer(T2),
991 replay_trace(Trace,[MatchSpec],[stop_at_failure],1,root,TransIds,_DestID,RestTrace,MatchInfoList),
992 stop_ms_timer_with_silent_msg(T2,'replaying JSON trace file'),
993 RestTrace=[], % will initiate backtracking
994 try_set_trace_by_transition_ids(TransIds),
995 (error_occured_during_replay(MatchInfoList)
996 -> add_error(replay_prolog_trace_file,'Errors occurred during replay of file:',FileName)
997 ; true).
998 replay_prolog2(FileName,_Trace) :-
999 add_error(replay_prolog_trace_file,'Could not fully replay file:',FileName).
1000
1001 read_prolog_trace_file(FileName,ModelName,Trace) :-
1002 open(FileName,read,Stream,[encoding(utf8)]),
1003 call_cleanup(parse_prolog_trace_file(FileName,Stream,ModelName,Trace),
1004 close(Stream)).
1005
1006 parse_prolog_trace_file(File,Stream,ModelName,Trace) :-
1007 safe_read_stream(Stream,0,Term),!,
1008 (Term = end_of_file
1009 -> Trace = [], ModelName = 'dummy(uses)',
1010 add_warning(read_prolog_trace_file,'Empty trace file: ',File)
1011 ; (Term = machine(ModelName)
1012 -> Trace = T
1013 ; Trace = [Term|T],
1014 add_warning(read_prolog_trace_file,'File does not start with a machine/1 fact: ',Term)
1015 ),
1016 parse_prolog_trace_file_body(Stream,1,T)
1017 ).
1018
1019 parse_prolog_trace_file_body(Stream,Step,Trace) :-
1020 safe_read_stream(Stream,Step,Term),!,
1021 (Term = end_of_file
1022 -> Trace = []
1023 ; skip_prolog_term(Term)
1024 -> add_message(read_prolog_trace_file,'Skipping: ',Term),
1025 parse_prolog_trace_file_body(Stream,Step,Trace)
1026 ; Trace = [TransSpec|T],
1027 convert_prolog_trace_step(Term,TransSpec),
1028 S1 is Step + 1,
1029 parse_prolog_trace_file_body(Stream,S1,T)
1030 ).
1031
1032 safe_read_stream(Stream,Step,T) :-
1033 catch(read(Stream,T), E, (
1034 ajoin(['Exception while reading step ', Step, 'of trace file: '], Msg),
1035 add_error(read_prolog_trace_file,Msg,[E]),
1036 T=end_of_file
1037 )).
1038
1039 skip_prolog_term('$check_value'(_ID,_Val)).
1040 convert_prolog_trace_step(Fact,
1041 transition_spec(OpName,Meta,ParaStore,ResultStore,DestStore,Unchanged,PredList,[])) :-
1042 PredList=[], Unchanged=[], Meta=[], DestStore = [],
1043 decompose_operation(Fact,OpName,ParaStore,ResultStore).
1044 % TODO: deal with '$check_value'(ID,Val)
1045 % decompose an operation term into name, parameter store and result store
1046 decompose_operation('-->'(OpTerm,Results),OpName,ParaStore,ResultStore) :- !,
1047 decompose_operation2(OpTerm,OpName,ParaStore),
1048 (b_get_machine_operation_result_names(OpName,ResultNames)
1049 -> create_sorted_store(ResultNames,Results,OpName,ResultStore)
1050 ; ResultStore = []).
1051 decompose_operation(OpTerm,OpName,ParaStore,[]) :- decompose_operation2(OpTerm,OpName,ParaStore).
1052
1053 is_setup_or_init('$initialise_machine','$initialise_machine').
1054 is_setup_or_init(initialise_machine,'$initialise_machine'). % old style
1055 is_setup_or_init(setup_constants,'$setup_constants'). % old style
1056 is_setup_or_init(Op,Op) :- is_setup_constants_op(Op).
1057
1058 decompose_operation2(OpTerm,OpName,ParaStore) :-
1059 functor(OpTerm,Functor,Arity),
1060 is_setup_or_init(Functor,OpName),
1061 !,
1062 % the order of constants, variables etc has changed in ProB;
1063 % in general we cannot reconstruct the association of the arguments to variables or constants
1064 (Arity=0 -> true
1065 ; add_message(b_intelligent_trace_replay,'Ignoring parameters of:',OpName)),
1066 ParaStore=[].
1067 decompose_operation2(OpTerm,OpName,ParaStore) :-
1068 OpTerm =.. [OpName|Paras],
1069 (b_get_machine_operation_parameter_names_for_animation(OpName,ParaNames)
1070 -> create_sorted_store(ParaNames,Paras,OpName,ParaStore)
1071 ; ParaStore = [],
1072 add_error(read_prolog_trace_file,'Unknown operation in trace file:',OpName)
1073 ).
1074
1075
1076 create_sorted_store([],Paras,OpName,SortedParaStore) :- Paras = [_|_],
1077 get_preference(show_eventb_any_arguments,false),!,
1078 add_message(b_intelligent_trace_replay,'Prolog trace file contains values for virtual parameters (set SHOW_EVENTB_ANY_VALUES to TRUE to better replay this trace file): ',OpName),
1079 SortedParaStore = [].
1080 create_sorted_store(ParaNames,[],_OpName,SortedParaStore) :- ParaNames = [_|_],
1081 get_preference(show_eventb_any_arguments,true),!,
1082 add_message(b_intelligent_trace_replay,'Prolog trace file contains no values for parameters (maybe SHOW_EVENTB_ANY_VALUES was FALSE when trace file was created): ',ParaNames),
1083 SortedParaStore = [].
1084 create_sorted_store(ParaNames,Paras,OpName,SortedParaStore) :-
1085 create_local_store_for_operation(ParaNames,Paras,OpName,ParaStore),
1086 sort(ParaStore,SortedParaStore).
1087
1088
1089
1090 % ------------------------
1091
1092 :- use_module(extrasrc(json_parser),[json_parse_file/3]).
1093
1094 % read a JSON ProB2-UI trace file and extract model name and transition_spec list
1095 read_json_trace_file(FileName,ModelName,Trace) :-
1096 json_parse_file(FileName,Term,[rest(_),position_infos(true),strings_as_atoms(false)]),
1097 %nl,print(Term),nl,nl,
1098 !,
1099 (extract_json_model_name(Term,M) -> ModelName=M ; ModelName = 'dummy(uses)'),
1100 (translate_json_trace_term(Term,FileName,Trace) -> true
1101 ; add_error(read_json_trace_file,'Could not translate JSON transitionList: ',Term),
1102 Trace = []).
1103
1104 % --------
1105
1106 :- use_module(probsrc(preferences), [reset_temporary_preference/2,temporary_set_preference/3, get_preference/2]).
1107 translate_json_trace_term(json(ObjList),FileName,Trace) :-
1108 get_json_key_list(transitionList,ObjList,List),
1109 List \= [], % optimization, dont set preferences
1110 !,
1111 temporary_set_preference(repl_cache_parsing,true,CHNG),
1112 eval_strings:turn_normalising_off,
1113 % call_cleanup: also restore when translating an operation fails or raises an exception
1114 call_cleanup(maplist(translate_json_operation(FileName),List,Trace),
1115 (eval_strings:turn_normalising_on,
1116 reset_temporary_preference(repl_cache_parsing,CHNG))).
1117
1118 % no transitionList => just use empty list
1119 translate_json_trace_term(json(_),_,[]) :- !.
1120
1121 % extract model name from metadata which looks like this
1122 /*
1123 "metadata": {
1124 "fileType": "Trace",
1125 "formatVersion": 1,
1126 "savedAt": "2021-10-13T13:38:02Z",
1127 "creator": "tcltk (leuschel)",
1128 "proBCliVersion": "1.11.1-nightly",
1129 "proBCliRevision": "3cb800bbadfeaf4f581327245507a55ae5a5e66d",
1130 "modelName": "scheduler",
1131 "modelFile": "/Users/bourkaki/B/Benchmarks/scheduler.mch"
1132 }
1133 */
1134
1135 extract_json_model_name(json(ObjList),MachineName) :-
1136 get_json_key_object(metadata,ObjList,List),
1137 get_json_attribute(modelName,List,string(MC)),
1138 atom_codes(MachineName,MC).
1139
1140
1141 % translate a single JSON transition entry into a transition_spec term for replay_trace
1142 /* here is a typical entry for the scheduler model:
1143 {
1144 "name": "ready",
1145 "params": {
1146 "rr": "process3"
1147 },
1148 "results": {
1149 },
1150 "destState": {
1151 "active": "{process3}",
1152 "waiting": "{}"
1153 },
1154 "destStateNotChanged": [
1155 "ready"
1156 ],
1157 "preds": null
1158 },
1159 */
1160 translate_json_operation(FileName,json(Json),
1161 transition_spec(OpName,Meta,
1162 ParaStore,ResultStore,DestStore,Unchanged,PredList,Postconditions) ) :-
1163 (get_json_attribute_with_pos(name,Json,FileName,string(OpNameC),Position)
1164 -> atom_codes(OpName,OpNameC)
1165 ; get_json_attribute_with_pos(_SomeOtherAttr,Json,FileName,_,Position)
1166 -> add_message(translate_json_operation,'Transition has no JSON "name" attribute','',Position),
1167 OpName = ''
1168 ; OpName = '', Position=unknown,
1169 add_error(translate_json_operation,'Transition has no JSON "name" or other attribute in file: ',FileName,Position)
1170 ),
1171 (debug_mode(off) -> true ; add_message(translate_json_operation,'Processing operation: ',OpName,Position)),
1172 (get_json_key_object(params,Json,Paras)
1173 -> translate_json_paras(Paras,params(OpName),FileName,OpName,Bindings),
1174 sort(Bindings,ParaStore) % put the parameters into the standard Prolog order
1175 ; ParaStore = []
1176 ),
1177 (get_json_key_object(results,Json,ResParas)
1178 -> translate_json_paras(ResParas,results(OpName),FileName,OpName,Bindings2),
1179 sort(Bindings2,ResultStore)
1180 ; ResultStore = []
1181 ),
1182 (get_json_key_object(destState,Json,DestState)
1183 -> translate_json_paras(DestState,destState,FileName,OpName,Bindings3),
1184 sort(Bindings3,DestStore)
1185 ; DestStore = []
1186 ),
1187 (get_json_key_list(destStateNotChanged,Json,UnchList)
1188 -> maplist(translate_json_string,UnchList,UnchAtoms),
1189 sort(UnchAtoms,Unchanged)
1190 ; Unchanged = []
1191 ),
1192 (get_json_key_list(preds,Json,JPredList)
1193 -> (maplist(translate_json_pred,JPredList,PredList) -> true
1194 ; add_error(translate_json_operation,'Unable to parse predicates for operation:',OpName,Position),
1195 PredList = []
1196 )
1197 ; PredList = []
1198 ),
1199 (get_json_key_list(postconditions,Json,PostconditionList)
1200 -> maplist(translate_postcondition,PostconditionList,Postconditions)
1201 ; Postconditions = []
1202 ),
1203 (get_json_attribute(description,Json,string(DescCodes))
1204 -> atom_codes(Desc,DescCodes), Meta = [description/Desc,pos/Position]
1205 ; Meta = [pos/Position]
1206 ).
1207
1208 translate_postcondition(json(Json),Postcondition) :- % each postcondition is a JSON object json(AttributeList)
1209 get_json_attribute(kind,Json,string(KindCodes)),
1210 atom_codes(Kind,KindCodes),
1211 (translate_postcondition_kind(Kind,Json,Postcondition) -> true ; add_error(translate_postcondition,'translate_postcondition_kind failed',Json), fail).
1212
1213 translate_postcondition_kind('PREDICATE',Json,state_predicate(TPred)) :-
1214 !,
1215 get_json_attribute(predicate,Json,PredString),
1216 translate_json_pred(PredString,TPred).
1217 translate_postcondition_kind(Kind,Json,operation_enabled(OpName,TPred,Enabled)) :-
1218 enabled_kind(Kind,Enabled),
1219 !,
1220 get_json_attribute(operation,Json,string(OpNameCodes)),
1221 atom_codes(OpName,OpNameCodes),
1222 get_json_attribute(predicate,Json,PredString),
1223 (PredString = string([]) -> TPred = b(truth,pred,[])
1224 ; translate_json_pred(PredString,TPred)
1225 ).
1226
1227 enabled_kind('ENABLEDNESS',enabled).
1228 enabled_kind('DISABLEDNESS',disabled).
1229
1230
1231
1232
1233 translate_json_string(string(AtomCodes),Atom) :- atom_codes(Atom,AtomCodes).
1234
1235 translate_json_paras([],_,_,_,R) :- !, R=[].
1236 translate_json_paras([Eq|T],Kind,FileName,OpName,[Bind|BT]) :-
1237 translate_json_para(Eq,Kind,FileName,OpName,Bind),!,
1238 translate_json_paras(T,Kind,FileName,OpName,BT).
1239 translate_json_paras([_|T],Kind,FileName,OpName,BT) :- translate_json_paras(T,Kind,FileName,OpName,BT).
1240
1241
1242 :- use_module(probsrc(tools),[safe_read_term_from_codes/2]).
1243 :- use_module(probsrc(b_global_sets),[add_prob_deferred_set_elements_to_store/3]).
1244 translate_json_para(Equality,_Kind,FileName,OpName,json_bind(Name,Value,any,Pos)) :-
1245 xtl_mode,
1246 is_json_equality_attr_with_pos(Equality,FileName,Name,string(ExprCodes),Pos),
1247 !,
1248 (safe_read_term_from_codes(ExprCodes,Value)
1249 -> true
1250 ; add_parameter_error('read term from JSON failed',Name,ExprCodes,OpName,Pos), Value = '').
1251 % TO DO: using eval_strings is very ugly, use a better API predicate
1252 translate_json_para(Equality,Kind,FileName,OpName,json_bind(Name,Value,Type,Pos)) :-
1253 \+ xtl_mode,
1254 is_json_equality_attr_with_pos(Equality,FileName,Name,string(ExpressionCodes),Pos),
1255 !,
1256 (ignore_operation_parameter(OpName,Name) -> fail
1257 ; eval_strings:repl_parse_expression(ExpressionCodes,Typed,Type,Error)
1258 -> (Error \= none -> add_parameter_error(Error,Name,ExpressionCodes,OpName,Pos)
1259 ; Type = pred -> add_parameter_error('use of predicate instead of expression',Name,ExpressionCodes,OpName,Pos)
1260 ; Type = subst -> add_parameter_error('unexpected substitution',Name,ExpressionCodes,OpName,Pos)
1261 ; (add_prob_deferred_set_elements_to_store([],EState,visible), % value should not depend on any state
1262 eval_strings:eval_expression_direct(Typed,EState,Value)
1263 -> \+ illegal_json_binding_type(Kind,Name,Type,Pos)
1264 ; add_parameter_error('evaluation error',Name,ExpressionCodes,OpName,Pos)
1265 )
1266 )
1267 ; add_parameter_error('parsing failed error',Name,ExpressionCodes,OpName,Pos)
1268 ).
1269 translate_json_para(Para,_,_,_,_) :-
1270 add_error(translate_json_para,'Unknown JSON para:',Para),fail.
1271
1272 :- use_module(specfile,[translate_operation_name/2]).
1273 add_parameter_error(Error,Name,ExpressionCodes,OpName,Pos) :-
1274 translate_operation_name(OpName,TOp),
1275 ajoin(['Ignoring JSON value for parameter ',Name,' of ',TOp,' due to ',Error,':'], Msg),
1276 atom_codes(A,ExpressionCodes),
1277 add_error(translate_json_para,Msg,A,Pos),fail.
1278
1279 %evaluate_codes_value(ExpressionCodes,Type,Value) :-
1280 % eval_strings:repl_parse_expression(ExpressionCodes,Typed,Type,Error), Error=none,
1281 % eval_strings:eval_expression_direct(Typed,Value).
1282
1283 illegal_json_binding_type(destState,ID,Type,Pos) :- get_expected_type(ID,Kind,ExpectedType),!,
1284 \+ unify_types_strict(Type,ExpectedType), pretty_type(Type,TS), pretty_type(ExpectedType,ETS),
1285 ajoin(['Ignoring JSON destState value for ',Kind,' ',ID,' due to illegal type ',TS, ', expected:'], Msg),
1286 add_error(translate_json_para,Msg,ETS,Pos).
1287 illegal_json_binding_type(destState,ID,_Type,Pos) :-
1288 b_get_machine_constants(TConsts),get_texpr_ids(TConsts,CVars),
1289 b_get_machine_variables(TVars),get_texpr_ids(TVars,VVars),
1290 append(CVars,VVars,All), sort(All,SAll),
1291 get_possible_fuzzy_matches_completions_and_inner_msg(ID,SAll,FMsg),!,
1292 ajoin(['Ignoring JSON destState value for unknown identifier (did you mean ',FMsg,' ?):'],Msg),
1293 add_error(translate_json_para,Msg,ID,Pos).
1294 illegal_json_binding_type(destState,ID,_Type,Pos) :-
1295 add_error(translate_json_para,'Ignoring JSON destState value for unknown identifier:',ID,Pos).
1296 % unknown operations are now dealt with later in check_and_adapt_trace_step
1297 %illegal_json_binding_type(params(Op),ID,_Type,Pos) :-
1298 % b_or_z_mode, % otherwise no types available
1299 % \+ b_top_level_operation(Op), !,
1300 % findall(KOpid,b_top_level_operation(KOpid),Ops),
1301 % (get_possible_fuzzy_matches_completions_and_inner_msg(Op,Ops,FMsg)
1302 % -> ajoin(['Ignoring JSON value for parameter ',ID,' of unknown operation (did you mean the operation ',FMsg,' ?) : '], Msg)
1303 % ; ajoin(['Ignoring JSON value for parameter ',ID,' of unknown operation: '], Msg)),
1304 % add_error(translate_json_para,Msg,Op,Pos).
1305 illegal_json_binding_type(params(Op),ID,Type,Pos) :-
1306 b_or_z_mode, % otherwise no types available
1307 b_top_level_operation(Op),
1308 b_get_machine_operation_typed_parameters_for_animation(Op,Params),
1309 member(b(identifier(ID),ExpectedType,_),Params),!,
1310 \+ unify_types_strict(Type,ExpectedType), pretty_type(Type,TS), pretty_type(ExpectedType,ETS),
1311 ajoin(['Ignoring JSON value for parameter ',ID,' of operation ', Op, ' due to illegal type ',TS, ', expected:'], Msg),
1312 add_error(translate_json_para,Msg,ETS,Pos).
1313 illegal_json_binding_type(params(Op),ID,_Type,Pos) :-
1314 b_or_z_mode, % otherwise show_eventb_any_arguments makes no sense
1315 b_top_level_operation(Op),
1316 (b_get_machine_operation_typed_parameters_for_animation(Op,[]),
1317 get_preference(show_eventb_any_arguments,false)
1318 % TODO: check if ID is a valid virtual parameter, or if trace file was generated with preference set to true
1319 -> ajoin(['Ignoring JSON value for parameter ',ID,', operation has no parameters (setting SHOW_EVENTB_ANY_VALUES to TRUE may help):'],Msg)
1320 ; ajoin(['Ignoring JSON value for unknown parameter ',ID,' for:'],Msg)
1321 ),
1322 add_error(translate_json_para,Msg,Op,Pos).
1323 illegal_json_binding_type(results(Op),ID,Type,Pos) :-
1324 b_or_z_mode, % otherwise there are no typred results available
1325 b_get_machine_operation_typed_results(Op,Results), member(b(identifier(ID),ExpectedType,_),Results),!,
1326 \+ unify_types_strict(Type,ExpectedType), pretty_type(Type,TS), pretty_type(ExpectedType,ETS),
1327 ajoin(['Ignoring JSON value for result ',ID,' of operation ', Op, ' due to illegal type ',TS], Msg),
1328 add_error(translate_json_para,Msg,ETS,Pos).
1329 % unknown operations are now dealt with later in check_and_adapt_trace_step
1330 %illegal_json_binding_type(results(_Op),ID,_Type,Pos) :-
1331 % add_error(translate_json_para,'Ignoring JSON value for unknown operation result:',ID,Pos).
1332
1333 get_expected_type(ID,variable,ExpectedType) :- bmachine_is_precompiled, b_is_variable(ID,ExpectedType).
1334 get_expected_type(ID,constant,ExpectedType) :- bmachine_is_precompiled, b_is_constant(ID,ExpectedType).
1335
1336 % TODO: already check results, ...
1337
1338 translate_json_pred(string(PredCodes),TPred) :-
1339 OuterQuantifier = no_quantifier,
1340 % TO DO: parse in context of operation ! otherwise we get type error for pp=pp for example where pp is a parameter
1341 eval_strings:repl_parse_predicate(PredCodes,OuterQuantifier,TPred,_TypeInfo). % , print(pred_ok(TPred)),nl.
1342
1343 /*
1344 after reading a JSON ProB2-UI file looks like this:
1345
1346 json([description=string([70,105,108,101,32,99,114,101,97,116,101,100,32,98,121,32,80,114,111,66,32,84,99,108,47,84,107]),transitionList=array([json([name=string([36,105,110,105,116,105,97,108,105,115,101,95,109,97,99,104,105,110,101]),params=json([]),results=json([]),destState=json([active=string([123,125]),ready=string([123,125]),waiting=string([123,125])]),destStateNotChanged=array([]),preds=@(null)]),json([name=string([110,101,119]),params=json([pp=string([112,114,111,99,101,115,115,51])]),results=json([]),destState=json([waiting=string([123,112,114,111,99,101,115,115,51,125])]),destStateNotChanged=array([string([97,99,116,105,118,101]),string([114,101,97,100,121])]),preds=@(null)]),json([name=string([114,101,97,100,121]),params=json([rr=string([112,114,111,99,101,115,115,51])]),results=json([]),destState=json([active=string([123,112,114,111,99,101,115,115,51,125]),waiting=string([123,125])]),destStateNotChanged=array([string([114,101,97,100,121])]),preds=@(null)]),json([name=string([115,119,97,112]),params=json([]),results=json([]),destState=json([active=string([123,125]),waiting=string([123,112,114,111,99,101,115,115,51,125])]),destStateNotChanged=array([string([114,101,97,100,121])]),preds=@(null)]),json([name=string([110,101,119]),params=json([pp=string([112,114,111,99,101,115,115,50])]),results=json([]),destState=json([waiting=string([123,112,114,111,99,101,115,115,50,44,112,114,111,99,101,115,115,51,125])]),destStateNotChanged=array([string([97,99,116,105,118,101]),string([114,101,97,100,121])]),preds=@(null)])]),metadata=json([fileType=string([84,114,97,99,101]),formatVersion=number(1),savedAt=string([50,48,50,49,45,49,48,45,49,51,84,49,51,58,51,56,58,48,50,90]),creator=string([116,99,108,116,107,32,40,108,101,117,115,99,104,101,108,41]),proBCliVersion=string([49,46,49,49,46,49,45,110,105,103,104,116,108,121]),proBCliRevision=string([51,99,98,56,48,48,98,98,97,100,102,101,97,102,52,102,53,56,49,51,50,55,50,52,53,53,48,55,97,53,53,97,101,53,97,53,101,54,54,100]),modelName=string([115,99,104,101,100,117,108,101,114]),modelFile=string([47,85,115,101,114,115,47,108,101,117,115,99,104,101,108,47,103,105,116,95,114,111,111,116,47,112,114,111,98,95,101,120,97,109,112,108,101,115,47,112,117,98,108,105,99,95,101,120,97,109,112,108,101,115,47,66,47,66,101,110,99,104,109,97,114,107,115,47,115,99,104,101,100,117,108,101,114,46,109,99,104])])])
1347
1348 */
1349
1350 % -------------------------
1351
1352 % Interactive Trace Replay API
1353
1354 % load a trace file and store it for interactive replay
1355 load_json_trace_file_for_ireplay(FileName) :-
1356 read_json_trace_file(FileName,ModelName,Trace),
1357 reset_json_trace_replay,
1358 store_json_trace(Trace,0,Len),
1359 assert(current_replay_step(1)),
1360 assert(loaded_json_trace_file(FileName,ModelName,Len)).
1361
1362 :- dynamic loaded_json_trace_file/3, json_trace_replay_step/3.
1363 :- dynamic current_replay_step/1, json_trace_replayed_info/2.
1364
1365
1366 :- use_module(eventhandling,[register_event_listener/3]).
1367 :- register_event_listener(clear_specification,reset_json_trace_replay,
1368 'Reset interactive trace replay.').
1369
1370 reset_json_trace_replay :-
1371 retractall(current_replay_step(_)),
1372 retractall(loaded_json_trace_file(_,_,_)),
1373 retractall(json_trace_replay_step(_,_,_)),
1374 retractall(json_trace_replayed_info(_,_)).
1375
1376 store_json_trace([],L,L).
1377 store_json_trace([TransSpec|T],StepNr,Len) :-
1378 S1 is StepNr + 1,
1379 get_transition_spec_txt(TransSpec,TTxt),
1380 formatsilent_with_colour(user_output,[blue],'==> Trace step ~w: ~w~n',[S1,TTxt]),
1381 phrase(check_and_adapt_trace_step(TransSpec,S1,CorrectedTransSpec),StaticErrors),
1382 assert(json_trace_replay_step(S1,CorrectedTransSpec,StaticErrors)),
1383 store_json_trace(T,S1,Len).
1384
1385 get_trace_step_info(StepNr,StepDescr) :-
1386 json_trace_replay_step(StepNr,TransSpec,StaticErrors),
1387 get_transition_spec_txt(TransSpec,TTxt),
1388 (StaticErrors = [] -> StaticTT=[]
1389 ; length(StaticErrors,NrStaticErrors),
1390 StaticTT = [' (static errors: ',NrStaticErrors,')']
1391 ),
1392 (json_trace_replayed_info(StepNr,Info),
1393 get_replay_info_text(Info,TextAtoms)
1394 -> append(StaticTT,TextAtoms,TT),
1395 ajoin([StepNr,': ',TTxt | TT],StepDescr)
1396 ; ajoin([StepNr,': ',TTxt | StaticTT],StepDescr)
1397 ).
1398
1399 get_replay_info_text(replay(FromID,TransID,MatchInfo,Errors),TextAtoms) :-
1400 transition(FromID,OperationTerm,TransID,_ToID),
1401 translate_event_with_limit(OperationTerm,40,OpTxt),
1402 !,
1403 (Errors=[] -> TextAtoms = [' * REPLAYED (', MatchInfo,') : ',OpTxt]
1404 ; length(Errors,NrErrors),
1405 TextAtoms = [' * REPLAYED (', MatchInfo, ', errors: ',NrErrors,') : ', OpTxt]
1406 ).
1407 get_replay_info_text(skipped,[' SKIPPED']) :- !.
1408 get_replay_info_text(X,[X]).
1409
1410 tk_get_stored_json_trace_description(list(List)) :-
1411 findall(StepDescr,get_trace_step_info(_,StepDescr),List).
1412
1413 get_stored_json_replay_steps(List) :-
1414 findall(ireplay_step(StepNr,TTxt,StaticErrors),
1415 (json_trace_replay_step(StepNr,TransSpec,RErrors),
1416 maplist(get_rerror,RErrors,StaticErrors),
1417 get_transition_spec_txt(TransSpec,TTxt)),
1418 List).
1419
1420 try_replay_next_step(MatchSpecs,CurStepNr,FromID,TransID,DestId,MatchInfo,TkTransInfos,TkErrors) :-
1421 (var(CurStepNr) -> current_replay_step(CurStepNr) ; true), % allow to pass a fixed Nr from ProB2
1422 (var(FromID) -> current_state_id(FromID) ; true), % allow to pass a fixed ID from ProB2
1423 json_trace_replay_step(CurStepNr,TransSpec,StaticErrors),
1424 flexible_perform_single_replay_step(FromID,TransID,DestId,MatchSpecs,TransSpec,MatchInfo),
1425 phrase(check_step_postconditions(TransSpec,DestId),Errors,StaticErrors),
1426 get_transition_name(FromID,TransID,OpName),
1427 length(Errors,NrErrs),
1428 formatsilent_with_colour(user_output,[green], '==> Replay step ~w (~w) ~w leading to state ~w~n',[CurStepNr,MatchInfo,OpName,DestId]),
1429 (NrErrs>0 -> formatsilent_with_colour(user_output,[orange],' Errors (~w): ~w~n',[NrErrs,Errors]) ; true),
1430 findall(TInfo,get_transition_info(TransSpec,TInfo),TkTransInfos),
1431 maplist(get_rerror,Errors,TkErrors). % make errors atomic for Tk
1432
1433 get_rerror(Err,Msg) :- get_replay_error(Err,Msg),!.
1434 get_rerror(Err,Msg) :- atom(Err),!,Msg=Err.
1435 get_rerror(Err,F) :- functor(Err,F,_).
1436
1437 :- use_module(translate,[translate_bexpression_with_limit/3]).
1438 % get text descriptions for a transition_spec, to be shown to user e.g. in Tk listbox:
1439 get_transition_info(transition_spec(_Op, _Meta, Paras, Results, DestStore,_UnchangedVars,_Preds,_Post),InfoTxt) :-
1440 (Kind=para, List=Paras
1441 ; Kind=result, List=Results
1442 ; Kind=dest, List=DestStore),
1443 get_binding_txt(List,Txt),
1444 ajoin([Kind,' : ',Txt],InfoTxt).
1445 get_transition_info(transition_spec(_Op, _, _, _, _,UnchangedVars,_,_),InfoTxt) :-
1446 member(ID,UnchangedVars),
1447 ajoin(['unchanged : ',ID],InfoTxt).
1448 get_transition_info(transition_spec(_Op, _, _, _, _,_,Preds,_),InfoTxt) :-
1449 member(TP,Preds),
1450 translate_bexpression_with_limit(TP,250,TPS),
1451 ajoin(['pred : ',TPS],InfoTxt).
1452
1453 get_binding_txt(List,BindingText) :-
1454 member(json_bind(Var,Value,_ValType,_ValPos),List),
1455 translate_bvalue_with_limit(Value,200,VS),
1456 ajoin([Var,'=',VS],BindingText).
1457
1458 default_match_specs([MatchSpec,MS2,MS3]) :-
1459 precise_match_spec(MatchSpec), % require precise replay
1460 ignore_dest_match_spec(MS2),
1461 opname_optimize_match_spec(MS3).
1462
1463 % expected options: precise, params_and_results, keep_name
1464 get_match_specs(precise,MS) :- !,
1465 precise_match_spec(MS1),
1466 MS=[MS1]. % allow only precise replay
1467 get_match_specs(params_and_results,MS) :- !,
1468 precise_match_spec(MS1),
1469 ignore_dest_match_spec(MS2),
1470 MS=[MS1,MS2]. % allow precise and params_and_results
1471 get_match_specs(_,MS) :- default_match_specs(MS). % allow all match_specs, including keep_name
1472
1473 %:- public ireplay/0.
1474 %ireplay :- default_match_specs(MS),
1475 % ireplay(MS).
1476 %
1477 %
1478 %ireplay(MatchSpecs) :-
1479 % replay_current_step(MatchSpecs,_),!,
1480 % ireplay(MatchSpecs).
1481 %ireplay(MatchSpecs) :-
1482 % skip_current_ireplay_step(_),
1483 % ireplay(MatchSpecs).
1484
1485 % get information about how the status of replaying a loaded trace is:
1486 get_ireplay_status(CurStepNr,Steps,Finished) :-
1487 loaded_json_trace_file(_,_,Steps),
1488 current_replay_step(CurStepNr),
1489 (CurStepNr =< Steps
1490 -> Finished=not_finished
1491 ; Finished=finished).
1492
1493 replay_of_current_step_is_possible(CurStepNr,OpName,MatchInfo,list(TransInfos),list(Errors)) :- % Tk
1494 default_match_specs(MS),
1495 try_replay_next_step(MS,CurStepNr,FromID,TransID,_DestId,MatchInfo,TransInfos,Errors),
1496 get_transition_name(FromID,TransID,OpName).
1497
1498 replay_of_current_step_is_possible_with_trans(CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)) :-
1499 default_match_specs(MS),
1500 replay_of_current_step_is_possible_with_trans_aux(MS,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)).
1501
1502 replay_of_current_step_is_possible_with_trans(MatchOption,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)) :- % ProB2
1503 get_match_specs(MatchOption,MS),
1504 replay_of_current_step_is_possible_with_trans_aux(MS,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)).
1505
1506 replay_of_current_step_is_possible_with_trans_aux(MatchSpec,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)) :-
1507 try_replay_next_step(MatchSpec,CurStepNr,FromID,TransID,DestID,MatchInfo,_TransInfos,Errors),
1508 create_op_transition(FromID,TransID,DestID,OpTerm).
1509
1510 create_op_transition(FromID,TransID,DestID,op(TransID,OpName,FromID,DestID)) :-
1511 get_transition_name(FromID,TransID,OpName).
1512
1513 % try and replay as much as possible
1514 ireplay_fast_forward(NrReplayed) :-
1515 default_match_specs(MS), ireplay_fast_forward(MS,0,NrReplayed).
1516
1517 ireplay_fast_forward(MatchSpecs,Nr,NrReplayed) :-
1518 replay_current_step(MatchSpecs,_),!,
1519 N1 is Nr+1,
1520 ireplay_fast_forward(MatchSpecs,N1,NrReplayed).
1521 ireplay_fast_forward(_,NrReplayed,NrReplayed).
1522
1523 ireplay_fast_forward_with_trans(CurStepNr,FromID,NrReplayed,Transitions,MatchInfos,Errors) :-
1524 default_match_specs(MS),
1525 ireplay_fast_forward_with_trans_aux(MS,CurStepNr,FromID,0,NrReplayed,Transitions,MatchInfos,Errors).
1526
1527 ireplay_fast_forward_with_trans(MatchOption,CurStepNr,FromID,NrReplayed,Transitions,MatchInfos,Errors) :- % for ProB2
1528 get_match_specs(MatchOption,MS),
1529 ireplay_fast_forward_with_trans_aux(MS,CurStepNr,FromID,0,NrReplayed,Transitions,MatchInfos,Errors).
1530
1531 ireplay_fast_forward_with_trans_aux(MS,CurStepNr,FromID,Nr,NrReplayed,[OpTerm|T1],[MatchInfo|M1],[Errors|E1]) :-
1532 replay_current_step_with_trans(MS,CurStepNr,FromID,OpTerm,MatchInfo,Errors),!,
1533 OpTerm = op(_,_,_,DestID),
1534 N1 is Nr+1,
1535 NextStepNr is CurStepNr+1,
1536 ireplay_fast_forward_with_trans_aux(MS,NextStepNr,DestID,N1,NrReplayed,T1,M1,E1).
1537 ireplay_fast_forward_with_trans_aux(_,_,_,NrReplayed,NrReplayed,[],[],[]).
1538
1539 % replay the currently selected step of the JSON trace, matching one step of the trace with one animation step
1540 replay_current_step(CurStepNr) :- % Tk
1541 default_match_specs(MS), replay_current_step(MS,CurStepNr).
1542
1543 % try and replay current step according to match specifications
1544 replay_current_step(MatchSpecs,CurStepNr) :-
1545 try_replay_next_step(MatchSpecs,CurStepNr,FromID,TransID,_DestID,MatchInfo,_,Errors),!,
1546 extend_trace_by_transition_ids([TransID]), % update state space
1547 assert(json_trace_replayed_info(CurStepNr,replay(FromID,TransID,MatchInfo,Errors))),
1548 increase_step_nr.
1549
1550 %replay_current_step_with_trans(FromID,OpTerm,MatchInfo,Errors) :- % ProB2
1551 % default_match_specs(MS),
1552 % replay_current_step_with_trans(MS,FromID,OpTerm,MatchInfo,Errors).
1553 replay_current_step_with_trans(MatchSpecs,CurStepNr,FromID,OpTerm,MatchInfo,Errors) :- % ProB2
1554 try_replay_next_step(MatchSpecs,CurStepNr,FromID,TransID,DestID,MatchInfo,_,Errors),!,
1555 create_op_transition(FromID,TransID,DestID,OpTerm).
1556
1557 % skip the current replay step and go to the next one
1558 skip_current_ireplay_step(CurStepNr) :-
1559 current_replay_step(CurStepNr),
1560 json_trace_replay_step(CurStepNr,TransSpec,_StaticErrors),
1561 get_transition_spec_txt(TransSpec,TTxt),
1562 formatsilent_with_colour(user_output,[orange],'Skipping replay step ~w : ~w~n',[CurStepNr,TTxt]),
1563 assert(json_trace_replayed_info(CurStepNr,skipped)),
1564 increase_step_nr.
1565
1566 increase_step_nr :-
1567 retract(current_replay_step(CurStepNr)),
1568 S1 is CurStepNr+1,
1569 assert(current_replay_step(S1)).
1570
1571 % :- b_intelligent_trace_replay:load_json_trace_file_for_interactive_replay('/Users/leuschel/git_root/prob_examples/public_examples/B/CBC/ConstantsAndVars/MyAwesomeLift.prob2trace'), b_intelligent_trace_replay:ireplay.
1572
1573
1574