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(self_check). % needed before the first assert_must_succeed
42 :- use_module(probsrc(state_space), [extend_trace_by_transition_ids/1]).
43 :- use_module(tools_json).
44
45 % A single step is a list of informations about the step
46 % name/OperationName
47 % paras/List of =(Name,Value)
48
49 % TO DO: for match_spec use mutable counter for number of matches instead of used parameter
50
51 :- use_module(tcltk_interface,[compute_all_transitions_if_necessary/2]).
52
53 :- use_module(probsrc(bmachine),[b_get_operation_non_det_modifies/2, b_is_operation_name/1]).
54 :- use_module(probsrc(bsyntaxtree), [def_get_texpr_id/2, get_texpr_ids/2, get_texpr_id/2, get_texpr_type/2]).
55 :- use_module(probsrc(tools_matching), [get_possible_fuzzy_matches_completions_and_inner_msg/3]).
56 :- use_module(probsrc(b_interpreter),[b_test_boolean_expression_for_ground_state/5]).
57
58 perform_single_replay_step(FromID,TransID,DestID,MatchSpec,TransSpec) :-
59 %format('* FROM: ~w ',[FromID]),portray_match_spec(MatchSpec),nl,
60 ? (match_spec_has_optimize_field(MatchSpec)
61 -> findall(sol(MM,TID,DID),
62 perform_single_replay_step_statespace(FromID,TID,DID,MatchSpec,TransSpec,MM),
63 Sols),
64 mark_match_spec_as_used(MatchSpec),
65 length(Sols,NrSols),
66 min_member(sol(Mismatches,TransID,DestID),Sols),
67 debug_format(19,'Min. nr of mismatches found ~w among ~w candidate steps (starting from state ~w). ~n',[Mismatches,NrSols,FromID])
68 ; % just find first solution:
69 ? perform_single_replay_step_statespace(FromID,TransID,DestID,MatchSpec,TransSpec,_)
70 ).
71 perform_single_replay_step(FromID,TransID,DestID,MatchSpec,TransSpec) :-
72 ? perform_single_replay_step_by_pred(FromID,TransID,DestID,MatchSpec,TransSpec).
73
74
75
76
77 % Assumption: ParaStore and ResultStore are sorted
78 % returns the number of mismatches for those Keys marked as optimize
79 perform_single_replay_step_statespace(FromID,TransID,DestID,
80 MatchSpec,
81 transition_spec(OpName, _, ParaStore, ResultStore, DestStore, UnchangedVars, Preds, _Postconditions),
82 Mismatches) :-
83 mark_match_spec_as_used(MatchSpec),
84 get_opt_match_spec_val(opname,MatchSpec,OpMatch),
85 compute_all_transitions_if_necessary(FromID,false), % could be made optional
86 (OpMatch==match -> TOpName=OpName ; true),
87 ? get_sorted_transition_details(FromID,TransID,DestID,TOpName,FullParaStore,FullResultStore),
88 (xtl_mode
89 -> transition(FromID,OpTerm,TransID,DestID),
90 ground(OpTerm) % if not ground: fail here and try to instantiate non-ground params by replay by predicate
91 ; true),
92 (TOpName=OpName -> MM0 = 0 ; MM0=1, assert_mismatch(OpMatch)),
93 count_store_mismatches(FullParaStore,ParaStore,paras,MatchSpec,MM0,MM1), % check if parameters match
94 count_store_mismatches(FullResultStore,ResultStore,results,MatchSpec,MM1,MM2), % check if operation return values match
95 get_unchanged_store(FromID,UnchangedVars,UnchangedStore),
96 (DestStore=[], UnchangedStore=[]
97 -> MM6=MM2
98 ; % check if variables in destination state match
99 visited_expression(DestID,DestState),
100 get_dest_store(DestState,FullDestStore),
101 count_store_mismatches(FullDestStore,DestStore,dest,MatchSpec,MM2,MM3),
102 count_store_mismatches(FullDestStore,UnchangedStore,unchanged,MatchSpec,MM3,MM4),
103 (b_or_z_mode, get_match_spec_val(nondet_vars,MatchSpec,_)
104 -> b_get_op_non_det_modifies(OpName,NonDetModifies),
105 include(b_intelligent_trace_replay:bind_id_is_element_of(NonDetModifies),DestStore,D1),
106 count_store_mismatches(FullDestStore,D1,nondet_vars,MatchSpec,MM4,MM5),
107 include(b_intelligent_trace_replay:bind_id_is_element_of(NonDetModifies),UnchangedStore,D2),
108 count_store_mismatches(FullDestStore,D2,nondet_vars,MatchSpec,MM5,MM6)
109 ; MM6=MM4
110 )
111 ),
112 Mismatches = MM6,
113 (Preds=[] -> true
114 ; get_match_spec_val(preds,MatchSpec,match)
115 -> bsyntaxtree:conjunct_predicates(Preds,Pred),
116 debug_format(9,'Testing preds in destination state ~w after ~w~n',[DestID,FromID]),
117 % TODO: insert_before_substitution_variables for $0 vars; check that it is consistent with Tcl/Tk and ProB2-UI
118 % maybe use annotate_becomes_such_vars or find_used_primed_ids
119 append(FullResultStore,FullParaStore,LocalStore),
120 % evaluate in the full destination state (with constants); FullDestStore is only computed if the trace step
121 % contains destination or unchanged variables and only contains the variables
122 get_dest_store_for_preds(DestID,PredDestStore),
123 b_test_boolean_expression_for_ground_state(Pred,LocalStore,PredDestStore,'trace replay', OpName)
124 ; true
125 ).
126
127 node_not_fully_explored(FromID,OpName) :-
128 (max_reached_for_node(FromID)
129 ; not_all_transitions_added(FromID)
130 ; not_interesting(FromID)
131 ; time_out_for_node(FromID,OpName,_)).
132
133 :- use_module(probsrc(preferences),[get_time_out_preference_with_factor/2]).
134 % lookup in state space failed; try perform by predicate
135 % Note: does not use optimize keys (yet), only match keys
136 perform_single_replay_step_by_pred(FromID,TransID,DestID,
137 MatchSpec,
138 transition_spec(OpName, _, ParaStore, ResultStore, DestStore, UnchangedVars, Preds,
139 _Postconditions)) :-
140 nonvar(OpName), % we currently cannot execute by predicate without knowing OpName
141 ? ((node_not_fully_explored(FromID,OpName) ; xtl_mode) -> true % TODO: improve max_reached_for_node for xtl_mode
142 ; debug_format(19,'Node ~w fully explored for ~w; no use in attempting execute by predicate~n',[FromID,OpName]),
143 fail
144 ),
145 mark_match_spec_as_used(MatchSpec),
146 !,
147 (ParaStore \= [], % check parameters of operation
148 get_match_spec_val(paras,MatchSpec,match)
149 -> b_get_operation_typed_paras(OpName,Paras1),
150 (xtl_mode, Paras1=[] % XTL special case: no custom param names found; use default from ParaStore: para1, para2, ...
151 -> findall(b(identifier(Para),string,[]),(member(B,ParaStore),b_intelligent_trace_replay:is_bind(B,Para,_)),Paras2)
152 ; Paras2=Paras1),
153 ? generate_predicates_from_store(operation_parameters,Paras2,ParaStore,ParaPreds)
154 ; ParaPreds = []),
155 (ResultStore \= [], % check return values of operation
156 get_match_spec_val(results,MatchSpec,match)
157 -> b_get_operation_typed_results(OpName,Results),
158 generate_predicates_from_store(operation_results,Results,ResultStore,ResultPreds)
159 ; ResultPreds = []),
160 get_machine_identifiers(OpName,TVars),
161 (DestStore = [] -> DestPreds=[]
162 ; get_match_spec_val(dest,MatchSpec,match)
163 ? -> generate_predicates_from_store(dest_variables,TVars,DestStore,DestPreds)
164 ; get_match_spec_val(nondet_vars,MatchSpec,match)
165 -> b_get_op_non_det_modifies(OpName,NonDetModifies),
166 include(b_intelligent_trace_replay:id_is_element_of(NonDetModifies),TVars,NDVars),
167 generate_predicates_from_store(non_det_vars,NDVars,DestStore,DestPreds)
168 ; DestPreds=[]
169 ),
170 get_unchanged_store(FromID,UnchangedVars,UnchangedStore),
171 (UnchangedStore = [] -> UnchangedPreds=[]
172 ; get_match_spec_val(unchanged,MatchSpec,match) ->
173 ? generate_predicates_from_store(unchanged_vars,TVars,UnchangedStore,UnchangedPreds)
174 ; get_match_spec_val(nondet_vars,MatchSpec,match) ->
175 % NonDetModifies is only computed above if DestStore is not empty
176 (var(NonDetModifies) -> b_get_op_non_det_modifies(OpName,NonDetModifies) ; true),
177 include(b_intelligent_trace_replay:id_is_element_of(NonDetModifies),TVars,NDVars),
178 ? generate_predicates_from_store(non_det_vars,NDVars,UnchangedStore,UnchangedPreds)
179 ; UnchangedPreds=[]
180 ),
181 (get_match_spec_val(preds,MatchSpec,match) -> AddPreds=Preds ; AddPreds=[]),
182 append([ParaPreds,ResultPreds,DestPreds,UnchangedPreds,AddPreds],AllPreds),
183 conjunct_predicates(AllPreds,Pred),
184 (debug_mode(off) -> true
185 ; format('Trying to execute ~w in state ~w by predicate: ',[OpName,FromID]),
186 translate:print_bexpr(Pred),nl,flush_output),
187 get_time_out_preference_with_factor(5,TO), % TODO: store this in meta JSON info or options
188 safe_time_out(tcltk_interface:tcltk_add_user_executed_operation_typed(OpName,FromID,_,Pred,TransID,DestID),
189 TO, TimeOutRes),
190 (TimeOutRes = time_out
191 -> format_with_colour(user_output,[orange],'==> Timeout when executing ~w by predicate in state ~w~n',[OpName,FromID]),fail
192 ; true),
193 (xtl_mode
194 -> % In XTL mode we cannot describe the dest state using the DestPreds from above because 'xtl_state' is not a valid identifier.
195 % Preliminary solution: force a precise state match for dest/match as in perform_single_replay_step_statespace.
196 visited_expression(DestID,DestState),
197 get_dest_store(DestState,FullDestStore),
198 count_store_mismatches(FullDestStore,DestStore,dest,MatchSpec,_,_) % fails if there is a mismatch for dest/match
199 ; true).
200
201 get_unchanged_store(_,[],UnchangedStore) :- !, UnchangedStore=[].
202 get_unchanged_store(FromID,UnchangedVars,UnchangedStore) :-
203 % copy old values to UnchangedStore
204 visited_expression(FromID,FromState),
205 extract_variables_from_state(FromState,FullFromStore),
206 sort(FullFromStore,SortedStore),
207 % TODO: generate warning when unchanged variable does not exist?
208 include(b_intelligent_trace_replay:bind_id_is_element_of(UnchangedVars),SortedStore,UnchangedStore).
209
210 :- use_module(library(codesio),[write_term_to_codes/3]).
211 generate_predicate_from_bind(Kind,TypedIDs,json_bind(ID,Val,Type,Pos),b(Res,pred,[])) :-
212 ? (member(b(identifier(ID),ExpectedType,_),TypedIDs) ->
213 (unify_types_strict(ExpectedType,Type)
214 -> TID = b(identifier(ID),ExpectedType,[]),
215 (xtl_mode
216 -> (write_term_to_codes(Val,ValC,[quoted(true),ignore_ops(true)]),
217 atom_codes(ValA,ValC),
218 TVal = b(external_function_call('STRING_TO_TERM',[b(string(ValA),string,[])]),ExpectedType,[]))
219 ; TVal = b(value(Val),ExpectedType,[])),
220 Res = equal(TID,TVal)
221 ; pretty_type(ExpectedType,ETS), pretty_type(Type,TS), debug_println(9,clash(Kind,ID,ETS,TS)),
222 % error should probably be caught earlier:
223 add_warning(b_intelligent_trace_replay,'Ignoring value for stored identifier due to type clash: ',ID,Pos),
224 Res = truth
225 )
226 ; % the identifier is not in the list and should be ignored here; sanity checks are made somewhere else
227 Res = truth
228 ).
229 generate_predicate_from_bind(Kind,TypedIDs,bind(ID,Val),R) :- % bind without type infos, e.g., from unchanged store
230 ? generate_predicate_from_bind(Kind,TypedIDs,json_bind(ID,Val,any,unknown),R).
231
232 generate_predicates_from_store(Kind,TVars,DestStore,DestPreds) :-
233 ? maplist(b_intelligent_trace_replay:generate_predicate_from_bind(Kind,TVars),DestStore,DestPreds).
234
235 get_machine_identifiers(_,[]) :- \+ b_or_z_mode, !.
236 get_machine_identifiers(Op,TConsts) :- is_setup_constants_op(Op), !, b_get_machine_constants(TConsts).
237 get_machine_identifiers(_,TVars) :- b_get_machine_variables(TVars).
238
239 is_setup_constants_op('$setup_constants').
240 is_setup_constants_op('$partial_setup_constants').
241
242 b_get_op_non_det_modifies(_,[]) :- \+ b_or_z_mode, !.
243 b_get_op_non_det_modifies(Op,NonDetModifies) :- is_setup_constants_op(Op),
244 !,% return all constants as non-det modifies
245 b_get_machine_constants(TConsts),get_texpr_ids(TConsts,ND),
246 sort(ND,NonDetModifies).
247 b_get_op_non_det_modifies(OpName,NonDetModifies) :- b_get_operation_non_det_modifies(OpName,NonDetModifies).
248
249 fix_operation_name(OpName,OpName2) :- \+ b_is_operation_name(OpName),
250 fix_operation_name2(OpName,OpName2).
251 fix_operation_name2('SETUP_CONSTANTS','$setup_constants').
252 fix_operation_name2('INITIALISATION','$initialise_machine').
253 % TODO: maybe provide more automatic fixes, list of automatic re-names when parameters stay identical,...
254
255 % wrappers to deal with a few special transitions; TO DO: extend for CSP||B
256 b_get_operation_typed_results('$setup_constants',Results) :- !,
257 Results=[]. % for trace replay we assume setup_constants to have no result variables
258 b_get_operation_typed_results('$initialise_machine',Results) :- !, Results=[]. % ditto
259 b_get_operation_typed_results('$partial_setup_constants',Results) :- !, Results=[]. % ditto
260 b_get_operation_typed_results(OpName,Results) :- b_or_z_mode, !, b_get_machine_operation_typed_results(OpName,Results).
261 b_get_operation_typed_results(_,[]).
262
263 b_get_operation_typed_paras('$setup_constants',Paras) :- !,
264 Paras=[]. % for trace replay we assume setup_constants to have no parameters
265 b_get_operation_typed_paras('$initialise_machine',Paras) :- !, Paras=[]. % ditto
266 b_get_operation_typed_paras('$partial_setup_constants',Paras) :- !, Paras=[]. % ditto
267 b_get_operation_typed_paras(OpName,Paras) :- b_or_z_mode,!,
268 b_get_machine_operation_typed_parameters_for_animation(OpName,Paras).
269 b_get_operation_typed_paras(OpName,Paras) :- xtl_mode,!,
270 xtl_interface:get_xtl_paras_as_identifiers(OpName,Paras).
271 b_get_operation_typed_paras(OpName,[]) :-
272 add_message(replay_json_trace_file,'Not in B mode, cannot obtain parameter info for: ',OpName).
273
274 % -------------------
275
276 % now a version with multiple MatchSpecs to be tried in order
277 % Flag can be used to see how many alternatives were tried
278 flexible_perform_single_replay_step(FromID,TransID,DestID,[MatchSpec1|TMS],TransitionSpec,MName) :-
279 skip_match_spec(FromID,TransitionSpec,MatchSpec1),!,
280 debug_println(9,skipping_redundant_failing_check(MatchSpec1)),
281 flexible_perform_single_replay_step(FromID,TransID,DestID,TMS,TransitionSpec,MName).
282 flexible_perform_single_replay_step(FromID,TransID,DestID,[MatchSpec1|TMS],TransitionSpec,MName) :-
283 ? if(perform_single_replay_step(FromID,TransID,DestID,MatchSpec1,TransitionSpec),
284 get_match_spec_txt(MatchSpec1,MName),
285 ? flexible_perform_single_replay_step(FromID,TransID,DestID,TMS,TransitionSpec,MName)
286 ).
287
288 % -------------------
289
290
291 % we only assert mismatches; if a variable remains untouched we matched perfectly
292 assert_mismatch(Var) :- var(Var),!, Var=optimize.
293 assert_mismatch(require_mismatch). % probably not useful; difficult to support by predicate
294 assert_mismatch(optimize).
295
296 precise_match_spec(match_spec(_,precise,KeyVals)) :-
297 KeyVals = [dest/match,opname/match,paras/match,preds/match,results/match,unchanged/match].
298 ignore_dest_match_spec(match_spec(_,params_and_results,KeyVals)) :-
299 KeyVals = [opname/match,paras/match,preds/match,results/match,nondet_vars/match,dest/optimize,unchanged/optimize].
300 %ignore_return_match_spec(match_spec(_,parameters_only,KeyVals)) :-
301 % KeyVals = [opname/match,paras/match,results/optimize,nondet_vars/optimize].
302 opname_optimize_match_spec(match_spec(_,keep_name,KeyVals)) :-
303 KeyVals = [opname/match,paras/optimize,results/optimize,nondet_vars/optimize,dest/optimize,unchanged/optimize].
304
305 % conditions on when to skip certain match_specs
306 % (we assume that the precise_match_spec was tried before)
307 skip_match_spec(root,TS,match_spec(_,params_and_results,_)) :- get_transition_spec_op(TS,'$setup_constants').
308 % for setup_constants: nondet_vars are all constants; so this is equivalent to precise
309 % for initialise_machine: paras are all variables
310 skip_match_spec(_,TS,match_spec(_,MS,_)) :- MS \= precise,
311 get_transition_spec_meta(TS,Meta),
312 % for an unknown operation we only try a precise replay (e.g., if operation just renamed), otherwise we skip it
313 member(unknown_operation/_,Meta).
314 % TODO: skip parameters_only if an operation has not results and no nondet_vars
315
316 match_spec_was_used(match_spec(UsedFlag,_,_)) :- UsedFlag==used.
317 mark_match_spec_as_used(match_spec(used,_,_)).
318
319 get_match_spec_txt(match_spec(_,Name,_),Name).
320 ?get_match_spec_val(Key,match_spec(_,_,List),Res) :- member(Key/Val,List),!,Res=Val.
321
322 get_opt_match_spec_val(Key,MS,Res) :- get_match_spec_val(Key,MS,Val),!, Res=Val.
323 get_opt_match_spec_val(_,_,optimize).
324
325 % check if it is useful to optimize the mismatches
326 ?match_spec_has_optimize_field(match_spec(_,_,KeyVals)) :- member(_/optimize,KeyVals).
327
328 :- public valid_match_spec_key/1.
329 valid_match_spec_key(dest).
330 valid_match_spec_key(nondet_vars).
331 valid_match_spec_key(opname).
332 valid_match_spec_key(paras).
333 valid_match_spec_key(results).
334 valid_match_spec_key(unchanged).
335
336 :- public portray_match_spec/1.
337 portray_match_spec(match_spec(UsedFlag,Name,List)) :-
338 (UsedFlag==used -> U=used ; U=not_yet_used),
339 format('~w (~w): ~w~n',[Name,U,List]).
340
341 % -------------------
342
343 % the store used to evaluate predicates of a trace step in the destination state
344 get_dest_store_for_preds(DestID,Store) :-
345 visited_expression(DestID,DestState),
346 (b_or_z_mode -> expand_const_and_vars_to_full_store(DestState,Store) ; get_dest_store(DestState,Store)).
347
348 get_dest_store(concrete_constants(C),SC) :- !, sort(C,SC).
349 get_dest_store(Store,Vars) :- b_or_z_mode,!, extract_variables_from_state(Store,Vars).
350 get_dest_store(State,XTLState) :- xtl_mode, !, XTLState = [bind(xtl_state,State)]. % special identifier xtl_state only exists in JSON traces
351 get_dest_store(_,[]). % CSP,... has no concept of variables
352
353
354 % count the number of mismatches for a given key and MatchSpec
355 % if MatchSpec requires match (perfect match) it will fail if Mismatches are 0
356 % it accumulates the global number of mismatches in a DCG style accumulator
357 count_store_mismatches(FullStore,PartialStore,Key,MatchSpec,MismatchesIn,MismatchesOut) :-
358 get_match_spec_val(Key,MatchSpec,MatchVal), !,
359 (MatchVal=match
360 -> MismatchesIn=MismatchesOut,
361 count_mismatches(FullStore,Key,PartialStore,0)
362 ; count_mismatches(FullStore,Key,PartialStore,Mismatches),
363 MismatchesOut is MismatchesIn+Mismatches,
364 %print(new_mm(MismatchesOut,Key,MatchVal,Mismatches)),nl,
365 (Mismatches=0 -> true
366 ; assert_mismatch(MatchVal))
367 ).
368 count_store_mismatches(_,_,_Key,_,M,M). % key does not exist; no matching required
369
370 % for maplist, include, exclude:
371 ?bind_id_is_element_of(Vars,Bind) :- is_bind(Bind,ID,_), member(ID,Vars). % we could use ord_member
372 id_is_element_of(Vars,TID) :- def_get_texpr_id(TID,ID), member(ID,Vars).
373
374 is_bind(bind(ID,Val),ID,Val).
375 is_bind(json_bind(ID,Val,_,_),ID,Val).
376
377 %check_no_mismatches(FullStore,Key,PartialStore) :- count_mismatches(FullStore,Key,PartialStore,0).
378
379 count_mismatches(FullStore,Key,PartialStore,Mismatches) :-
380 count_mismatches_aux(FullStore,Key,PartialStore,0,Mismatches).
381 :- use_module(probsrc(translate), [translate_bvalue_with_limit/3]).
382 % count mismatches in FullStore compared to partial reference store
383 % if result is set to 0, it will fail after first mismatch
384 count_mismatches_aux(_,_,[],Acc,Res) :- !,Res=Acc.
385 count_mismatches_aux([],Key,PartialStore,_,_) :- b_or_z_mode, !,
386 ajoin(['Saved trace step contains unknown bindings for ',Key,': '],Msg),
387 add_error(b_intelligent_trace_replay,Msg,PartialStore),
388 fail.
389 count_mismatches_aux([],Key,[_|T],Acc,Res) :- xtl_mode, !, % in XTL mode we can have multiple transitions with the same name => no error, try next for param match
390 inc_mismatches(Acc,Acc1,Res), % each remaining binding of the partial store counts as a mismatch
391 count_mismatches_aux([],Key,T,Acc1,Res).
392 count_mismatches_aux([Bind1|T],Key,[Bind2|T2],Acc,Res) :-
393 is_bind(Bind1,ID,Val), is_bind(Bind2,ID,Val2),!,
394 ? (check_value_equal(ID,Val,Val2)
395 -> count_mismatches_aux(T,Key,T2,Acc,Res)
396 ; ((debug_mode(off) ; \+ b_or_z_mode) -> true
397 ; translate_bvalue_with_limit(Val,200,V1), translate_bvalue_with_limit(Val2,200,V2),
398 formatsilent_with_colour(user_output,[red],'==> Mismatch for ~w ~w:~n ~w~n (trace) ~w~n',[Key,ID,V1,V2])
399 %nl,print(Val),nl,nl,print(Val2),nl,nl,
400 ),
401 inc_mismatches(Acc,Acc1,Res),
402 count_mismatches_aux(T,Key,T2,Acc1,Res)
403 ).
404 count_mismatches_aux([_ID|T],Key,PartialStore,Acc,Res) :- count_mismatches_aux(T,Key,PartialStore,Acc,Res).
405
406 inc_mismatches(X,_,Res) :- number(Res),X>=Res,!,fail. % X+1 would exceed Res; Res could be 0 for perfect match
407 inc_mismatches(Acc,Acc1,_) :- Acc1 is Acc+1.
408
409 % check if saved value and actual value is identical
410 :- use_module(kernel_objects,[equal_object/3]).
411 check_value_equal(ID,Val1,Val2) :-
412 temporary_set_preference(allow_enumeration_of_infinite_types,true,OldValueOfPref),
413 ? call_cleanup(check_value_equal_aux(ID,Val1,Val2),
414 reset_temporary_preference(allow_enumeration_of_infinite_types,OldValueOfPref)).
415
416 % what if trace was saved with different SYMBOLIC pref value?
417 :- use_module(b_ast_cleanup, [clean_up/3]).
418 :- use_module(custom_explicit_sets, [same_closure/2]).
419 :- use_module(debug, [debug_mode/1]).
420 check_value_equal_aux(ID,closure(P1,T1,B1),C2) :- C2 = closure(P2,T2,B2),
421 C1 = closure(P1,T1,B1),
422 !, % we have two symbolic values
423 (same_closure(C1,C2)
424 -> true
425 ; % simple comparison failed, now try and normalize the symbolic values and compare again
426 temporary_set_preference(normalize_ast,true,CHANGE),
427 % normalize_ast_sort_commutative should probably be false, unless we improve the sorting
428 %we could call: b_compiler:b_optimize_closure(closure(P1,T1,B1C),closure(P12,T12,B12),WF),
429 call_cleanup((clean_up(B1,[],B1C), clean_up(B2,[],B2C)), % call_cleanup: also restore upon exceptions
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: ',RS)),
606 exclude_and_collect_errors(unknown_variable_binding(Step,''),DestStore,DestStore2), % operation name is empty
607 exclude_and_collect_errors(unknown_variable(Step,''),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 :- assert_must_succeed((b_intelligent_trace_replay:delta_store_match([bind(b,int(2))],paras,[bind(a,int(1)),bind(b,int(2))],L,[]),
864 L==[a])). % a is missing in the full store, b matches
865 :- assert_must_succeed((b_intelligent_trace_replay:delta_store_match([bind(a,int(1)),bind(b,int(2))],paras,[bind(b,int(3))],L,[]),
866 L==[b])).
867 delta_store_match(_,_,[]) --> !.
868 delta_store_match([],_Key,Rest)
869 --> add_rest(Rest). % these bindings were probably filtered out during replay and error messages were generated
870 delta_store_match([Bind1|T],Key,[Bind2|T2]) -->
871 {is_bind(Bind1,ID,Val), is_bind(Bind2,ID,Val2)},
872 !,
873 ({check_value_equal(ID,Val,Val2)}
874 -> []
875 ; %translate_bvalue_with_limit(Val,100,V1), translate_bvalue_with_limit(Val2,100,V2),
876 [ID] % TO DO: provided detailed explanation using values
877 ),delta_store_match(T,Key,T2).
878 delta_store_match([Bind1|T],Key,[Bind2|T2]) -->
879 {is_bind(Bind1,ID1,_), is_bind(Bind2,ID2,_), ID2 @< ID1},
880 !, % ID2 of the trace step does not occur in the (sorted) full store: report it and keep Bind1 for the next entry
881 [ID2],
882 delta_store_match([Bind1|T],Key,T2).
883 delta_store_match([_ID|T],Key,PartialStore) --> delta_store_match(T,Key,PartialStore).
884
885 add_rest([]) --> [].
886 add_rest([Bind|T]) --> {is_bind(Bind,ID,_)}, [ID], add_rest(T).
887
888 % -----------------------
889
890 replay_json_trace_file(FileName,ReplayStatus) :-
891 replay_json_trace_file_with_check(FileName,_,ReplayStatus,TransIds,_),
892 try_set_trace_by_transition_ids(TransIds).
893
894
895 % generate error/warning for imperfect or partial replay
896 replay_json_trace_file_with_check(FileName,Trace,ReplayStatus,TransIds,MatchInfoList) :-
897 replay_json_trace_file(FileName,Trace,ReplayStatus,TransIds,MatchInfoList),
898 exclude(==(skip),TransIds,ReplayedTransIds), % steps that could not be replayed are skipped and marked by skip
899 length(ReplayedTransIds,Steps),
900 length(Trace,AllSteps),
901 check_replay_status(ReplayStatus,Steps,AllSteps).
902
903 check_replay_status(imperfect,Steps,_) :- !,
904 ajoin(['Imperfect replay, steps replayed: '],Msg),
905 add_warning(replay_json_trace_file,Msg, Steps).
906 check_replay_status(partial,_,0) :- !. % trace file could not be read or no specification loaded; error already reported
907 check_replay_status(partial,Steps,AllSteps) :- !,
908 ajoin(['Replay of all ',AllSteps,' steps not possible, steps replayed: '],Msg),
909 add_error(replay_json_trace_file,Msg, Steps).
910 check_replay_status(perfect,Steps,_) :-
911 add_message(replay_json_trace_file,'Perfect replay possible, steps replayed: ', Steps).
912
913 % ------------
914
915 :- use_module(tools,[start_ms_timer/1, stop_ms_timer_with_silent_msg/2,
916 stop_ms_timer_with_debug_msg/2]).
917 :- use_module(bmachine_construction,[dummy_machine_name/2]).
918
919 replay_json_trace_file(FileName,Trace,ReplayStatus,TransIds,MatchInfoList) :- \+ bmachine_is_precompiled,!,
920 add_error(replay_json_trace_file,'No specification loaded, cannot replay trace file:',FileName),
921 Trace=[], TransIds=[], ReplayStatus=partial, MatchInfoList=[].
922 replay_json_trace_file(FileName,Trace,ReplayStatus,TransIds,MatchInfoList) :-
923 start_ms_timer(T1),
924 read_json_trace_file(FileName,ModelName,Trace),
925 stop_ms_timer_with_debug_msg(T1,'loading JSON trace file'),
926 precise_match_spec(MatchSpec), % require precise replay
927 ignore_dest_match_spec(MS2),
928 opname_optimize_match_spec(MS3),
929 % was ignore_return_match_spec(MS3), % TODO: when no return and no non-det vars: do not try MS3
930 start_ms_timer(T2),
931 temporary_set_preference(deterministic_trace_replay,true,CHNG),
932 call_cleanup(replay_trace(Trace,[MatchSpec,MS2,MS3],[],1,root,TransIds,_DestID,RestTrace,MatchInfoList),
933 reset_temporary_preference(deterministic_trace_replay,CHNG)), % also restore upon failure or exceptions
934 stop_ms_timer_with_silent_msg(T2,'replaying JSON trace file'),
935 !,
936 (RestTrace = []
937 -> ((match_spec_was_used(MS3) % Grade=3
938 ; match_spec_was_used(MS2) %Grade=2
939 ? ; member(replay_step(_,Errs),MatchInfoList), replay_error_occured(Errs)
940 )
941 -> ReplayStatus=imperfect,
942 check_model_name(ModelName)
943 ; ReplayStatus=perfect
944 )
945 ; ReplayStatus=partial,
946 check_model_name(ModelName)
947 ).
948 replay_json_trace_file(_FileName,Trace,ReplayStatus,TransIds,MatchInfoList) :-
949 % the trace file could not be read or translated (error already reported): do not report a perfect replay
950 Trace=[], TransIds=[], ReplayStatus=partial, MatchInfoList=[].
951
952 :- use_module(specfile,[currently_opened_specification_name/1]).
953 check_model_name(ModelName) :-
954 currently_opened_specification_name(CurModelName),!,
955 (CurModelName=ModelName -> true
956 ; dummy_machine_name(ModelName,CurModelName) % CurModelName = MAIN_MACHINE_FOR_...
957 -> true
958 ; ModelName = 'dummy(uses)'
959 -> true % if modelName is "null" this is the value used
960 ; prob2_ui_suffix(ModelName,CurModelName) ->
961 % happens when ProB2-UI saves trace files; sometimes it adds (2), ... suffix, see issue #243
962 add_message(replay_json_trace_file, 'JSON trace file model name has a ProB2-UI suffix: ', ModelName)
963 ; ajoin(['JSON trace file model name ',ModelName,' does not match current model name: '],MMsg),
964 add_warning(replay_json_trace_file, MMsg, CurModelName)
965 ).
966 check_model_name(ModelName) :-
967 add_warning(replay_json_trace_file, 'Cannot determine current model name to check stored name:', ModelName).
968
969 :- set_prolog_flag(double_quotes, codes).
970 :- use_module(self_check).
971 :- assert_must_succeed(b_intelligent_trace_replay:prob2_ui_suffix('b_mch', 'b')).
972 :- assert_must_succeed(b_intelligent_trace_replay:prob2_ui_suffix('b_mch (2)', 'b')).
973 :- assert_must_succeed(b_intelligent_trace_replay:prob2_ui_suffix('b (2)', 'b')).
974 :- assert_must_fail(b_intelligent_trace_replay:prob2_ui_suffix('b', 'bc')).
975 :- assert_must_fail(b_intelligent_trace_replay:prob2_ui_suffix('b (2)', 'bc')).
976 % check if name matches current model name catering for ProB2-UI quirks
977 prob2_ui_suffix(JSONModelName,CurModelName) :-
978 atom_codes(JSONModelName,JCodes),
979 atom_codes(CurModelName,TargetCodes),
980 append(TargetCodes,After,JCodes),
981 (append("_mch",After2,After)
982 -> true % .eventb package file name
983 ; append(".mch",After2,After) -> true
984 ; After2=After),
985 valid_prob2_ui_suffix(After2).
986
987 valid_prob2_ui_suffix([]) :- !.
988 valid_prob2_ui_suffix([32|_]). % we could check that we have (2), ... after; but is it necessary?
989
990
991 error_occured_during_replay(MatchInfoList) :-
992 member(replay_step(_,Errs),MatchInfoList), replay_error_occured(Errs),!.
993
994 % ---------------------------------
995
996 replay_prolog_trace_file(FileName) :-
997 start_ms_timer(T1),
998 read_prolog_trace_file(FileName,_ModelName,Trace),
999 stop_ms_timer_with_debug_msg(T1,'loading Prolog trace file'),
1000 replay_prolog2(FileName,Trace).
1001
1002 replay_prolog2(FileName,Trace) :-
1003 precise_match_spec(MatchSpec),
1004 start_ms_timer(T2),
1005 replay_trace(Trace,[MatchSpec],[stop_at_failure],1,root,TransIds,_DestID,RestTrace,MatchInfoList),
1006 stop_ms_timer_with_silent_msg(T2,'replaying JSON trace file'),
1007 RestTrace=[], % will initiate backtracking
1008 try_set_trace_by_transition_ids(TransIds),
1009 (error_occured_during_replay(MatchInfoList)
1010 -> add_error(replay_prolog_trace_file,'Errors occurred during replay of file:',FileName)
1011 ; true).
1012 replay_prolog2(FileName,_Trace) :-
1013 add_error(replay_prolog_trace_file,'Could not fully replay file:',FileName).
1014
1015 read_prolog_trace_file(FileName,ModelName,Trace) :-
1016 open(FileName,read,Stream,[encoding(utf8)]),
1017 call_cleanup(parse_prolog_trace_file(FileName,Stream,ModelName,Trace),
1018 close(Stream)).
1019
1020 parse_prolog_trace_file(File,Stream,ModelName,Trace) :-
1021 safe_read_stream(Stream,0,Term),!,
1022 (Term = end_of_file
1023 -> Trace = [], ModelName = 'dummy(uses)',
1024 add_warning(read_prolog_trace_file,'Empty trace file: ',File)
1025 ; (Term = machine(ModelName)
1026 -> Trace = T
1027 ; Trace = [Term|T],
1028 add_warning(read_prolog_trace_file,'File does not start with a machine/1 fact: ',Term)
1029 ),
1030 parse_prolog_trace_file_body(Stream,1,T)
1031 ).
1032
1033 parse_prolog_trace_file_body(Stream,Step,Trace) :-
1034 safe_read_stream(Stream,Step,Term),!,
1035 (Term = end_of_file
1036 -> Trace = []
1037 ; skip_prolog_term(Term)
1038 -> add_message(read_prolog_trace_file,'Skipping: ',Term),
1039 parse_prolog_trace_file_body(Stream,Step,Trace)
1040 ; Trace = [TransSpec|T],
1041 convert_prolog_trace_step(Term,TransSpec),
1042 S1 is Step + 1,
1043 parse_prolog_trace_file_body(Stream,S1,T)
1044 ).
1045
1046 safe_read_stream(Stream,Step,T) :-
1047 catch(read(Stream,T), E, (
1048 ajoin(['Exception while reading step ', Step, ' of trace file: '], Msg),
1049 add_error(read_prolog_trace_file,Msg,[E]),
1050 T=end_of_file
1051 )).
1052
1053 skip_prolog_term('$check_value'(_ID,_Val)).
1054 convert_prolog_trace_step(Fact,
1055 transition_spec(OpName,Meta,ParaStore,ResultStore,DestStore,Unchanged,PredList,[])) :-
1056 PredList=[], Unchanged=[], Meta=[], DestStore = [],
1057 decompose_operation(Fact,OpName,ParaStore,ResultStore).
1058 % TODO: deal with '$check_value'(ID,Val)
1059 % decompose an operation term into name, parameter store and result store
1060 decompose_operation('-->'(OpTerm,Results),OpName,ParaStore,ResultStore) :- !,
1061 decompose_operation2(OpTerm,OpName,ParaStore),
1062 (b_get_machine_operation_result_names(OpName,ResultNames)
1063 -> create_sorted_store(ResultNames,Results,OpName,ResultStore)
1064 ; ResultStore = []).
1065 decompose_operation(OpTerm,OpName,ParaStore,[]) :- decompose_operation2(OpTerm,OpName,ParaStore).
1066
1067 is_setup_or_init('$initialise_machine','$initialise_machine').
1068 is_setup_or_init(initialise_machine,'$initialise_machine'). % old style
1069 is_setup_or_init(setup_constants,'$setup_constants'). % old style
1070 is_setup_or_init(Op,Op) :- is_setup_constants_op(Op).
1071
1072 decompose_operation2(OpTerm,OpName,ParaStore) :-
1073 functor(OpTerm,Functor,Arity),
1074 is_setup_or_init(Functor,OpName),
1075 !,
1076 % the order of constants, variables etc has changed in ProB;
1077 % in general we cannot reconstruct the association of the arguments to variables or constants
1078 (Arity=0 -> true
1079 ; add_message(b_intelligent_trace_replay,'Ignoring parameters of:',OpName)),
1080 ParaStore=[].
1081 decompose_operation2(OpTerm,OpName,ParaStore) :-
1082 OpTerm =.. [OpName|Paras],
1083 (b_get_machine_operation_parameter_names_for_animation(OpName,ParaNames)
1084 -> create_sorted_store(ParaNames,Paras,OpName,ParaStore)
1085 ; ParaStore = [],
1086 add_error(read_prolog_trace_file,'Unknown operation in trace file:',OpName)
1087 ).
1088
1089
1090 create_sorted_store([],Paras,OpName,SortedParaStore) :- Paras = [_|_],
1091 get_preference(show_eventb_any_arguments,false),!,
1092 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),
1093 SortedParaStore = [].
1094 create_sorted_store(ParaNames,[],_OpName,SortedParaStore) :- ParaNames = [_|_],
1095 get_preference(show_eventb_any_arguments,true),!,
1096 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),
1097 SortedParaStore = [].
1098 create_sorted_store(ParaNames,Paras,OpName,SortedParaStore) :-
1099 create_local_store_for_operation(ParaNames,Paras,OpName,ParaStore),
1100 sort(ParaStore,SortedParaStore).
1101
1102
1103
1104 % ------------------------
1105
1106 :- use_module(extrasrc(json_parser),[json_parse_file/3]).
1107
1108 % read a JSON ProB2-UI trace file and extract model name and transition_spec list
1109 read_json_trace_file(FileName,ModelName,Trace) :-
1110 json_parse_file(FileName,Term,[rest(_),position_infos(true),strings_as_atoms(false)]),
1111 %nl,print(Term),nl,nl,
1112 !,
1113 ? (extract_json_model_name(Term,M) -> ModelName=M ; ModelName = 'dummy(uses)'),
1114 ? (translate_json_trace_term(Term,FileName,Trace) -> true
1115 ; add_error(read_json_trace_file,'Could not translate JSON transitionList: ',Term),
1116 fail). % do not return an empty trace, which would be replayed perfectly
1117
1118 % --------
1119
1120 :- use_module(probsrc(preferences), [reset_temporary_preference/2,temporary_set_preference/3, get_preference/2]).
1121 translate_json_trace_term(json(ObjList),FileName,Trace) :-
1122 ? get_json_key_list(transitionList,ObjList,List),
1123 List \= [], % optimization, dont set preferences
1124 !,
1125 temporary_set_preference(repl_cache_parsing,true,CHNG),
1126 eval_strings:turn_normalising_off,
1127 % call_cleanup: also restore when translating an operation fails or raises an exception
1128 ? call_cleanup(maplist(translate_json_operation(FileName),List,Trace),
1129 (eval_strings:turn_normalising_on,
1130 reset_temporary_preference(repl_cache_parsing,CHNG))).
1131
1132 % no transitionList => just use empty list
1133 translate_json_trace_term(json(_),_,[]) :- !.
1134
1135 % extract model name from metadata which looks like this
1136 /*
1137 "metadata": {
1138 "fileType": "Trace",
1139 "formatVersion": 1,
1140 "savedAt": "2021-10-13T13:38:02Z",
1141 "creator": "tcltk (leuschel)",
1142 "proBCliVersion": "1.11.1-nightly",
1143 "proBCliRevision": "3cb800bbadfeaf4f581327245507a55ae5a5e66d",
1144 "modelName": "scheduler",
1145 "modelFile": "/Users/bourkaki/B/Benchmarks/scheduler.mch"
1146 }
1147 */
1148
1149 extract_json_model_name(json(ObjList),MachineName) :-
1150 get_json_key_object(metadata,ObjList,List),
1151 ? get_json_attribute(modelName,List,string(MC)),
1152 atom_codes(MachineName,MC).
1153
1154
1155 % translate a single JSON transition entry into a transition_spec term for replay_trace
1156 /* here is a typical entry for the scheduler model:
1157 {
1158 "name": "ready",
1159 "params": {
1160 "rr": "process3"
1161 },
1162 "results": {
1163 },
1164 "destState": {
1165 "active": "{process3}",
1166 "waiting": "{}"
1167 },
1168 "destStateNotChanged": [
1169 "ready"
1170 ],
1171 "preds": null
1172 },
1173 */
1174 translate_json_operation(FileName,json(Json),
1175 transition_spec(OpName,Meta,
1176 ParaStore,ResultStore,DestStore,Unchanged,PredList,Postconditions) ) :-
1177 ? (get_json_attribute_with_pos(name,Json,FileName,string(OpNameC),Position)
1178 -> atom_codes(OpName,OpNameC)
1179 ; get_json_attribute_with_pos(_SomeOtherAttr,Json,FileName,_,Position)
1180 -> add_message(translate_json_operation,'Transition has no JSON "name" attribute','',Position),
1181 OpName = ''
1182 ; OpName = '', Position=unknown,
1183 add_error(translate_json_operation,'Transition has no JSON "name" or other attribute in file: ',FileName,Position)
1184 ),
1185 (debug_mode(off) -> true ; add_message(translate_json_operation,'Processing operation: ',OpName,Position)),
1186 ? (get_json_key_object(params,Json,Paras)
1187 -> translate_json_paras(Paras,params(OpName),FileName,OpName,Bindings),
1188 sort(Bindings,ParaStore) % put the parameters into the standard Prolog order
1189 ; ParaStore = []
1190 ),
1191 ? (get_json_key_object(results,Json,ResParas)
1192 -> translate_json_paras(ResParas,results(OpName),FileName,OpName,Bindings2),
1193 sort(Bindings2,ResultStore)
1194 ; ResultStore = []
1195 ),
1196 ? (get_json_key_object(destState,Json,DestState)
1197 -> translate_json_paras(DestState,destState,FileName,OpName,Bindings3),
1198 sort(Bindings3,DestStore)
1199 ; DestStore = []
1200 ),
1201 ? (get_json_key_list(destStateNotChanged,Json,UnchList)
1202 -> maplist(translate_json_string,UnchList,UnchAtoms),
1203 sort(UnchAtoms,Unchanged)
1204 ; Unchanged = []
1205 ),
1206 ? (get_json_key_list(preds,Json,JPredList)
1207 -> (maplist(translate_json_pred,JPredList,PredList) -> true
1208 ; add_error(translate_json_operation,'Unable to parse predicates for operation:',OpName,Position),
1209 PredList = []
1210 )
1211 ; PredList = []
1212 ),
1213 ? (get_json_key_list(postconditions,Json,PostconditionList)
1214 ? -> maplist(translate_postcondition,PostconditionList,Postconditions)
1215 ; Postconditions = []
1216 ),
1217 ? (get_json_attribute(description,Json,string(DescCodes))
1218 -> atom_codes(Desc,DescCodes), Meta = [description/Desc,pos/Position]
1219 ; Meta = [pos/Position]
1220 ).
1221
1222 translate_postcondition(json(Json),Postcondition) :- % each postcondition is a JSON object json(AttributeList)
1223 ? get_json_attribute(kind,Json,string(KindCodes)),
1224 atom_codes(Kind,KindCodes),
1225 ? (translate_postcondition_kind(Kind,Json,Postcondition) -> true ; add_error(translate_postcondition,'translate_postcondition_kind failed',Json), fail).
1226
1227 translate_postcondition_kind('PREDICATE',Json,state_predicate(TPred)) :-
1228 !,
1229 get_json_attribute(predicate,Json,PredString),
1230 translate_json_pred(PredString,TPred).
1231 translate_postcondition_kind(Kind,Json,operation_enabled(OpName,TPred,Enabled)) :-
1232 enabled_kind(Kind,Enabled),
1233 !,
1234 ? get_json_attribute(operation,Json,string(OpNameCodes)),
1235 atom_codes(OpName,OpNameCodes),
1236 get_json_attribute(predicate,Json,PredString),
1237 (PredString = string([]) -> TPred = b(truth,pred,[])
1238 ; translate_json_pred(PredString,TPred)
1239 ).
1240
1241 enabled_kind('ENABLEDNESS',enabled).
1242 enabled_kind('DISABLEDNESS',disabled).
1243
1244
1245
1246
1247 translate_json_string(string(AtomCodes),Atom) :- atom_codes(Atom,AtomCodes).
1248
1249 translate_json_paras([],_,_,_,R) :- !, R=[].
1250 translate_json_paras([Eq|T],Kind,FileName,OpName,[Bind|BT]) :-
1251 translate_json_para(Eq,Kind,FileName,OpName,Bind),!,
1252 translate_json_paras(T,Kind,FileName,OpName,BT).
1253 translate_json_paras([_|T],Kind,FileName,OpName,BT) :- translate_json_paras(T,Kind,FileName,OpName,BT).
1254
1255
1256 :- use_module(probsrc(tools),[safe_read_term_from_codes/2]).
1257 :- use_module(probsrc(b_global_sets),[add_prob_deferred_set_elements_to_store/3]).
1258 translate_json_para(Equality,_Kind,FileName,OpName,json_bind(Name,Value,any,Pos)) :-
1259 xtl_mode,
1260 is_json_equality_attr_with_pos(Equality,FileName,Name,string(ExprCodes),Pos),
1261 !,
1262 (safe_read_term_from_codes(ExprCodes,Value)
1263 -> true
1264 ; add_parameter_error('read term from JSON failed',Name,ExprCodes,OpName,Pos), Value = '').
1265 % TO DO: using eval_strings is very ugly, use a better API predicate
1266 translate_json_para(Equality,Kind,FileName,OpName,json_bind(Name,Value,Type,Pos)) :-
1267 \+ xtl_mode,
1268 is_json_equality_attr_with_pos(Equality,FileName,Name,string(ExpressionCodes),Pos),
1269 !,
1270 (ignore_operation_parameter(OpName,Name) -> fail
1271 ; eval_strings:repl_parse_expression(ExpressionCodes,Typed,Type,Error)
1272 -> (Error \= none -> add_parameter_error(Error,Name,ExpressionCodes,OpName,Pos)
1273 ; Type = pred -> add_parameter_error('use of predicate instead of expression',Name,ExpressionCodes,OpName,Pos)
1274 ; Type = subst -> add_parameter_error('unexpected substitution',Name,ExpressionCodes,OpName,Pos)
1275 ; (add_prob_deferred_set_elements_to_store([],EState,visible), % value should not depend on any state
1276 eval_strings:eval_expression_direct(Typed,EState,Value)
1277 -> \+ illegal_json_binding_type(Kind,Name,Type,Pos)
1278 ; add_parameter_error('evaluation error',Name,ExpressionCodes,OpName,Pos)
1279 )
1280 )
1281 ; add_parameter_error('parsing failed error',Name,ExpressionCodes,OpName,Pos)
1282 ).
1283 translate_json_para(Para,_,_,_,_) :-
1284 add_error(translate_json_para,'Unknown JSON para:',Para),fail.
1285
1286 :- use_module(specfile,[translate_operation_name/2]).
1287 add_parameter_error(Error,Name,ExpressionCodes,OpName,Pos) :-
1288 translate_operation_name(OpName,TOp),
1289 ajoin(['Ignoring JSON value for parameter ',Name,' of ',TOp,' due to ',Error,':'], Msg),
1290 atom_codes(A,ExpressionCodes),
1291 add_error(translate_json_para,Msg,A,Pos),fail.
1292
1293 %evaluate_codes_value(ExpressionCodes,Type,Value) :-
1294 % eval_strings:repl_parse_expression(ExpressionCodes,Typed,Type,Error), Error=none,
1295 % eval_strings:eval_expression_direct(Typed,Value).
1296
1297 ?illegal_json_binding_type(destState,ID,Type,Pos) :- get_expected_type(ID,Kind,ExpectedType),!,
1298 \+ unify_types_strict(Type,ExpectedType), pretty_type(Type,TS), pretty_type(ExpectedType,ETS),
1299 ajoin(['Ignoring JSON destState value for ',Kind,' ',ID,' due to illegal type ',TS, ', expected:'], Msg),
1300 add_error(translate_json_para,Msg,ETS,Pos).
1301 illegal_json_binding_type(destState,ID,_Type,Pos) :-
1302 b_get_machine_constants(TConsts),get_texpr_ids(TConsts,CVars),
1303 b_get_machine_variables(TVars),get_texpr_ids(TVars,VVars),
1304 append(CVars,VVars,All), sort(All,SAll),
1305 get_possible_fuzzy_matches_completions_and_inner_msg(ID,SAll,FMsg),!,
1306 ajoin(['Ignoring JSON destState value for unknown identifier (did you mean ',FMsg,' ?):'],Msg),
1307 add_error(translate_json_para,Msg,ID,Pos).
1308 illegal_json_binding_type(destState,ID,_Type,Pos) :-
1309 add_error(translate_json_para,'Ignoring JSON destState value for unknown identifier:',ID,Pos).
1310 % unknown operations are now dealt with later in check_and_adapt_trace_step
1311 %illegal_json_binding_type(params(Op),ID,_Type,Pos) :-
1312 % b_or_z_mode, % otherwise no types available
1313 % \+ b_top_level_operation(Op), !,
1314 % findall(KOpid,b_top_level_operation(KOpid),Ops),
1315 % (get_possible_fuzzy_matches_completions_and_inner_msg(Op,Ops,FMsg)
1316 % -> ajoin(['Ignoring JSON value for parameter ',ID,' of unknown operation (did you mean the operation ',FMsg,' ?) : '], Msg)
1317 % ; ajoin(['Ignoring JSON value for parameter ',ID,' of unknown operation: '], Msg)),
1318 % add_error(translate_json_para,Msg,Op,Pos).
1319 illegal_json_binding_type(params(Op),ID,Type,Pos) :-
1320 b_or_z_mode, % otherwise no types available
1321 b_top_level_operation(Op),
1322 b_get_machine_operation_typed_parameters_for_animation(Op,Params),
1323 ? member(b(identifier(ID),ExpectedType,_),Params),!,
1324 \+ unify_types_strict(Type,ExpectedType), pretty_type(Type,TS), pretty_type(ExpectedType,ETS),
1325 ajoin(['Ignoring JSON value for parameter ',ID,' of operation ', Op, ' due to illegal type ',TS, ', expected:'], Msg),
1326 add_error(translate_json_para,Msg,ETS,Pos).
1327 illegal_json_binding_type(params(Op),ID,_Type,Pos) :-
1328 b_or_z_mode, % otherwise show_eventb_any_arguments makes no sense
1329 b_top_level_operation(Op),
1330 (b_get_machine_operation_typed_parameters_for_animation(Op,[]),
1331 get_preference(show_eventb_any_arguments,false)
1332 % TODO: check if ID is a valid virtual parameter, or if trace file was generated with preference set to true
1333 -> ajoin(['Ignoring JSON value for parameter ',ID,', operation has no parameters (setting SHOW_EVENTB_ANY_VALUES to TRUE may help):'],Msg)
1334 ; ajoin(['Ignoring JSON value for unknown parameter ',ID,' for:'],Msg)
1335 ),
1336 add_error(translate_json_para,Msg,Op,Pos).
1337 illegal_json_binding_type(results(Op),ID,Type,Pos) :-
1338 b_or_z_mode, % otherwise there are no typred results available
1339 b_get_machine_operation_typed_results(Op,Results), member(b(identifier(ID),ExpectedType,_),Results),!,
1340 \+ unify_types_strict(Type,ExpectedType), pretty_type(Type,TS), pretty_type(ExpectedType,ETS),
1341 ajoin(['Ignoring JSON value for result ',ID,' of operation ', Op, ' due to illegal type ',TS], Msg),
1342 add_error(translate_json_para,Msg,ETS,Pos).
1343 % unknown operations are now dealt with later in check_and_adapt_trace_step
1344 %illegal_json_binding_type(results(_Op),ID,_Type,Pos) :-
1345 % add_error(translate_json_para,'Ignoring JSON value for unknown operation result:',ID,Pos).
1346
1347 get_expected_type(ID,variable,ExpectedType) :- bmachine_is_precompiled, b_is_variable(ID,ExpectedType).
1348 get_expected_type(ID,constant,ExpectedType) :- bmachine_is_precompiled, b_is_constant(ID,ExpectedType).
1349
1350 % TODO: already check results, ...
1351
1352 translate_json_pred(string(PredCodes),TPred) :-
1353 OuterQuantifier = no_quantifier,
1354 % TO DO: parse in context of operation ! otherwise we get type error for pp=pp for example where pp is a parameter
1355 eval_strings:repl_parse_predicate(PredCodes,OuterQuantifier,TPred,_TypeInfo). % , print(pred_ok(TPred)),nl.
1356
1357 /*
1358 after reading a JSON ProB2-UI file looks like this:
1359
1360 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])])])
1361
1362 */
1363
1364 % -------------------------
1365
1366 % Interactive Trace Replay API
1367
1368 % load a trace file and store it for interactive replay
1369 load_json_trace_file_for_ireplay(FileName) :-
1370 read_json_trace_file(FileName,ModelName,Trace),
1371 reset_json_trace_replay,
1372 store_json_trace(Trace,0,Len),
1373 assert(current_replay_step(1)),
1374 assert(loaded_json_trace_file(FileName,ModelName,Len)).
1375
1376 :- dynamic loaded_json_trace_file/3, json_trace_replay_step/3.
1377 :- dynamic current_replay_step/1, json_trace_replayed_info/2.
1378
1379
1380 :- use_module(eventhandling,[register_event_listener/3]).
1381 :- register_event_listener(clear_specification,reset_json_trace_replay,
1382 'Reset interactive trace replay.').
1383
1384 reset_json_trace_replay :-
1385 retractall(current_replay_step(_)),
1386 retractall(loaded_json_trace_file(_,_,_)),
1387 retractall(json_trace_replay_step(_,_,_)),
1388 retractall(json_trace_replayed_info(_,_)).
1389
1390 store_json_trace([],L,L).
1391 store_json_trace([TransSpec|T],StepNr,Len) :-
1392 S1 is StepNr + 1,
1393 get_transition_spec_txt(TransSpec,TTxt),
1394 formatsilent_with_colour(user_output,[blue],'==> Trace step ~w: ~w~n',[S1,TTxt]),
1395 phrase(check_and_adapt_trace_step(TransSpec,S1,CorrectedTransSpec),StaticErrors),
1396 assert(json_trace_replay_step(S1,CorrectedTransSpec,StaticErrors)),
1397 store_json_trace(T,S1,Len).
1398
1399 get_trace_step_info(StepNr,StepDescr) :-
1400 json_trace_replay_step(StepNr,TransSpec,StaticErrors),
1401 get_transition_spec_txt(TransSpec,TTxt),
1402 (StaticErrors = [] -> StaticTT=[]
1403 ; length(StaticErrors,NrStaticErrors),
1404 StaticTT = [' (static errors: ',NrStaticErrors,')']
1405 ),
1406 (json_trace_replayed_info(StepNr,Info),
1407 get_replay_info_text(Info,TextAtoms)
1408 -> append(StaticTT,TextAtoms,TT),
1409 ajoin([StepNr,': ',TTxt | TT],StepDescr)
1410 ; ajoin([StepNr,': ',TTxt | StaticTT],StepDescr)
1411 ).
1412
1413 get_replay_info_text(replay(FromID,TransID,MatchInfo,Errors),TextAtoms) :-
1414 transition(FromID,OperationTerm,TransID,_ToID),
1415 translate_event_with_limit(OperationTerm,40,OpTxt),
1416 !,
1417 (Errors=[] -> TextAtoms = [' * REPLAYED (', MatchInfo,') : ',OpTxt]
1418 ; length(Errors,NrErrors),
1419 TextAtoms = [' * REPLAYED (', MatchInfo, ', errors: ',NrErrors,') : ', OpTxt]
1420 ).
1421 get_replay_info_text(skipped,[' SKIPPED']) :- !.
1422 get_replay_info_text(X,[X]).
1423
1424 tk_get_stored_json_trace_description(list(List)) :-
1425 findall(StepDescr,get_trace_step_info(_,StepDescr),List).
1426
1427 get_stored_json_replay_steps(List) :-
1428 findall(ireplay_step(StepNr,TTxt,StaticErrors),
1429 (json_trace_replay_step(StepNr,TransSpec,RErrors),
1430 maplist(get_rerror,RErrors,StaticErrors),
1431 get_transition_spec_txt(TransSpec,TTxt)),
1432 List).
1433
1434 try_replay_next_step(MatchSpecs,CurStepNr,FromID,TransID,DestId,MatchInfo,TkTransInfos,TkErrors) :-
1435 (var(CurStepNr) -> current_replay_step(CurStepNr) ; true), % allow to pass a fixed Nr from ProB2
1436 (var(FromID) -> current_state_id(FromID) ; true), % allow to pass a fixed ID from ProB2
1437 json_trace_replay_step(CurStepNr,TransSpec,StaticErrors),
1438 flexible_perform_single_replay_step(FromID,TransID,DestId,MatchSpecs,TransSpec,MatchInfo),
1439 phrase(check_step_postconditions(TransSpec,DestId),Errors,StaticErrors),
1440 get_transition_name(FromID,TransID,OpName),
1441 length(Errors,NrErrs),
1442 formatsilent_with_colour(user_output,[green], '==> Replay step ~w (~w) ~w leading to state ~w~n',[CurStepNr,MatchInfo,OpName,DestId]),
1443 (NrErrs>0 -> formatsilent_with_colour(user_output,[orange],' Errors (~w): ~w~n',[NrErrs,Errors]) ; true),
1444 findall(TInfo,get_transition_info(TransSpec,TInfo),TkTransInfos),
1445 maplist(get_rerror,Errors,TkErrors). % make errors atomic for Tk
1446
1447 get_rerror(Err,Msg) :- get_replay_error(Err,Msg),!.
1448 get_rerror(Err,Msg) :- atom(Err),!,Msg=Err.
1449 get_rerror(Err,F) :- functor(Err,F,_).
1450
1451 :- use_module(translate,[translate_bexpression_with_limit/3]).
1452 % get text descriptions for a transition_spec, to be shown to user e.g. in Tk listbox:
1453 get_transition_info(transition_spec(_Op, _Meta, Paras, Results, DestStore,_UnchangedVars,_Preds,_Post),InfoTxt) :-
1454 (Kind=para, List=Paras
1455 ; Kind=result, List=Results
1456 ; Kind=dest, List=DestStore),
1457 get_binding_txt(List,Txt),
1458 ajoin([Kind,' : ',Txt],InfoTxt).
1459 get_transition_info(transition_spec(_Op, _, _, _, _,UnchangedVars,_,_),InfoTxt) :-
1460 member(ID,UnchangedVars),
1461 ajoin(['unchanged : ',ID],InfoTxt).
1462 get_transition_info(transition_spec(_Op, _, _, _, _,_,Preds,_),InfoTxt) :-
1463 member(TP,Preds),
1464 translate_bexpression_with_limit(TP,250,TPS),
1465 ajoin(['pred : ',TPS],InfoTxt).
1466
1467 get_binding_txt(List,BindingText) :-
1468 member(json_bind(Var,Value,_ValType,_ValPos),List),
1469 translate_bvalue_with_limit(Value,200,VS),
1470 ajoin([Var,'=',VS],BindingText).
1471
1472 default_match_specs([MatchSpec,MS2,MS3]) :-
1473 precise_match_spec(MatchSpec), % require precise replay
1474 ignore_dest_match_spec(MS2),
1475 opname_optimize_match_spec(MS3).
1476
1477 % expected options: precise, params_and_results, keep_name
1478 get_match_specs(precise,MS) :- !,
1479 precise_match_spec(MS1),
1480 MS=[MS1]. % allow only precise replay
1481 get_match_specs(params_and_results,MS) :- !,
1482 precise_match_spec(MS1),
1483 ignore_dest_match_spec(MS2),
1484 MS=[MS1,MS2]. % allow precise and params_and_results
1485 get_match_specs(_,MS) :- default_match_specs(MS). % allow all match_specs, including keep_name
1486
1487 %:- public ireplay/0.
1488 %ireplay :- default_match_specs(MS),
1489 % ireplay(MS).
1490 %
1491 %
1492 %ireplay(MatchSpecs) :-
1493 % replay_current_step(MatchSpecs,_),!,
1494 % ireplay(MatchSpecs).
1495 %ireplay(MatchSpecs) :-
1496 % skip_current_ireplay_step(_),
1497 % ireplay(MatchSpecs).
1498
1499 % get information about how the status of replaying a loaded trace is:
1500 get_ireplay_status(CurStepNr,Steps,Finished) :-
1501 loaded_json_trace_file(_,_,Steps),
1502 current_replay_step(CurStepNr),
1503 (CurStepNr =< Steps
1504 -> Finished=not_finished
1505 ; Finished=finished).
1506
1507 replay_of_current_step_is_possible(CurStepNr,OpName,MatchInfo,list(TransInfos),list(Errors)) :- % Tk
1508 default_match_specs(MS),
1509 try_replay_next_step(MS,CurStepNr,FromID,TransID,_DestId,MatchInfo,TransInfos,Errors),
1510 get_transition_name(FromID,TransID,OpName).
1511
1512 replay_of_current_step_is_possible_with_trans(CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)) :-
1513 default_match_specs(MS),
1514 replay_of_current_step_is_possible_with_trans_aux(MS,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)).
1515
1516 replay_of_current_step_is_possible_with_trans(MatchOption,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)) :- % ProB2
1517 get_match_specs(MatchOption,MS),
1518 replay_of_current_step_is_possible_with_trans_aux(MS,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)).
1519
1520 replay_of_current_step_is_possible_with_trans_aux(MatchSpec,CurStepNr,FromID,OpTerm,MatchInfo,list(Errors)) :-
1521 try_replay_next_step(MatchSpec,CurStepNr,FromID,TransID,DestID,MatchInfo,_TransInfos,Errors),
1522 create_op_transition(FromID,TransID,DestID,OpTerm).
1523
1524 create_op_transition(FromID,TransID,DestID,op(TransID,OpName,FromID,DestID)) :-
1525 get_transition_name(FromID,TransID,OpName).
1526
1527 % try and replay as much as possible
1528 ireplay_fast_forward(NrReplayed) :-
1529 default_match_specs(MS), ireplay_fast_forward(MS,0,NrReplayed).
1530
1531 ireplay_fast_forward(MatchSpecs,Nr,NrReplayed) :-
1532 replay_current_step(MatchSpecs,_),!,
1533 N1 is Nr+1,
1534 ireplay_fast_forward(MatchSpecs,N1,NrReplayed).
1535 ireplay_fast_forward(_,NrReplayed,NrReplayed).
1536
1537 ireplay_fast_forward_with_trans(CurStepNr,FromID,NrReplayed,Transitions,MatchInfos,Errors) :-
1538 default_match_specs(MS),
1539 ireplay_fast_forward_with_trans_aux(MS,CurStepNr,FromID,0,NrReplayed,Transitions,MatchInfos,Errors).
1540
1541 ireplay_fast_forward_with_trans(MatchOption,CurStepNr,FromID,NrReplayed,Transitions,MatchInfos,Errors) :- % for ProB2
1542 get_match_specs(MatchOption,MS),
1543 ireplay_fast_forward_with_trans_aux(MS,CurStepNr,FromID,0,NrReplayed,Transitions,MatchInfos,Errors).
1544
1545 ireplay_fast_forward_with_trans_aux(MS,CurStepNr,FromID,Nr,NrReplayed,[OpTerm|T1],[MatchInfo|M1],[Errors|E1]) :-
1546 replay_current_step_with_trans(MS,CurStepNr,FromID,OpTerm,MatchInfo,Errors),!,
1547 OpTerm = op(_,_,_,DestID),
1548 N1 is Nr+1,
1549 NextStepNr is CurStepNr+1,
1550 ireplay_fast_forward_with_trans_aux(MS,NextStepNr,DestID,N1,NrReplayed,T1,M1,E1).
1551 ireplay_fast_forward_with_trans_aux(_,_,_,NrReplayed,NrReplayed,[],[],[]).
1552
1553 % replay the currently selected step of the JSON trace, matching one step of the trace with one animation step
1554 replay_current_step(CurStepNr) :- % Tk
1555 default_match_specs(MS), replay_current_step(MS,CurStepNr).
1556
1557 % try and replay current step according to match specifications
1558 replay_current_step(MatchSpecs,CurStepNr) :-
1559 try_replay_next_step(MatchSpecs,CurStepNr,FromID,TransID,_DestID,MatchInfo,_,Errors),!,
1560 extend_trace_by_transition_ids([TransID]), % update state space
1561 assert(json_trace_replayed_info(CurStepNr,replay(FromID,TransID,MatchInfo,Errors))),
1562 increase_step_nr.
1563
1564 %replay_current_step_with_trans(FromID,OpTerm,MatchInfo,Errors) :- % ProB2
1565 % default_match_specs(MS),
1566 % replay_current_step_with_trans(MS,FromID,OpTerm,MatchInfo,Errors).
1567 replay_current_step_with_trans(MatchSpecs,CurStepNr,FromID,OpTerm,MatchInfo,Errors) :- % ProB2
1568 try_replay_next_step(MatchSpecs,CurStepNr,FromID,TransID,DestID,MatchInfo,_,Errors),!,
1569 create_op_transition(FromID,TransID,DestID,OpTerm).
1570
1571 % skip the current replay step and go to the next one
1572 skip_current_ireplay_step(CurStepNr) :-
1573 current_replay_step(CurStepNr),
1574 json_trace_replay_step(CurStepNr,TransSpec,_StaticErrors),
1575 get_transition_spec_txt(TransSpec,TTxt),
1576 formatsilent_with_colour(user_output,[orange],'Skipping replay step ~w : ~w~n',[CurStepNr,TTxt]),
1577 assert(json_trace_replayed_info(CurStepNr,skipped)),
1578 increase_step_nr.
1579
1580 increase_step_nr :-
1581 retract(current_replay_step(CurStepNr)),
1582 S1 is CurStepNr+1,
1583 assert(current_replay_step(S1)).
1584
1585 % :- 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.
1586
1587
1588