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