1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5
6 :- module(bvisual2,[ %reset_bvisual/0,
7 bv_get_top_level/1
8 , bv_expand_formula/3 % also used to get string of entry
9 , bv_get_values/3
10 , bv_get_values/2
11 , bv_insert_formula/3
12 %, bv_include_variables/0
13 , bv_get_value_unlimited/3
14 , bv_get_values_unlimited/3
15 , bv_is_explanation_node/1
16 , bv_print_to_file/3
17 , bv_write_all_variables_and_constants/2
18 , set_bvisual2_translation_mode/1
19 , bvisual2_translation_mode/1
20 , bv_get_top_level_formula/4
21 , bv_get_top_level_formula/5
22 , bv_value_to_atom/2
23 , bv_formula_origin/2
24 , bv_show_formula_origin/2
25 , bv_formula_description/2
26 , bv_formula_extended_description/2
27 , bv_formula_discharged_info/2
28 , bv_get_formula_functor_symbol/2
29 , bv_get_btvalue/4
30 , bv_is_child_formula/1
31 , bv_formula_labels/2
32 , bv_is_typed_formula/1
33 , bv_is_typed_predicate/1
34 , bv_is_typed_identifier/2
35 , bv_get_stored_formula_expr/2
36 , bv_formula_text/3
37 , tcltk_register_new_user_formula/1
38 , bv_re_register_definitions_if_necessary/0
39 , html_debug_operation_for_stateid/4
40 , bv_top_level_set/2
41 ]).
42
43 :- meta_predicate bv_time_out_call(0,-,-,-).
44 :- meta_predicate call_with_temp_preference(*,*,0).
45 :- meta_predicate with_bvisual2_translation_mode(0).
46
47 :- use_module(probsrc(module_information),[module_info/2]).
48 :- module_info(group,ast).
49 :- module_info(description,'This module contains functionality to analyse B expressions and predicates by evaluating and decomposing them into substructures.').
50
51 :- use_module(library(lists)).
52 :- use_module(library(codesio)).
53 %:- use_module(library(timeout)).
54
55 :- use_module(probsrc(bmachine), [ b_machine_has_constants_or_properties/0
56 , b_get_machine_variables_in_original_order/1
57 , b_get_machine_constants/1
58 , b_get_machine_operation/4
59 , b_get_properties_from_machine/1
60 , b_machine_additional_property/1
61 , get_invariant_list_with_proof_info/1
62 , number_of_ignored_invariants/1
63 , b_get_static_assertions_from_machine/1
64 , b_get_assertions_from_main_machine/2
65 , b_get_dynamic_assertions_from_machine/1
66 , b_get_assertion_count/3
67 , b_get_operation_variant/3
68 , b_get_operation_description/2
69 ]).
70 :- use_module(probsrc(specfile),[ state_corresponds_to_initialised_b_machine/2
71 , state_corresponds_to_set_up_constants/2, property/2, xtl_mode/0
72 ]).
73 :- use_module(probsrc(state_space), [ visited_expression/2
74 , current_state_id/1
75 , invariant_not_yet_checked/1
76 , invariant_violated/1
77 , transition/3
78 ]).
79 :- use_module(probsrc(store),[ empty_state/1
80 , normalise_store/2
81 ]).
82 :- use_module(probsrc(b_interpreter),[
83 b_not_test_boolean_expression_cs/5
84 , b_test_boolean_expression_for_ground_state/5
85 , b_test_boolean_expression/4
86 , b_compute_expression_nowf/6
87 , b_execute_statement_nowf/5
88 , set_up_typed_localstate/6
89 , properties_were_filtered/1
90 ]).
91 :- use_module(probsrc(translate),[ translate_bexpression_to_codes/2
92 , translate_subst_or_bexpr_with_limit/3
93 , get_texpr_top_level_symbol/4
94 , translate_bvalue_for_expression_with_limit/4
95 , translate_bvalue_for_expression/3
96 , translate_bvalue_with_type_and_limit/4
97 , translate_bvalue/2
98 , translate_any_state/2
99 , translate_b_state_to_comma_list/3
100 , translate_prolog_exception/2
101 , translate_eventb_direct_definition_header/3
102 , translate_eventb_direct_definition_body/2
103 ]).
104 :- use_module(probsrc(bsyntaxtree),[ get_texpr_expr/2
105 , get_texpr_type/2
106 , get_texpr_info/2
107 , get_texpr_id/2
108 , is_texpr/1
109 , create_texpr/4
110 , safe_create_texpr/3
111 , syntaxtraversion/6
112 , conjunction_to_list/2
113 , conjunct_predicates/2
114 , create_exists/3
115 , create_or_merge_exists/3
116 , create_forall/3
117 , texpr_contains_wd_condition/1
118 %, find_identifier_uses/3
119 ]).
120 :- use_module(probsrc(b_ast_cleanup),[ clean_up_pred/3
121 ]).
122 :- use_module(probsrc(error_manager),[ get_all_errors_and_clear/1
123 , get_perror/4
124 , time_out_with_enum_warning_one_solution/3
125 ]).
126 :- use_module(probsrc(preferences), [ get_preference/2
127 , set_preference/2
128 ]).
129 :- use_module(probsrc(kernel_waitflags), [ init_wait_flags_with_call_stack/2
130 , ground_wait_flags/1]).
131 :- use_module(probsrc(b_enumerate),[ b_tighter_enumerate_values_in_ctxt/3 ]).
132 :- use_module(probsrc(tools_files),[ put_codes/2]).
133 :- use_module(probsrc(tools_strings),[ strip_newlines/2, atom_prefix/2]).
134 :- use_module(probltlsrc(ltl),[get_ltl_formula_strings/2]). % did lead to SPIO_E_TOO_MANY_OPEN_FILES
135 :- use_module(probltlsrc(ltl_translate),[pp_ltl_formula/2, get_ltl_sub_formulas/3]).
136 :- use_module(probltlsrc(ltl_propositions), [is_atomic_ltl_property/1, check_atomic_property_formula/2]).
137 :- use_module(probltlsrc(ltl_tools),[temporal_parser/3]).
138
139 :- use_module(probsrc(bmachine_eventb), [ stored_operator_direct_definition/8]).
140 :- use_module(probsrc(debug), [debug_format/3, debug_mode/1]).
141
142 :- set_prolog_flag(double_quotes, codes).
143
144 :- dynamic top_level_node/1, subnode/2, supernode/2.
145 :- dynamic stored_formula/2, expanded/1, explanation_parent/1.
146 :- dynamic id_counter/1.
147 :- dynamic formula_cache/3.
148 % We store the information whether a node can introduce new values as an (counter-)example
149 % in example_node/1; the value is computed in explore_node/2.
150 % For such nodes, the found examples are stored in local_state/3.
151 :- dynamic example_node/1,local_state/3.
152
153
154
155 bv_value_to_atom(p(P),R) :- !, % a predicate value
156 (P=true -> R='TRUE' ; P=false -> R='FALSE' ; R=P).
157 bv_value_to_atom(e(_),R) :- !, R='ERROR'.
158 bv_value_to_atom(v(V),R) :- !, R=V. % a value, already pretty-printed !??
159 bv_value_to_atom(i,R) :- !, R='INACTIVE'.
160 bv_value_to_atom(bv_info(V),R) :- !, R=V.
161 bv_value_to_atom(V,V).
162
163
164 :- dynamic variables_should_be_included/0.
165 variables_should_be_included.
166 %bv_include_variables :-
167 % (variables_should_be_included -> true ; assertz(variables_should_be_included)).
168
169 clear_bvisual :-
170 retractall(top_level_node(_)),
171 retractall(subnode(_,_)), % TO DO: do not delete user formulas for a simple re-load ?!
172 retractall(supernode(_,_)),
173 retractall(stored_formula(_,_)),
174 retractall(expanded(_)),
175 retractall(explanation_parent(_)),
176 retractall(formula_cache(_,_,_)),
177 retractall(example_node(_)),
178 retractall(local_state(_,_,_)),
179 retractall(specfile_property_cache(_,_)),
180 retractall(specfile_property_cached_state(_)).
181 % This predicate should be called after loading a new specification
182 % and before using the other predicates below
183 reset_bvisual :-
184 clear_bvisual,
185 register_top_level.
186
187 :- public portray_bvisual/0. % debugging utility
188 portray_bvisual :- %listing(top_level_node/1), listing(subnode/2), listing(stored_formula/2)
189 top_level_node(N), bv_portray(N,1),fail.
190 portray_bvisual.
191 bv_portray(ID,Level) :-
192 (stored_formula(ID,Form) -> functor(Form,F,_) ; F = '??'),
193 (expanded(ID) -> E=expanded ; E = 'not_expanded'),
194 indent(Level),format('~w -> ~w [~w]~n',[ID,F,E]),
195 L1 is Level+1,
196 subnode(ID,ID2),
197 bv_portray(ID2,L1).
198 indent(0) :- !.
199 indent(N) :- N>0,!, N1 is N-1, print(' '), indent(N1).
200
201 % returns the top-level nodes as a list of IDs
202 bv_get_top_level(Tops) :-
203 findall( Id, top_level_node(Id), Tops ).
204
205 % bv_expand_formula(+FormulaID,-LabelAtom,-)
206 % Input: Id
207 % Output: Label of Formula, list of children
208 bv_expand_formula(Id,Label,Children) :-
209 expanded(Id),!,
210 get_node_label(Id,Label),
211 findall(C, subnode(Id,C), Children).
212 bv_expand_formula(Id,Label,Children) :-
213 get_node_label(Id,Label),
214 explore_node(Id,Children).
215
216 % bv_get_values in current state
217 bv_get_values(Ids,Values) :-
218 current_state_id(StateId),
219 bv_get_values(Ids,StateId,Values).
220
221 :- use_module(probsrc(specfile),[prepare_state_for_specfile_trans/3]).
222 :- use_module(probsrc(tools),[start_ms_timer/1,get_elapsed_runtime/2]).
223
224 % bv_get_values(+IdsOfFormulas,+CurrentStateID,-ValuesOfFormulas)
225 bv_get_values(Ids,StateId,Values) :-
226 visited_expression(StateId,State),!,
227 prepare_state_for_specfile_trans(State,StateId,PreparedState),
228 bv_get_default_formula_timeout(Timeout),
229 start_ms_timer(Timer),
230 bv_get_values2(Ids,PreparedState,StateId,Timeout,Timer,Values).
231 bv_get_values(Ids,_StateId,Values) :-
232 % in case that the state ID cannot be resolved, we
233 % return an error for each formula
234 same_length(Ids,Values),
235 same_value(Values,e('unknown state')).
236 same_value([],_).
237 same_value([V|Rest],V) :- same_value(Rest,V).
238
239 % get timeout for standard formula evaluation of an entry in the bvisual2 table:
240 bv_get_default_formula_timeout(BVTimeout) :-
241 get_preference(time_out,Timeout),
242 (Timeout =< 1200 -> BVTimeout = Timeout
243 ; BVTimeout is 1200 + (Timeout-1000)// 5).
244
245 % Insert a new formula
246 % bv_insert_formula(+TypeCheckedExpression,+ParentID,-IDofNewFormula)
247 bv_insert_formula(TExpr,ParentId,Id) :- %print(bv_insert_formula(TExpr,ParentId)),nl,
248 get_new_id(Id),
249 assertz( stored_formula(Id,TExpr) ),
250 assertz( subnode(ParentId,Id) ),
251 assertz( supernode(Id,ParentId) ),
252 (ParentId == top -> assertz(top_level_node(Id)) ; true).
253
254 bv_time_out_call(Call,ValueFromCall,Timeout,Value) :-
255 catch(bv_time_out_call2(Call,ValueFromCall,Timeout,Value),Exception,
256 (Value=e(ErrStr),translate_prolog_exception(Exception,ErrStr))).
257 bv_time_out_call2(Call,ValueFromCall,Timeout,Value) :-
258 (time_out_with_enum_warning_one_solution( Call,
259 Timeout,
260 Result)
261 ->
262 ( Result == success -> Value = ValueFromCall
263 ; Result = virtual_time_out(failure_enumeration_warning(_Info,_,_,_,critical)) -> Value = e('?(\x221E\)') % Value = e('\x22A5\?(\x221E\)') % 8734 in decimal % Feedback for user : increasing MAXINT,... could mean ProB can find a solution; However, increasing TIMEOUT value will not help
264 ; Result = virtual_time_out(_) -> Value = e('?(\x221E\)') % infinity symbol: Feedback to the user : probably no way to solve the issue apart from ensuring that set comprehensions are finite ...
265 ; Value = e(timeout))
266 ).
267
268 % compute a local timeout based on how long the bv_get_values command has been running thus far:
269 get_local_formula_timeout(DefaultTimeout,TimerSinceStart,FormulaTimeout) :-
270 get_elapsed_runtime(TimerSinceStart,Delta),
271 (Delta > 2*DefaultTimeout % then reduce timeout
272 -> Factor is Delta / DefaultTimeout,
273 debug_format(19,'Reducing timeout by factor of ~w (runtime thus far: ~w, default timeout: ~w)~n',[Factor,Delta,DefaultTimeout]),
274 FormulaTimeout is integer(DefaultTimeout / Factor)
275 ; FormulaTimeout=DefaultTimeout).
276
277 bv_get_values2([],_,_,_,_,[]).
278 bv_get_values2([Id|Irest],State,StateId,Timeout,TimerSinceStart,[Value|Vrest]) :-
279 get_local_formula_timeout(Timeout,TimerSinceStart,FormulaTimeout),
280 bv_get_value(Id,State,StateId,FormulaTimeout,Value),
281 bv_get_values2(Irest,State,StateId,Timeout,TimerSinceStart,Vrest).
282
283 bv_get_value(Id,State1,StateId,Timeout,FinalValue) :-
284 bv_get_value_unprocessed(Id,State1,StateId,Timeout,Value),
285 value_post_processing(Value,FinalValue).
286 bv_get_value_unprocessed(Id,State1,StateId,Timeout,Value) :-
287 is_active(Id,StateId,State1,State,LocalState),!, %print(is_active(Id)), debug:nl_time,
288 ( is_cached(Id,StateId,State1,Value1) ->
289 FromCache = true
290 ; bv_get_value1(Id,StateId,State,LocalState,Timeout,Value1) ->
291 FromCache = false %, print(evaluated),debug:nl_time
292 ;
293 Value1 = e('evaluation failed'),
294 FromCache = false),
295 handle_errors(Value1,Value),
296 (FromCache==false, should_be_cached(Id) -> write_to_cache(Id,StateId,State1,Value) ; true).
297 bv_get_value_unprocessed(_Id,_State1,_StateId,_Timeout,i). % INACTIVE
298
299 bv_get_value1(Id,StateId,State,LocalState,Timeout,Value) :-
300 stored_formula(Id,Formula),
301 bv_get_value2(Formula,Id,StateId,State,LocalState,Timeout,Value).
302
303 bv_get_value2(Formula,Id,_,State,LocalState,Timeout,Value) :-
304 is_texpr(Formula),!,
305 get_texpr_type(Formula,Type),
306 bv_get_texpr_value3(Type,Id,Formula,LocalState,State,Timeout,Value).
307 bv_get_value2(named_subformula(_,Formula,Error),Id,StateId,State,LocalState,Timeout,Value) :- !,
308 (Error='$no_error' -> bv_get_value2(Formula,Id,StateId,State,LocalState,Timeout,Value)
309 ; Value = e(Error)).
310 bv_get_value2(bind(_ID,Value),_,_,_,_,_,btvalue(Value)).
311 bv_get_value2(textnode(Value,_),_,_,_State,_LS,_,v(Value)).
312 bv_get_value2(textnode3(_,Value,_),_,_,_State,_LS,_,ResValue) :-
313 (color_based_on_value(Value,_) -> ResValue = Value % already using encoding
314 ; ResValue = v(Value)).
315 %bv_get_value2(cbc_path(_LastStateID,Path,_Last),_,_,_State,_LS,_,v(NrOfPaths)) :-
316 % append(Path,_,Prefix),
317 % findall(Last,sap:cb_path(_,Prefix,Last),AllPathsWithPrefix),
318 % length(AllPathsWithPrefix,NrOfPaths).
319 bv_get_value2(included_machine(_,Value,_),_,_,_State,_LS,_,v(Value)).
320 bv_get_value2(variant(_Name,_ConvOrAnt,Variant),Id,StateId,State,LocalState,Timeout,Value) :- !,
321 bv_get_value2(Variant,Id,StateId,State,LocalState,Timeout,Value).
322 bv_get_value2(ltl_named_formula(_Name,String),_Id,_StateId,_,_LocalState,_Timeout,Value) :- !,
323 strip_newlines(String,String2), Value=v(String2).
324 bv_get_value2(ltl_formula(_,Tree),_Id,StateId,_,_LocalState,_Timeout,Value) :- !,
325 (is_atomic_ltl_property(Tree) ->
326 (check_atomic_property_formula(Tree,StateId) -> Value = p(true) ; Value=p(false))
327 ; Value = v('-')). % TO DO: we could evaluate the formulas on back and forward history; ap(enabled(E))
328 bv_get_value2(guard(_Name,Parameters,Guard),Id,StateId,State,LocalState,Timeout,Value) :- !,
329 get_guard_formula(Parameters,Guard,Expr),
330 bv_get_value2(Expr,Id,StateId,State,LocalState,Timeout,Value).
331 bv_get_value2(guard_theorems(_Name,Parameters,Guard,Theorems),FID,StateId,State,LocalState,Timeout,Value) :- !,
332 get_guard_theorems_formula(Parameters,Guard,Theorems,Expr),
333 bv_get_value2(Expr,FID,StateId,State,LocalState,Timeout,Value).
334 bv_get_value2(raw_state_pp,_,_,State,_LS,_,v(Value)) :- !, % raw pretty printed stated
335 translate_any_state(State,Value).
336 bv_get_value2(property_pp(Nr),_,_,State,_LS,_,v(Value)) :- !, % xtl or csp properties
337 get_specfile_property(State,Nr,Value).
338 bv_get_value2(Node,_,_,_State,_LS,_,e(unknown)) :-
339 format('Unknown bvisual2 node: ~w~n',[Node]).
340
341
342 :- dynamic specfile_property_cache/2, specfile_property_cached_state/1.
343 get_specfile_property(State,Nr,PVal) :- recompute_specfile_property_cache(State),
344 specfile_property_cache(Nr,PVal).
345
346 recompute_specfile_property_cache(State) :- \+ specfile_property_cached_state(State),
347 retractall(specfile_property_cached_state(_)),
348 assert(specfile_property_cached_state(State)),
349 retractall(specfile_property_cache(_,_)),
350 findall(P,specfile:property(State,P),List),
351 is_property_atom(_Atom,Nr),
352 nth1(Nr,List,PVal),
353 write_to_codes(PVal,C), atom_codes(Value,C),
354 assert(specfile_property_cache(Nr,Value)),fail.
355 recompute_specfile_property_cache(_).
356
357
358
359 bv_get_texpr_value3(pred,Id,Formula,LocalState,State,Timeout,Value) :-
360 !,
361 % print('CHECKING PREDICATE: '), translate:print_bexpr(Formula),nl,
362 CS = 'state view table',
363 (bv_time_out_call(b_test_boolean_expression_for_ground_state(Formula,LocalState,State,CS,Id),true,Timeout,ValuePos) -> true ; ValuePos=false),
364 ( get_preference(double_evaluation_when_analysing,true) ->
365 CS2 = 'state view table (negated)',
366 (bv_time_out_call(b_not_test_boolean_expression_cs(Formula,LocalState,State,CS2,Id),true,Timeout,ValueNeg)
367 -> true ; ValueNeg=false),
368 combine_predicate_values(ValuePos,ValueNeg,Value)
369 ; encode_predicate_value(ValuePos,Value)).
370 bv_get_texpr_value3(subst,_Id,Formula,LocalState,State,Timeout,Res) :- !,
371 (bv_time_out_call(b_execute_statement_nowf(Formula,LocalState,State,OutState,prob_command_context),
372 OutState,Timeout,Value)
373 -> ( Value = e(E) -> Res = e(E) % e for exception or timeout
374 ; Res = btstate(Value)
375 )
376 ; Res = e(infeasible)
377 ).
378 bv_get_texpr_value3(_,Id,Formula,LocalState,State,Timeout,Res) :-
379 CS = 'state view table',
380 (bv_time_out_call(b_compute_expression_nowf(Formula,LocalState,State,FValue,CS,Id),FValue,Timeout,Value)
381 -> ( Value = e(E) -> Res = e(E) % e for exception or timeout
382 ; Res = btvalue(Value,Formula)
383 )
384 ; texpr_contains_wd_condition(Formula) -> Res = e(undefined)
385 ).
386
387
388
389 encode_predicate_value(e(Error),e(Error)).
390 encode_predicate_value(bv_info(Error),bv_info(Error)).
391 encode_predicate_value(true,p(true)).
392 encode_predicate_value(false,p(false)).
393 combine_predicate_values(e(_Error),true,p(false)) :-
394 print('### Ignoring Timeout in Positive Case of DOUBLE_EVALUATION as Negated Predicate is TRUE'),nl.
395 combine_predicate_values(e(_Error),false,p(true)) :-
396 print('### Ignoring Timeout in Positive Case of DOUBLE_EVALUATION as Negated Predicate is FALSE'),nl.
397 combine_predicate_values(e(Error),e(_),e(Error)).
398 combine_predicate_values(true,false,p(true)).
399 combine_predicate_values(false,true,p(false)).
400 combine_predicate_values(true,true,e('both true and false')).
401 combine_predicate_values(false,false,e(undefined)).
402 combine_predicate_values(true,e(_Error),p(true)) :-
403 print('### Ignoring Timeout in Negative Case of DOUBLE_EVALUATION'),nl.
404 combine_predicate_values(false,e(_Error),p(false)) :-
405 print('### Ignoring Timeout in Negative Case of DOUBLE_EVALUATION'),nl.
406
407 :- dynamic get_unlimited_value/0.
408
409
410 value_post_processing(In,Out) :-
411 with_bvisual2_translation_mode(
412 (value_post_processing2(In,O) -> O=Out
413 ; Out=e('internal error: failed to post-process value'))).
414 value_post_processing2(v(Value),v(Value)).
415 value_post_processing2(p(Value),p(Value)).
416 value_post_processing2(e(Error),e(Error)).
417 value_post_processing2(i,i).
418 value_post_processing2(bv_info(I),bv_info(I)).
419 value_post_processing2(btvalue(BValue,Expr),v(Value)) :-
420 (get_unlimited_value -> translate_bvalue_for_expression(BValue,Expr,Value)
421 ; translate_bvalue_for_expression_with_limit(BValue,Expr,600,Value) % one can always use bv_get_value_unlimited
422 ).
423 value_post_processing2(btvalue(BValue),v(Value)) :-
424 % TO DO: get type for variables and constants
425 (get_unlimited_value -> translate_bvalue(BValue,Value)
426 ; translate_bvalue_with_type_and_limit(BValue,any,600,Value)).
427 value_post_processing2(btstate(Updates),v(Value)) :-
428 (Updates=[] -> Value='skip'
429 ; get_unlimited_value -> translate_b_state_to_comma_list(Updates,100000,Value) % TODO: not unlimited
430 ; translate_b_state_to_comma_list(Updates,600,Value)).
431
432
433
434
435 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
436 % caching of some values
437 :- use_module(probsrc(store),[no_value_for_variable/2]).
438
439 % we do not compute the theorems node, only its subnodes
440 is_cached(theoremsc,_,_,v('')) :- !.
441 is_cached(theoremscm,_,_,v('')) :- !.
442 is_cached(theoremsv,_,_,v('')) :- !.
443 is_cached(theoremsvm,_,_,v('')) :- !.
444 is_cached(goal,_,_,v('')) :- !.
445 % we use the invariant_violated flag of the state space as a kind of cache
446 is_cached(inv,StateId,_State,Value) :-
447 \+ invariant_not_yet_checked(StateId),
448 (invariant_violated(StateId) -> Value=p(false)
449 ; number_of_ignored_invariants(Nr), Nr>0 ->
450 get_node_label(invariants,INV),
451 ajoin(['some ', INV,' (',Nr,') were ignored'],Msg), Value = e(Msg)
452 ; Value=p(true)).
453 % axioms are usually true in the constants' state
454 is_cached(axioms,StateId,concrete_constants(State),R) :- !,
455 is_cached_constants_state(StateId,State,R).
456 is_cached(axioms,StateId,[_|_],R) :- !, % states consisting of just a list are either constructed by
457 % find valid state, state-based MC,... or when there are no constants
458 % We assume PROPERTIES/axioms to be true; by constructing these commands have to satisfy the properties
459 is_cached_constants_state(StateId,[],R).
460 % this formula was already computed and cached for the given state
461 is_cached(FormulaId,StateId,_State,Value) :-
462 formula_cache(FormulaId,StateId,Value),!.
463 % in case of axiom, we can look at the reverences constants' state
464 is_cached(FormulaId,_,expanded_const_and_vars(ConstId,_,_,_),Value) :- is_cached_axiom(FormulaId,ConstId,Value).
465 is_cached(FormulaId,_,const_and_vars(ConstId,_),Value) :- is_cached_axiom(FormulaId,ConstId,Value).
466 is_cached_axiom(FormulaId,ConstId,Value) :-
467 is_axiom_or_static_theorem(FormulaId),
468 visited_expression(ConstId,ConstState),
469 % we could avoid unpacking, but constants state are not packed anyway; full value is only used for partial_setup_constants below; TO DO avoid extracting ConstState
470 is_cached(FormulaId,ConstId,ConstState,Value),!.
471
472 is_cached_constants_state(StateId,State,R) :-
473 % only if a partial_setup_constants event led to that
474 % state, then something did not work
475 ( transition(root,'$partial_setup_constants',StateId) ->
476 (member(bind(_,Val),State), no_value_for_variable(Val,_)
477 -> R = e('some constants have no values')
478 ; properties_were_filtered(Nr), Nr>0
479 -> get_node_label(axioms,Axioms),
480 ajoin(['some ',Axioms, ' (',Nr,') were ignored'],Msg), R = e(Msg)
481 ; animation_minor_mode(eventb) -> R = e('some axioms may be false')
482 ; R = e('some properties may be false')
483 )
484 ; R = p(true)).
485
486 should_be_cached(FormulaId) :-
487 is_axiom_or_static_theorem(FormulaId).
488
489 write_to_cache(FormulaId,_StateId,const_and_vars(ConstId,_),Value) :-
490 is_axiom_or_static_theorem(FormulaId),!,
491 visited_expression(ConstId,ConstState),
492 write_to_cache(FormulaId,ConstId,ConstState,Value).
493 write_to_cache(FormulaId,StateId,_State,Value) :-
494 assertz(formula_cache(FormulaId,StateId,Value)).
495
496 is_axiom_or_static_theorem(axioms) :- !.
497 is_axiom_or_static_theorem(theoremsc) :- !.
498 is_axiom_or_static_theorem(theoremscm) :- !.
499 is_axiom_or_static_theorem(FormulaId) :-
500 supernode(FormulaId,Parent),is_axiom_or_static_theorem(Parent).
501
502 :- use_module(probsrc(tools_strings),[atom_codes_with_limit/3]).
503 handle_errors(_,e(ErrorMsg)) :-
504 get_all_errors_and_clear([Error|_]),!, % TO DO: use proper error scoping and do not trigger when error stored before calling bvisual2
505 write_to_codes(Error,ErrorCodes),
506 atom_codes_with_limit(ErrorMsg,200,ErrorCodes).
507 handle_errors(Value,Value).
508
509
510 % is_active(+FormulaID,+InState,-PossiblyExpandedState)
511 % says if a FormulaID makes sense for the current state, if not: it will be grayed out
512 is_active(user,StateId,InState,OutState,LocalState) :- !,
513 is_active(inv,StateId,InState,OutState,LocalState).
514 is_active(inv,_StateId,InState,OutState,LocalState) :- !,
515 empty_state(LocalState),
516 state_corresponds_to_initialised_b_machine(InState,OutState).
517 is_active(axioms,_StateId,InState,OutState,LocalState) :- !,
518 (csp_with_bz_mode
519 -> InState \= csp_and_b_root
520 ; InState \= root),
521 empty_state(LocalState),
522 state_corresponds_to_set_up_constants(InState,OutState),
523 !.
524 is_active(variants,StateId,InState,OutState,LocalState) :- !,
525 is_active(inv,StateId,InState,OutState,LocalState).
526 is_active(theoremsc,StateId,InState,OutState,LocalState) :- !,
527 is_active(axioms,StateId,InState,OutState,LocalState).
528 is_active(theoremscm,StateId,InState,OutState,LocalState) :- !,
529 is_active(axioms,StateId,InState,OutState,LocalState).
530 is_active(theoremsv,StateId,InState,OutState,LocalState) :- !,
531 is_active(inv,StateId,InState,OutState,LocalState).
532 is_active(theoremsvm,StateId,InState,OutState,LocalState) :- !,
533 is_active(inv,StateId,InState,OutState,LocalState).
534 is_active(guards_top_level,StateId,InState,OutState,LocalState) :- !,
535 is_active(inv,StateId,InState,OutState,LocalState).
536 is_active(guards_subsidiary,StateId,InState,OutState,LocalState) :- !,
537 is_active(inv,StateId,InState,OutState,LocalState).
538 is_active(guard_theorems,StateId,InState,OutState,LocalState) :- !,
539 is_active(inv,StateId,InState,OutState,LocalState).
540 is_active(variables,StateId,InState,OutState,LocalState) :- !,
541 is_active(inv,StateId,InState,OutState,LocalState).
542 is_active(constants,StateId,InState,OutState,LocalState) :- !,
543 is_active(axioms,StateId,InState,OutState,LocalState).
544 is_active(sets,_StateId,InState,OutState,LocalState) :- !, b_or_z_successsful_mode,
545 empty_state(LocalState), InState=OutState.
546 is_active(freetypes,_StateId,InState,OutState,LocalState) :- !,
547 empty_state(LocalState), InState=OutState.
548 is_active(goal,StateId,InState,OutState,LocalState) :- !,
549 is_active(inv,StateId,InState,OutState,LocalState).
550 is_active(user_formulas,StateId,InState,OutState,LocalState) :- !,
551 is_active(inv,StateId,InState,OutState,LocalState).
552 is_active(definitions,StateId,InState,OutState,LocalState) :- !,
553 is_active(inv,StateId,InState,OutState,LocalState).
554 is_active(included_machines,_StateId,_InState,_OutState,_LocalState) :- !,
555 b_or_z_mode.
556 is_active(ltl_formulas,StateId,InState,OutState,LocalState) :- !,
557 is_active(inv,StateId,InState,OutState,LocalState).
558 is_active(channels,_StateId,S,OutState,LocalState) :- !,
559 csp_mode, OutState=S,empty_state(LocalState).
560 is_active(datatypes,_StateId,S,OutState,LocalState) :- !,
561 csp_mode, OutState=S,empty_state(LocalState).
562 is_active(subtypes,_StateId,S,OutState,LocalState) :- !,
563 csp_mode, OutState=S,empty_state(LocalState).
564 is_active(raw_state,_StateId,S,OutState,LocalState) :- !,
565 \+ b_or_z_mode, % maybe we should extract it for csp_and_b ?
566 OutState=S,empty_state(LocalState).
567 %is_active(cbc_tests,_StateId,_InState,_OutState,_LocalState) :- !,
568 % sap:cb_path(_,[_],_). % show cbc_tests if we ran CBC test-case generator
569 is_active(Atom,_StateId,S,OutState,LocalState) :- is_property_atom(Atom,Nr),!,
570 get_specfile_property(S,Nr,_),
571 OutState=S,empty_state(LocalState).
572 is_active(NodeId,StateId,InState,OutState,LocalState) :-
573 supernode(NodeId,Super),
574 is_active(Super,StateId,InState,OutState,InLocalState),
575 % check if the parent node introduces example values (e.g. in a exists-clause)
576 % If yes, the local state is extended by the values
577 ( example_node(Super) ->
578 find_example(Super,StateId,OutState,InLocalState,LocalState)
579 ;
580 InLocalState = LocalState).
581
582 find_example(NodeId,StateId,_State,_InLocalState,LocalState) :-
583 % check if the value was computed and cached before
584 local_state(NodeId,StateId,Result),!,
585 % if Result is not of the form example/1, no example
586 % was found. Just fail to show inactive state
587 Result = example(LocalState).
588 find_example(NodeId,StateId,State,InLocalState,LocalState) :-
589 % how the example is computed depends on the expression (e.g. exists)
590 % and the outcome of the parent node (true or false)
591 bv_get_values([NodeId],StateId,[V]),!,
592 stored_formula(NodeId,Formula),
593 ( find_example1(Formula,V,State,InLocalState,LocalState) ->
594 Result = example(LocalState)
595 ;
596 Result = not_found),
597 % currently we just ignore errors
598 handle_errors(_,_),
599 assertz( local_state(NodeId,StateId,Result) ),
600 Result = example(_).
601 find_example1(TExpr,V,State,InLocalState,LocalState) :-
602 is_texpr(TExpr),!,
603 get_texpr_expr(TExpr,Expr),
604 find_example2(Expr,V,State,InLocalState,LocalState).
605 find_example1(guard(_Name,Parameters,Guard),V,State,InLocalState,LocalState) :-
606 create_or_merge_exists(Parameters,Guard,Exists),
607 find_example1(Exists,V,State,InLocalState,LocalState).
608 find_example1(guard_theorems(_Name,Parameters,Guard,Theorems),V,State,InLocalState,LocalState) :-
609 create_forall(Parameters,b(implication(Guard,Theorems),pred,[]),ForAll),
610 find_example1(ForAll,V,State,InLocalState,LocalState).
611 find_example2(let_predicate(Ids,AssignmentExprs,Pred),Status,State,InLocalState,LocalState) :-
612 % translate LET back to exists
613 create_exists_for_let(Ids,AssignmentExprs,Pred,_,ExistsPred),
614 find_example2(exists(Ids,ExistsPred),Status,State,InLocalState,LocalState).
615 find_example2(let_expression(Ids,AssignmentExprs,_Expr),_Status,State,InLocalState,LocalState) :-
616 % translate LET expression to exists to find solution for assignments
617 % _Status is typically v(Value)
618 create_exists_for_let(Ids,AssignmentExprs,b(truth,pred,[]),_,ExistsPred),
619 find_example2(exists(Ids,ExistsPred),p(true),State,InLocalState,LocalState).
620 find_example2(exists(Ids,Predicate),p(true),State,InLocalState,LocalState) :-
621 find_solution_for_predicate(Ids,Predicate,State,InLocalState,LocalState).
622 find_example2(exists(Ids,Predicate),p(false),State,InLocalState,LocalState) :-
623 Predicate = b(conjunct(_,_),pred,_), % we have a false conjunct: try and find maximal prefix that is satisfiable
624 conjunction_to_list(Predicate,PredList),
625 maxsat_conjunct(Ids,PredList,[],State,InLocalState,no_solution,LocalState),
626 LocalState \= no_solution,
627 !.
628 find_example2(exists(Ids,Predicate),p(false),State,InLocalState,LocalState) :-
629 safe_create_texpr(negation(Predicate),pred,Negation),
630 find_solution_for_predicate(Ids,Negation,State,InLocalState,LocalState).
631 find_example2(forall(Ids,Pre,Condition),p(false),State,InLocalState,LocalState) :-
632 safe_create_texpr(negation(Condition),pred,Negation),
633 conjunct_predicates([Pre,Negation],Predicate),
634 find_solution_for_predicate(Ids,Predicate,State,InLocalState,LocalState).
635 find_example2(forall(Ids,Pre,Condition),p(true),State,InLocalState,LocalState) :-
636 conjunct_predicates([Pre,Condition],Predicate),
637 find_solution_for_predicate(Ids,Predicate,State,InLocalState,LocalState),
638 !.
639 find_example2(forall(Ids,Pre,_),p(true),State,InLocalState,LocalState) :-
640 % the LHS of the forall is never true; try find maximal subsequence for it:
641 find_example2(exists(Ids,Pre),p(false),State,InLocalState,LocalState).
642 find_example2(comprehension_set(Ids,Predicate),v(VS),State,InLocalState,LocalState) :-
643 (empty_val_str(VS) -> PVal=false ; PVal=true),
644 find_example2(exists(Ids,Predicate),p(PVal),State,InLocalState,LocalState).
645 empty_val_str(VS) :- (VS = '{}' -> true ; atom(VS),atom_codes(VS,[8709])). % unicode empty set
646
647 find_solution_for_predicate(Ids,Predicate,State,InLocalState,NormedLocalState) :-
648 get_preference(time_out,Timeout),
649 set_up_typed_localstate(Ids,_FreshVars,TypedVals,InLocalState,LocalState,positive),
650 (time_out_with_enum_warning_one_solution(
651 (init_wait_flags_with_call_stack(WF,[prob_command_context(find_solution_for_predicate,unknown)]),
652 b_tighter_enumerate_values_in_ctxt(TypedVals,Predicate,WF),
653 b_test_boolean_expression(Predicate,LocalState,State,WF),
654 ground_wait_flags(WF)),
655 Timeout,Result)
656 -> Result == success,
657 normalise_store(LocalState,NormedLocalState)
658 ).
659
660 create_exists_for_let(Ids,AssignmentExprs,Pred,Equalities,ExistsPred) :-
661 maplist(create_equality,Ids,AssignmentExprs,Equalities),
662 append(Equalities,[Pred],L),
663 conjunct_predicates(L,ExistsPred).
664
665 create_equality(ID,Expr,Equality) :-
666 safe_create_texpr(equal(ID,Expr),pred,Equality).
667
668 % find maximal subsequence of conjuncts that are satisfiable and return LocalState solution found
669 maxsat_conjunct(Ids,[LHS|Rest],ConSoFar,State,InLocalState,_BestLocalStateSoFar,ResLocalState) :-
670 append(ConSoFar,[LHS],NewConjunctList),
671 %print('TRY: '), translate:print_bexpr(LHS),nl,
672 conjunct_predicates(NewConjunctList,NewConjunct),
673 find_solution_for_predicate(Ids,NewConjunct,State,InLocalState,LocalState),
674 !, % print('+'),
675 maxsat_conjunct(Ids,Rest,NewConjunctList,State,InLocalState, LocalState,ResLocalState).
676 maxsat_conjunct(Ids,[_|Rest],ConSoFar,State,InLocalState,BestLocalStateSoFar,Res) :- !, % allows skipping conjuncts
677 maxsat_conjunct(Ids,Rest,ConSoFar,State,InLocalState,BestLocalStateSoFar,Res).
678 maxsat_conjunct(_Ids,_Rest,_ConSoFar,_State,_InLocalState,BestLocalStateSoFar,Res) :-
679 Res = BestLocalStateSoFar.
680
681 explore_node(Id,Children) :-
682 stored_formula(Id,Formula),
683 check_if_example_node(Id,Formula),
684 get_subformulas(Formula,Subs,Kind),
685 assertz( expanded(Id) ),
686 (Kind = explanation(Operator)
687 -> assert_as_explanation(Id,ExplId,Operator), Children = [ExplId|Children1],
688 register_formulas(Subs,Id,Children1)
689 ; register_formulas(Subs,Id,Children)).
690
691 assert_as_explanation(Parent,Id,Operator) :-
692 assertz(explanation_parent(Parent)),
693 % add a text line; showing that we did an equivalence rewrite
694 get_new_id(Id),
695 assertz( stored_formula(Id,textnode3('\x21D4\',bv_info(Operator),[])) ), % unicode translation
696 assertz( subnode(Parent,Id) ),
697 assertz( supernode(Id,Parent) ).
698
699 bv_is_explanation_node(NodeId) :-
700 supernode(NodeId,ParentId),
701 explanation_parent(ParentId).
702
703 % the following predicates determine whether the node introduces
704 % example values and stores that information in example_node/1.
705 check_if_example_node(Id,Formula) :-
706 is_example_node(Formula),!,
707 assertz( example_node(Id) ).
708 check_if_example_node(_Id,_Formula).
709 is_example_node(TFormula) :-
710 is_texpr(TFormula),!,
711 get_texpr_expr(TFormula,Formula),
712 is_example_node2(Formula).
713 is_example_node(guard(_Name,[_|_],_Guard)).
714 is_example_node(guard_theorems(_Name,[_|_],_Guard,_Theorems)).
715 is_example_node2(exists(_Ids,_Cond)).
716 is_example_node2(forall(_Ids,_Pre,_Cond)).
717 is_example_node2(let_predicate(_Ids,_E,_Cond)).
718 is_example_node2(let_expression(_Ids,_E,_Cond)).
719 is_example_node2(comprehension_set(_Ids,_Cond)).
720
721 % subformula_rule/4 defines wich subformulas should be
722 % shown in an evaluation tree for a formula. If no
723 % rule matches, the standard subformulas are used
724 subformula_rule(forall(Ids,P,R),_,Subs,quantifier) :-
725 append(Ids,[P,R],Subs).
726 subformula_rule(let_predicate(Ids,AssignmentExprs,Pred),_,Subs,quantifier) :-
727 % see create_exists_for_let(Ids,AssignmentExprs,Pred,Equalities,_ExistsPred),
728 maplist(create_equality,Ids,AssignmentExprs,Equalities),
729 append(Equalities,[Pred],EP), % show equalities and then one subnode for the predicate
730 append(Ids,EP,Subs).
731 subformula_rule(exists(Ids,P),_,Subs,quantifier) :-
732 conjunction_to_list(P,PL),
733 append(Ids,PL,Subs).
734 subformula_rule(comprehension_set(Ids,P),_,Subs,quantifier) :-
735 conjunction_to_list(P,PL),
736 append(Ids,PL,Subs).
737 subformula_rule(conjunct(A,B),_,Subs,normal) :-
738 safe_create_texpr(conjunct(A,B),pred,E),
739 conjunction_to_list(E,Subs).
740 subformula_rule(disjunct(A,B),_,Subs,normal) :-
741 disjunction_to_list(A,B,Subs).
742 subformula_rule(let_expression(Ids,AssignmentExprs,Expr),_,Subs,quantifier) :-
743 maplist(create_equality,Ids,AssignmentExprs,Equalities),
744 append(Equalities,[Expr],EP), % show equalities and then one subnode for the expression
745 append(Ids,EP,Subs).
746 subformula_rule(Formula,TFormula,Subs,Kind) :-
747 get_preference(show_bvisual_formula_explanations,true),
748 subformula_explanation_rule(Formula,TFormula,Subs,Kind).
749
750 subformula_explanation_rule(equal(A,B),TF,[Sub1,Sub2],explanation(equal)) :-
751 get_texpr_type(A,T),T=set(SType),
752 \+ (kernel_objects:max_cardinality(SType,Max),number(Max),Max<10), % sets can never be very large
753 is_not_bvexpr(TF), % do not apply to explanation expressions
754 no_empty_set(A),no_empty_set(B),
755 !,
756 create_bvexpr(set_subtraction(A,B),T,AminusB),
757 create_bvexpr(set_subtraction(B,A),T,BminusA),
758 create_bvexpr(empty_set,T,Empty),
759 create_bvexpr(equal(AminusB,Empty),pred,Sub1),
760 create_bvexpr(equal(BminusA,Empty),pred,Sub2).
761 subformula_explanation_rule(subset(A,B),_,[Equals],explanation(subset)) :-
762 subset_rule(A,B,Equals).
763 subformula_explanation_rule(subset_strict(A,B),_,[AmBEmpty,NotEquals],explanation(subset_strict)) :-
764 subset_rule(A,B,AmBEmpty),
765 get_texpr_type(A,T),
766 create_bvexpr(set_subtraction(B,A),T,BminusA),
767 create_bvexpr(empty_set,T,Empty),
768 create_bvexpr(not_equal(BminusA,Empty),pred,NotEquals).
769 subformula_explanation_rule(not_subset(A,B),_,Subs,Kind) :-
770 subformula_explanation_rule(subset(A,B),_,Subs,Kind). % it is an equivalent rewrite to the negation
771 subformula_explanation_rule(not_subset_strict(A,B),_,Subs,Kind) :-
772 subformula_explanation_rule(subset_strict(A,B),_,Subs,Kind). % it is an equivalent rewrite to the negation
773 subformula_explanation_rule(member(TM,TS),_,Children,explanation(Func)) :-
774 get_texpr_expr(TS,S),
775 subformula_member_rule(S,TM,TS,Children),!,
776 functor(S,Func,_).
777
778 subset_rule(A,B,Equals) :- % A<:B <=> A\B = {}
779 get_texpr_type(A,T),
780 create_bvexpr(set_subtraction(A,B),T,AminusB),
781 create_bvexpr(empty_set,T,Empty),
782 create_bvexpr(equal(AminusB,Empty),pred,Equals1),
783 add_texpr_description(Equals1,'Subset check: find elements in left not in right set',Equals).
784
785 :- use_module(probsrc(bsyntaxtree),[is_just_type/1,add_texpr_description/3]).
786
787 subformula_member_rule(partial_function(TDom,TRan),TM,TS,[TDoubles]) :-
788 is_just_type(TDom),
789 is_just_type(TRan),
790 !,
791 % this rule describes the plain function check, without
792 % checking domains
793 texpr_function_type(TS,FunctionType,DomType,RanType),
794 create_texpr(identifier(d),DomType,[],TDomId),
795 create_texpr(identifier(r1),RanType,[],TRanId1),
796 create_texpr(identifier(r2),RanType,[],TRanId2),
797 create_texpr(comprehension_set([TDomId,TRanId1],TExists),FunctionType,[],TDoubles0),
798 % create_exists([TRanId2],TPred,TExists1), % moved below so that used ids can be computed
799 create_texpr(couple(TDomId,TRanId1),couple(DomType,RanType),[],TCouple1),
800 create_texpr(couple(TDomId,TRanId2),couple(DomType,RanType),[],TCouple2),
801 safe_create_texpr(not_equal(TRanId1,TRanId2),pred,Unequal),
802 create_texpr(member(TCouple1,TM),pred,[],TMember1),
803 create_texpr(member(TCouple2,TM),pred,[],TMember2),
804 conjunct_predicates([Unequal,TMember1,TMember2],TPred),
805 create_exists([TRanId2],TPred,TExists1), % now also computes used identifiers; cleanup no longer required ?
806 % This is necessary to register the used identifiers
807 clean_up_pred(TExists1,[],TExists),
808 add_texpr_description(TDoubles0,'Partial function check: find counter-example pairs for functionality',TDoubles).
809 subformula_member_rule(partial_function(TA,TB),TM,TS,[TFunCheck|SetChecks]) :-
810 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
811 create_domain_range_checks(TDomain,TRange,TA,TB,SetChecks).
812 subformula_member_rule(total_function(TA,TB),TM,TS,[TFunCheck|SetChecks]) :-
813 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
814 create_total_domain_range_checks(TDomain,TRange,TA,TB,SetChecks).
815 subformula_member_rule(partial_injection(TA,TB),TM,TS,[TFunCheck,TInjCheck|SetChecks]) :-
816 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
817 create_injection_check(TM,TS,TInjCheck),
818 create_domain_range_checks(TDomain,TRange,TA,TB,SetChecks).
819 subformula_member_rule(total_injection(TA,TB),TM,TS,[TFunCheck,TInjCheck|SetChecks]) :-
820 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
821 create_injection_check(TM,TS,TInjCheck),
822 create_total_domain_range_checks(TDomain,TRange,TA,TB,SetChecks).
823 subformula_member_rule(partial_surjection(TA,TB),TM,TS,Children) :-
824 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
825 create_texpr(equal(TRange,TB),pred,[],TRanCheck),
826 create_optional_subset_check(TDomain,TA,DomChecks),
827 append([TFunCheck|DomChecks],[TRanCheck],Children).
828 subformula_member_rule(total_surjection(TA,TB),TM,TS,[TFunCheck,TDomCheck,TRanCheck]) :-
829 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
830 create_texpr(equal(TDomain,TA),pred,[],TDomCheck),
831 create_texpr(equal(TRange,TB),pred,[],TRanCheck).
832 subformula_member_rule(total_bijection(TA,TB),TM,TS,[TFunCheck,TInjCheck,TDomCheck,TRanCheck]) :-
833 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
834 create_injection_check(TM,TS,TInjCheck),
835 create_texpr(equal(TDomain,TA),pred,[],TDomCheck),
836 create_texpr(equal(TRange,TB),pred,[],TRanCheck).
837 subformula_member_rule(partial_bijection(TA,TB),TM,TS,Children) :-
838 create_function_check(TM,TS,TFunCheck,TDomain,TRange),
839 create_injection_check(TM,TS,TInjCheck),
840 create_optional_subset_check(TDomain,TA,DomChecks),
841 create_texpr(equal(TRange,TB),pred,[],TRanCheck),
842 append([TFunCheck,TInjCheck|DomChecks],[TRanCheck],Children).
843 subformula_member_rule(pow_subset(TA),TM,_TS,[NewCheck]) :-
844 % TM : POW(TA) <=> TM \ TA = {}
845 get_texpr_type(TM,Type),
846 create_bvexpr(set_subtraction(TM,TA),Type,Diff),
847 create_bvexpr(empty_set,Type,Empty),
848 create_bvexpr(equal(Diff,Empty),pred,NewCheck).
849 % TO DO: add rules for <:, <<:, FIN, POW1, FIN1
850
851 :- use_module(probsrc(typing_tools),[create_maximal_type_set/2]).
852
853 create_function_check(TM,TS,TFunCheck,TDomain,TRange) :-
854 texpr_function_type(TS,FunctionType,DomType,RanType),
855 create_maximal_type_set(DomType,TDom), % we could use typeset/0, but requires going through ast_cleanup
856 create_maximal_type_set(RanType,TRan), % ditto
857 create_bvexpr(partial_function(TDom,TRan),set(FunctionType),TFun),
858 create_bvexpr(member(TM,TFun),pred,TFunCheck0),
859 create_bvexpr(domain(TM),set(DomType),TDomain),
860 create_bvexpr(range(TM),set(RanType),TRange),
861 add_texpr_description(TFunCheck0,'Check partial function',TFunCheck).
862
863 create_domain_range_checks(TDomain,TRange,TA,TB,SetChecks) :-
864 create_optional_subset_check(TDomain,TA,DomCheck),
865 create_optional_subset_check(TRange,TB,RanCheck),
866 append(DomCheck,RanCheck,SetChecks).
867 create_total_domain_range_checks(TDomain,TRange,TA,TB,[TIsTotal|RanCheck]) :-
868 create_texpr(equal(TDomain,TA),pred,[description('Check domain of total function')],TIsTotal),
869 create_optional_subset_check(TRange,TB,RanCheck).
870 create_optional_subset_check(TSubset,TSuperset,Check) :-
871 ( is_just_type(TSuperset) ->
872 Check = []
873 ;
874 create_texpr(subset(TSubset,TSuperset),pred,[description('Check domain/range of function')],TPred),
875 Check = [TPred]).
876
877 create_injection_check(TM,TS,TCheckExpr) :-
878 texpr_function_type(TS,FunctionType,DomType,RanType),
879 create_texpr(identifier(d1),DomType,[],TDomId1),
880 create_texpr(identifier(d2),DomType,[],TDomId2),
881 create_texpr(identifier(r1),RanType,[],TRanId),
882 create_texpr(comprehension_set([TDomId1,TRanId],TExists),FunctionType,[bv_function_check(TM)],TCheckExpr),
883 %create_exists([TDomId2],TPred,TExists1),
884 create_texpr(couple(TDomId1,TRanId),couple(DomType,RanType),[],TCouple1),
885 create_texpr(couple(TDomId2,TRanId),couple(DomType,RanType),[],TCouple2),
886 create_texpr(not_equal(TDomId1,TDomId2),pred,[],Unequal),
887 create_texpr(member(TCouple1,TM),pred,[],TMember1),
888 create_texpr(member(TCouple2,TM),pred,[],TMember2),
889 conjunct_predicates([Unequal,TMember1,TMember2],TPred),
890 create_exists([TDomId2],TPred,TExists1), % now also computes used identifiers; cleanup no longer required ?
891 % This is necessary to register the used identifiers
892 clean_up_pred(TExists1,[],TExists2),
893 add_texpr_description(TExists2,'Find counter-example pairs for injectivity',TExists).
894
895 texpr_function_type(TFun,FunType,DomType,RanType) :-
896 get_texpr_type(TFun,set(FunType)),
897 FunType = set(couple(DomType,RanType)).
898
899
900 create_bvexpr(Expr,Type,TExpr) :-
901 create_texpr(Expr,Type,[bvisual],TExpr).
902 is_not_bvexpr(TExpr) :-
903 get_texpr_info(TExpr,Infos),nonmember(bvisual,Infos).
904 %is_bvexpr(TExpr) :- get_texpr_info(TExpr,Infos),memberchk(bvisual,Infos).
905
906 no_empty_set(E) :- \+ is_empty_set(E).
907
908 is_empty_set(b(E,_,_)) :- is_empty_set_aux(E).
909 is_empty_set_aux(empty_set).
910 is_empty_set_aux(empty_sequence).
911 is_empty_set_aux(value(X)) :- X==[].
912
913 get_subformulas(TFormula,Subs,Kind) :-
914 is_texpr(TFormula),
915 get_texpr_expr(TFormula,Formula),
916 subformula_rule(Formula,TFormula,Subs,Kind),!.
917 get_subformulas(TFormula,Subs,syntaxtraversion) :-
918 is_texpr(TFormula),!,
919 bv_syntaxtraversion(TFormula,Subs).
920 get_subformulas(named_subformula(_,TFormula,_),Subs,Kind) :- !,
921 (get_subformulas(TFormula,TSubs,Kind),TSubs \= []
922 -> Subs = [TFormula]
923 ; Kind=syntaxtraversion, Subs=[]).
924 get_subformulas(textnode(_,Subs),Subs,textnode) :- !.
925 get_subformulas(textnode3(_,_,Subs),Subs,textnode) :- !.
926 get_subformulas(included_machine(_,_,Subs),Subs,textnode) :- !.
927 get_subformulas(guard(_Name,Parameters,Guard),Subs,guard) :- !,
928 conjunction_to_list(Guard,GuardSubs),
929 append(Parameters,GuardSubs,Subs).
930 get_subformulas(variant(_Name,_ConvOrAnt,Variant),Subs,variant) :- !,
931 Subs = [Variant].
932 get_subformulas(ltl_named_formula(_,String),Subs,ltl_formula) :- !,
933 temporal_parser(String,ltl,Formula),
934 Subs = [ltl_formula(String,Formula)].
935 get_subformulas(ltl_formula(_,Formula),Subs,ltl_formula) :- !,
936 get_bv_ltl_sub_formulas(Formula,Subs).
937 get_subformulas(guard_theorems(_Name,[],_Guard,Theorems),Subs,guard_theorems) :- !,
938 conjunction_to_list(Theorems,Subs).
939 get_subformulas(guard_theorems(_Name,Parameters,Guard,Theorems),Subs,guard_theorems) :- !,
940 append(Parameters,[b(implication(Guard,Theorems),pred,[])],Subs).
941 %get_subformulas(cbc_path(_,Path,_),Subs) :- !,
942 % append(Path,[X],XPath),
943 % findall(cbc_path(LastStateID,XPath,X), sap:cb_path(LastStateID,XPath,_), Subs).
944 get_subformulas(bind(_,_),S,K) :- !,S=[], K=none.
945 get_subformulas(Node,[],none) :- format('No subformulas for ~w~n',[Node]).
946
947 bv_syntaxtraversion(b(rec(Fields),_,_),Subs) :-
948 maplist(transform_field,Fields,Subs1),!,
949 Subs = Subs1. % Note: there are no new quantified names/identifiers; just field names
950 bv_syntaxtraversion(TFormula,Subs) :-
951 syntaxtraversion(TFormula,_,_,_,Subs1,Names),
952 (Names = [] -> filter_trivial_expressions(Subs1,Subs) ; Subs = []).
953
954 transform_field(field(Name,TVal),named_subformula(Name,TVal,'$no_error')).
955
956 :- use_module(probsrc(preferences),[get_prob_application_type/1]).
957 filter_trivial_expressions([],[]).
958 filter_trivial_expressions([TI|Irest],Out) :-
959 get_texpr_expr(TI,I),get_texpr_info(TI,Info),
960 ( get_preference(show_bvisual_formula_functor_from,Lim), Lim>=0 -> Out = [TI|Orest]
961 % only functor shown when expanding; we should show all sub formulas; otherwise it is confusing to the user
962 ; get_prob_application_type(Type), Type \= tcltk -> Out = [TI|Orest] % in ProB2 we always just show the functor now
963 ; is_trivial(I,Info) -> Out = Orest
964 ; Out = [TI|Orest]),
965 filter_trivial_expressions(Irest,Orest).
966
967 % is_trivial/2 is true for expressions that should not appear as single nodes
968 % in the evaluation tree, because they are too simple.
969 % The first argument is the expression, the second its information list
970 is_trivial(integer(_),_).
971 is_trivial(integer_set(_),_).
972 is_trivial(empty_set,_).
973 is_trivial(boolean_true,_).
974 is_trivial(boolean_false,_).
975 is_trivial(bool_set,_).
976 is_trivial(truth,_).
977 is_trivial(falsity,_).
978 is_trivial(identifier(_),Info) :-
979 memberchk(given_set,Info).
980 is_trivial(identifier(_),Info) :-
981 memberchk(enumerated_set_element,Info).
982 % TO DO: treat value(_) ?
983
984 :- use_module(probsrc(tools_strings),[ajoin/2]).
985 :- use_module(probsrc(specfile),[animation_minor_mode/1, csp_mode/0, csp_with_bz_mode/0, b_or_z_mode/0,
986 get_specification_description/2]).
987 get_node_label(inv,invariants) :- animation_minor_mode(eventb),!.
988 get_node_label(inv,I):- !, get_specification_description(invariant,I).
989 get_node_label(invariants,invariants) :- animation_minor_mode(eventb),!.
990 get_node_label(invariants,I):- !, get_specification_description(invariants,I).
991 get_node_label(axioms,axioms) :- animation_minor_mode(eventb),!.
992 get_node_label(axioms,S):- !, get_specification_description(properties,S).
993 get_node_label(variants,variants) :- animation_minor_mode(eventb),!.
994 get_node_label(variants,'VARIANT') :- !. % not used there
995 get_node_label(theoremsc,'theorems (on constants)') :- animation_minor_mode(eventb),!.
996 get_node_label(theoremsc,'ASSUME (on constants)') :- animation_minor_mode(tla),!.
997 get_node_label(theoremsc,'ALL ASSERTIONS (on CONSTANTS)') :- b_get_assertion_count(static,AllNr,MainNr), MainNr < AllNr, !.
998 get_node_label(theoremsc,'ASSERTIONS (on CONSTANTS)') :- !.
999 get_node_label(theoremscm,'MAIN ASSERTIONS (on CONSTANTS)') :- !. % should only trigger in B mode at the moment
1000 get_node_label(theoremsv,'theorems (on variables)') :- animation_minor_mode(eventb),!.
1001 get_node_label(theoremsv,'ALL ASSERTIONS (on VARIABLES)') :- b_get_assertion_count(dynamic,AllNr,MainNr), MainNr < AllNr, !.
1002 get_node_label(theoremsv,'ASSERTIONS (on VARIABLES)') :- !.
1003 get_node_label(theoremsvm,'MAIN ASSERTIONS (on VARIABLES)') :- !. % should only trigger in B mode at the moment
1004 get_node_label(sets,'sets') :- animation_minor_mode(eventb),!.
1005 get_node_label(sets,'SETS') :- !.
1006 get_node_label(freetypes,'inductive datatypes') :- animation_minor_mode(eventb),!.
1007 get_node_label(freetypes,'FREETYPES') :- !.
1008 get_node_label(goal,'GOAL') :- !.
1009 get_node_label(variables,'variables') :- animation_minor_mode(eventb),!.
1010 get_node_label(variables,'VARIABLES') :- !.
1011 get_node_label(constants,'constants') :- animation_minor_mode(eventb),!.
1012 get_node_label(constants,'CONSTANTS') :- !.
1013 get_node_label(guards_top_level,'event guards') :- animation_minor_mode(eventb),!.
1014 get_node_label(guards_top_level,'ACTIONS (guards)') :- animation_minor_mode(tla),!.
1015 get_node_label(guards_top_level,'OPERATIONS (guards/preconditions)') :- !. % GUARDS/PRE
1016 get_node_label(guards_subsidiary,'subsidiary event guards') :- animation_minor_mode(eventb),!.
1017 get_node_label(guards_subsidiary,'SUBSIDIARY ACTIONS (guards)') :- animation_minor_mode(tla),!.
1018 get_node_label(guards_subsidiary,'SUBSIDIARY OPERATIONS (guards/preconditions)') :- !. % GUARDS/PRE
1019 get_node_label(guard_theorems,'theorems (in guards)') :- !.
1020 get_node_label(user_formulas,'USER FORMULAS') :- !.
1021 get_node_label(definitions,'theory operators') :- animation_minor_mode(eventb),!.
1022 get_node_label(definitions,'DEFINITIONS') :- !.
1023 get_node_label(included_machines,'inclusions') :- animation_minor_mode(eventb),!. % shows refines and sees
1024 get_node_label(included_machines,'INCLUDED MACHINES') :- !.
1025 get_node_label(ltl_formulas,'LTL Formulas') :- !.
1026 %get_node_label(cbc_tests,'CBC_TESTS') :- !.
1027 get_node_label(channels,'channel') :- !.
1028 get_node_label(datatypes,'datatype') :- !.
1029 get_node_label(subtypes,'subtype') :- !.
1030 get_node_label(raw_state,'Raw State') :- !.
1031 get_node_label(Atom,Label) :- is_property_atom(Atom,Nr),!,
1032 (xtl_mode -> ajoin(['XTL Property ',Nr],Label) ; Label='property').
1033 get_node_label(Id,Label) :-
1034 stored_formula(Id,Formula),!,
1035 get_node_label2(Formula,Label).
1036 get_node_label(Id,'??') :- format('Unknown node: ~w~n',[Id]).
1037
1038 get_node_label2(textnode(Text,_),Text) :- !.
1039 get_node_label2(textnode3(Text,_,_),Text) :- !.
1040 get_node_label2(included_machine(Text,_,_),Text) :- !.
1041 get_node_label2(bind(TID,_),ID) :- !,
1042 (is_texpr(TID),get_texpr_id(TID,R) -> ID = R ; ID = TID).
1043 get_node_label2(named_subformula(Name,_,_),Res) :- !, Res=Name.
1044 get_node_label2(guard(Name,_Parameters,_Guard),Name) :- !.
1045 get_node_label2(guard_theorems(Name,_Parameters,_Guard,_Theorems),Name) :- !.
1046 get_node_label2(variant(OpName,ConvOrAnt,_Variant),Name) :- !,
1047 ajoin([OpName,' |-> ',ConvOrAnt],Name).
1048 get_node_label2(ltl_named_formula(Name,_),Res) :- !, Res=Name.
1049 get_node_label2(ltl_formula(String,_Tree),Name) :- !, strip_newlines(String,Name).
1050 get_node_label2(TExpr,Label) :-
1051 is_texpr(TExpr),!,
1052 % Mode = unicode, latex or ascii; but unicode_mode makes Viewer slower
1053 with_bvisual2_translation_mode(get_node_label3(TExpr,Label)).
1054 get_node_label2(Term,Label) :-
1055 functor(Term,F,Arity),
1056 ajoin(['unknown node type: ',F,'/',Arity],Label).
1057
1058 get_node_label3(TExpr,Label) :-
1059 with_bvisual2_translation_mode(translate_subst_or_bexpr_with_limit(TExpr,500,TS)),
1060 ( get_preference(show_bvisual_formula_functor_from,Lim), Lim>=0,
1061 get_texpr_top_level_symbol(TExpr,Functor,_,_OpType),
1062 %(OpType=infix ; OpType=postfix),
1063 (Lim=0 -> true ; atom_length(TS,Len), Len>=Lim)
1064 -> %ajoin([Functor,' \x25AB\ ',TS],Label) % unicode small block / box
1065 ajoin(['[',Functor, '] ',TS],Label0)
1066 ; Label0=TS
1067 ),
1068 (animation_minor_mode(eventb), %maybe in future we also have proof info for Classical B
1069 get_preference(show_bvisual_proof_info_icons,true),
1070 get_discharged_info(TExpr,Proven,_)
1071 -> (Proven=proven, _SHOW=full
1072 -> ajoin([' \x2713\ ',Label0],Label) % alternatives \x2705\ \x2713\ (10003) \x2714\ \x22A2\ (turnstile)
1073 % \x2705\ (crashes sometimes on macOS Tk)
1074 ; ajoin([' \x25EF\ ',Label0],Label) % x2B55 \x22AC\ (turnstile with bar)
1075 )
1076 ; Label=Label0).
1077
1078
1079 :- dynamic bvisual2_translation_mode/1.
1080 bvisual2_translation_mode(unicode). % any mode accepted by translate:set_translation_mode
1081 set_bvisual2_translation_mode(X) :- retractall(bvisual2_translation_mode(_)),
1082 assertz(bvisual2_translation_mode(X)).
1083
1084 :- use_module(probsrc(translate), [with_translation_mode/2]).
1085 :- use_module(probsrc(preferences), [temporary_set_preference/3,reset_temporary_preference/2]).
1086 with_bvisual2_translation_mode(Call) :-
1087 bvisual2_translation_mode(Mode),
1088 temporary_set_preference(expand_avl_upto,5000,Chng),
1089 call_cleanup(with_translation_mode(Mode,Call),
1090 reset_temporary_preference(expand_avl_upto,Chng)).
1091
1092
1093 register_top_level :- register_top_level(_).
1094 register_top_level(Id) :-
1095 ? top_level2(Id,Formula,Subs), % print(register(Id,Subs)),nl,
1096 register_top_level_formula(Id,Formula,Subs),
1097 fail.
1098 register_top_level(_Id).
1099
1100 % useful to re-register e.g. definitions after b_load_additional_definitions_file/1 or similar is called
1101 % Note: it should not be done in Tk while the State View dialog is open
1102
1103 bv_re_register_definitions_if_necessary :-
1104 additional_defs_loaded,!, re_register_top_level(definitions).
1105 bv_re_register_definitions_if_necessary.
1106
1107 re_register_top_level(Id) :-
1108 delete_top_level_formula(Id),
1109 register_top_level(Id).
1110
1111
1112 :- use_module(probsrc(specfile),[b_or_z_mode/0, classical_b_mode/0,spec_file_has_been_successfully_loaded/0]).
1113 :- use_module(probsrc(b_global_sets),[all_elements_of_type/2, b_get_fd_type_bounds/3]).
1114 :- use_module(probsrc(bmachine),[b_get_machine_goal/1]).
1115 b_or_z_successsful_mode :- b_or_z_mode,
1116 true. %spec_file_has_been_successfully_loaded. % make unit test fail
1117
1118 % top_level2(SectionID, ValueNode, ListOfSubs)
1119 top_level2(variables,textnode('',Variables),Variables) :- b_or_z_successsful_mode,
1120 variables_should_be_included,
1121 b_get_machine_variables_in_original_order(Variables).
1122 top_level2(constants,textnode('',Constants),Constants) :- b_or_z_successsful_mode,
1123 variables_should_be_included,
1124 b_get_machine_constants(Constants).
1125 top_level2(sets,textnode('',Sets),Sets) :- b_or_z_successsful_mode,
1126 findall(bind(S,All),
1127 bv_top_level_set(S,All),Sets), Sets \= [].
1128 top_level2(freetypes,textnode('',Sets),Sets) :- b_or_z_successsful_mode,
1129 findall(All, top_level_freetype(_Set,All),Sets), Sets \= [].
1130 top_level2(goal,Goal,Subs) :- b_or_z_successsful_mode,
1131 b_get_machine_goal(Goal),
1132 conjunction_to_list(Goal,Subs).
1133 top_level2(inv,Invariant,Subs) :- b_or_z_successsful_mode,
1134 get_invariant_list_with_proof_info(Subs),
1135 conjunct_predicates(Subs,Invariant).
1136 top_level2(variants,textnode('',Variants),Variants) :- animation_minor_mode(eventb),
1137 spec_file_has_been_successfully_loaded,
1138 findall(variant(Name,ConvOrAnt,Variant),
1139 b_get_operation_variant(Name,ConvOrAnt,Variant),
1140 Variants),
1141 Variants = [_|_].
1142 top_level2(axioms,Props,AllSubs) :- b_or_z_successsful_mode,
1143 b_machine_has_constants_or_properties,
1144 b_get_properties_from_machine(Props),
1145 conjunction_to_list(Props,Subs),
1146 findall(AddPred,b_machine_additional_property(AddPred),VSubs), % could be VALUES clause
1147 (VSubs=[] -> AllSubs = Subs ; append(Subs,VSubs,AllSubs)).
1148 top_level2(theoremsc,Pred,Assertions) :- b_or_z_successsful_mode,
1149 b_get_static_assertions_from_machine(Assertions),Assertions\=[],
1150 conjunct_predicates(Assertions,Pred).
1151 top_level2(theoremscm,Pred,Assertions) :- b_or_z_successsful_mode,
1152 b_get_assertions_from_main_machine(static,Assertions),
1153 %Assertions\=[], % in case we have less: show that there are none
1154 ? b_get_assertion_count(static,AllNr,MainNr), MainNr < AllNr,
1155 conjunct_predicates(Assertions,Pred).
1156 top_level2(theoremsv,Pred,Assertions) :- b_or_z_successsful_mode,
1157 b_get_dynamic_assertions_from_machine(Assertions),Assertions\=[],
1158 conjunct_predicates(Assertions,Pred).
1159 top_level2(theoremsvm,Pred,Assertions) :- b_or_z_successsful_mode,
1160 b_get_assertions_from_main_machine(dynamic,Assertions),
1161 %Assertions\=[], % in case we have less: show that there are none
1162 b_get_assertion_count(dynamic,AllNr,MainNr), MainNr < AllNr,
1163 conjunct_predicates(Assertions,Pred).
1164 top_level2(guards_top_level,textnode('',EventGuards),EventGuards) :- b_or_z_successsful_mode,
1165 findall(guard(Name,Params,Guard),
1166 get_top_level_guard(Name,Params,Guard),EventGuards),
1167 EventGuards = [_|_].
1168 top_level2(guards_subsidiary,textnode('',EventGuards),EventGuards) :- b_or_z_successsful_mode,
1169 findall(guard(Name,Params,Guard),
1170 get_subsidiary_guard(Name,Params,Guard),EventGuards),
1171 EventGuards = [_|_].
1172 top_level2(guard_theorems,textnode('',EventGuards),EventGuards) :- b_or_z_successsful_mode,
1173 findall(guard_theorems(Name,Params,Guard,GuardTheorems),
1174 ( b_get_machine_operation(Name,_,_,TBody),
1175 get_texpr_expr(TBody,Body),
1176 Body = rlevent(_Name,_Section,_Status,Params,Guard,Theorems,
1177 _Actions,_VWitnesses,_PWitnesses,_Unmod,_AbstractEvents),
1178 Theorems \= [],
1179 conjunct_predicates(Theorems,GuardTheorems)
1180 ),
1181 EventGuards),
1182 EventGuards = [_|_].
1183 top_level2(user_formulas,textnode('',UserPredicates),UserPredicates) :- b_or_z_successsful_mode,
1184 findall(UP,subnode(user_formulas,UP),UserPredicates), UserPredicates\=[].
1185 top_level2(definitions,textnode('',Defs),Defs) :- b_or_z_successsful_mode,
1186 pre_expand_typing_scope([variables_and_additional_defs],ExpandedScope),
1187 get_definitions_section(DefSection), % get it only once
1188 full_b_machine(Machine),
1189 findall(Node,get_definition(Node,pre_ctxt(ExpandedScope,DefSection,Machine)),Defs),
1190 Defs\=[].
1191 top_level2(included_machines,textnode('',Subs),Subs) :- b_or_z_successsful_mode,
1192 main_machine_name(Main),
1193 get_machine_inclusions(Main,Subs),
1194 Subs \= [].
1195 top_level2(ltl_formulas,textnode('',Defs),Defs) :- b_or_z_successsful_mode,
1196 findall(Node,get_ltl_named_formula(Node),Defs), Defs\=[].
1197 top_level2(channels,textnode('',Channels),Channels) :- csp_mode, spec_file_has_been_successfully_loaded,
1198 findall(Node,get_csp_channel(Node),Cs), Cs\=[], sort(Cs,Channels).
1199 top_level2(datatypes,textnode('',DT),DT) :- csp_mode, spec_file_has_been_successfully_loaded,
1200 findall(Node,get_csp_datatype(Node),Cs), Cs\=[], sort(Cs,DT).
1201 top_level2(subtypes,textnode('',DT),DT) :- csp_mode, spec_file_has_been_successfully_loaded,
1202 findall(Node,get_csp_subtype(Node),Cs), Cs\=[], sort(Cs,DT).
1203 top_level2(raw_state,raw_state_pp,[]) :- \+ b_or_z_mode,
1204 spec_file_has_been_successfully_loaded.
1205 top_level2(Atom,property_pp(Nr),[]) :- xtl_mode, % probably also useful for CSP mode
1206 spec_file_has_been_successfully_loaded,
1207 is_property_atom(Atom,Nr).
1208 % we are now using a custom tree_inspector for the CBC Tests
1209 /* top_level2(cbc_tests,textnode('',Paths),Paths) :- b_or_z_mode,
1210 get_preference(user_is_an_expert_with_accessto_source_distribution,true),
1211 %sap:cb_path(_,[_],_), % we have generated at least one test-case
1212 % TO DO: we need a way to refresh this information after test-cases have been generated
1213 % currently the only way seems to close the evaluation view, reload, generate the tests and then open the view
1214 Paths = [cbc_path(root,[],'INITIALISATION')].
1215 */
1216
1217 :- use_module(library(between),[between/3]).
1218 :- use_module(probsrc(xtl_interface),[xtl_nr_state_properties/1]).
1219 % Tcl/Tk requires atoms as top_level properties
1220 is_property_atom(Name,Nr) :-
1221 (xtl_mode, xtl_nr_state_properties(MaxNr) % use value provided in XTL file
1222 -> true
1223 ; MaxNr = 8), % default
1224 ? between(1,MaxNr,Nr),
1225 ajoin([property,Nr],Name).
1226
1227 :- use_module(probcspsrc(haskell_csp),[channel_type_list/2, dataTypeDef/2, subTypeDef/2]).
1228 :- use_module(probsrc(translate),[translate_cspm_expression/2]).
1229 get_csp_channel(bind(Channel,string(TypeString))) :-
1230 channel_type_list(Channel,TypeList), % something like [dataType('SubSubMsg'),intType,boolType]
1231 translate_cspm_expression(dotTuple(TypeList),TypeString).
1232 get_csp_datatype(bind(DT,string(TypeString))) :-
1233 dataTypeDef(DT,TypeList), % something like [dataType('SubSubMsg'),intType,boolType]
1234 translate_cspm_expression(dataTypeDef(TypeList),TypeString).
1235 get_csp_subtype(bind(DT,string(TypeString))) :-
1236 subTypeDef(DT,TypeList), % something like [dataType('SubSubMsg'),intType,boolType]
1237 translate_cspm_expression(dataTypeDef(TypeList),TypeString).
1238
1239 :- use_module(probsrc(b_machine_hierarchy),[main_machine_name/1, machine_references/2, get_machine_short_desc/2]).
1240 get_machine_inclusions(M,Subs) :-
1241 findall(included_machine(SubMachine,Text,Subs),
1242 (machine_references(M,Refs),
1243 member(ref(Kind,SubMachine,Prefix),Refs),
1244 (Prefix='' -> Text=Kind ; ajoin([Kind,' with prefix ',Prefix],Text)),
1245 get_machine_inclusions(SubMachine,Subs)),
1246 Subs).
1247
1248 :- use_module(probsrc(bmachine)).
1249 :- use_module(probsrc(pref_definitions),[b_get_set_pref_definition/3]).
1250 get_definition(textnode('GOAL',Subs),_) :- b_get_machine_goal(Goal), conjunction_to_list(Goal,Subs).
1251 get_definition(textnode('SCOPE',Subs),_) :- b_get_machine_searchscope(S), conjunction_to_list(S,Subs).
1252 get_definition(textnode('HEURISTIC_FUNCTION',[F]),_) :- b_get_machine_heuristic_function(F).
1253 get_definition(textnode(STR,[F]),_) :- b_get_machine_animation_expression(STR,F).
1254 get_definition(textnode(Name,[F]),_) :- b_get_machine_animation_function(F,Nr),
1255 number_codes(Nr,NC), append("ANIMATION_FUNCTION",NC,C), atom_codes(Name,C).
1256 ?get_definition(textnode(Name,[Term]),_) :- b_get_machine_setscope(SetName,Term),
1257 atom_codes(SetName,NC), append("scope_",NC,C), atom_codes(Name,C).
1258 get_definition(textnode(Name,[b(integer(Nr),integer,[])]),_) :- b_get_machine_operation_max(OpName,Nr),
1259 atom_codes(OpName,NC), append("MAX_OPERATIONS_",NC,C), atom_codes(Name,C).
1260 get_definition(textnode(PrefixCategory,Subs),PreExpandContext) :-
1261 ? special_def_category(PrefixCategory), % group special prefixes separately
1262 findall(named_subformula(DefName,Body,Error),
1263 (special_def_prefix(Prefix,Match,PrefixCategory),
1264 (Match=perfect -> DefName=Prefix ; true),
1265 get_useful_definition_for_bvisual2(expression,Prefix,DefName,PreExpandContext,_Pos,Body,Error)),
1266 Subs), Subs \= [].
1267 get_definition(named_subformula(DefName,Body,Error),PreExpandContext) :-
1268 ? get_useful_definition_for_bvisual2(_,'',DefName,PreExpandContext,_Pos,Body,Error).
1269 get_definition(textnode3(Header,DefBodyStr,
1270 [textnode3('Theory',FullThName,[]),
1271 textnode3('Body',DefBodyStr,[]) | Tail
1272 ]),_PreExpandContext) :-
1273 ? stored_operator_direct_definition(Name,ProjName,TheoryName,Parameters,RawDefBody,RawWD,ParaTypes,_Kind),
1274 ajoin([ProjName,'.',TheoryName],FullThName),
1275 translate_eventb_direct_definition_header(Name,Parameters,Header),
1276 with_bvisual2_translation_mode(translate_eventb_direct_definition_body(RawDefBody,DefBodyStr)),
1277 (ParaTypes = [] -> Tail = Tail2
1278 ; debug_mode(off), \+ ground(ParaTypes) -> Tail=Tail2 % non-ground types are for destructors, ... are not useful for average user
1279 ; Tail = [textnode3('Type Parameters',TypeParaStr,[])|Tail2],
1280 write_term_to_codes(ParaTypes,PC,[]),
1281 atom_codes(TypeParaStr,PC)
1282 ),
1283 (RawWD=truth(_) -> Tail2=[]
1284 ; Tail2 = [textnode3('WD Condition',WDStr,[])],
1285 with_bvisual2_translation_mode(translate_eventb_direct_definition_body(RawWD,WDStr))
1286 ).
1287 % TODO: show mapped Event-B and recursive operators; also: above still shown as string and type paras not shown
1288 % TO DO: we could try and get more complex definitions if get_preference(type_check_definitions,true), see type_check_definitions; or we could just pretty print the RAW ast using transform_raw;
1289 % NOTE: special definitions are also declared in
1290 % - procDoSyntaxColouring in main_prob_tcltk_gui.tcl
1291 % - isProBSpecialDefinitionName in Utils.java in de.be4.classicalb.core.parser.util
1292
1293 special_def_category('CUSTOM_GRAPH').
1294 special_def_category('VISB').
1295 special_def_category('PREFERENCES').
1296 special_def_category('UML_SEQUENCE').
1297 special_def_category('SIMB').
1298 % TODO: add ANIMATION function, ASSERT_CTL, ASSERT_LTL, GAME_MCTS, ...
1299 special_def_prefix('CUSTOM_GRAPH_EDGES',prefix,'CUSTOM_GRAPH').
1300 special_def_prefix('CUSTOM_GRAPH_NODES',prefix,'CUSTOM_GRAPH').
1301 special_def_prefix('CUSTOM_GRAPH',prefix,'CUSTOM_GRAPH'). % perfect match required
1302 special_def_prefix('VISB_DEFINITIONS_FILE',perfect,'VISB'). % perfect match required
1303 special_def_prefix('VISB_JSON_FILE',perfect,'VISB'). % perfect match required
1304 special_def_prefix('VISB_SVG_BOX',perfect,'VISB'). % perfect match required
1305 special_def_prefix('VISB_SVG_CONTENTS',prefix,'VISB').
1306 special_def_prefix('VISB_SVG_OBJECTS',prefix,'VISB').
1307 special_def_prefix('VISB_SVG_UPDATES',prefix,'VISB').
1308 special_def_prefix('VISB_SVG_EVENTS',prefix,'VISB').
1309 special_def_prefix('VISB_SVG_HOVERS',prefix,'VISB').
1310 special_def_prefix('SET_PREF_',prefix,'PREFERENCES').
1311 special_def_prefix('scope_',prefix,'PREFERENCES').
1312 special_def_prefix('MAX_OPERATIONS_',prefix,'PREFERENCES').
1313 special_def_prefix('OPERATION_REUSE_OFF_',prefix,'PREFERENCES').
1314 special_def_prefix('SEQUENCE_CHART_',prefix,'UML_SEQUENCE').
1315 % these definitions are already displayed by bvisual2 separately (via b_get_machine_animation_expression, ...)
1316 special_def_prefix('FORCE_SYMMETRY_',prefix,special).
1317 special_def_prefix('GOAL',perfect,special).
1318 special_def_prefix('SCOPE',perfect,special).
1319 special_def_prefix('HEURISTIC_FUNCTION',perfect,special).
1320 special_def_prefix('ANIMATION_FUNCTION',prefix,special).
1321 special_def_prefix('ANIMATION_EXPRESSION',prefix,special).
1322 special_def_prefix('DESCRIPTION_FOR_',prefix,special).
1323 special_def_prefix('GAME_PLAYER',perfect,special).
1324 special_def_prefix('GAME_OVER',perfect,special).
1325 special_def_prefix('GAME_VALUE',perfect,special).
1326 special_def_prefix('GAME_MCTS_RUNS',perfect,special).
1327 special_def_prefix('GAME_MCTS_TIMEOUT',perfect,special).
1328 special_def_prefix('GAME_MCTS_CACHE_LAST_TREE',perfect,special).
1329 special_def_prefix('SIMB_JSON_FILE',perfect,'SIMB').
1330
1331 ?is_special_def_name(DefName) :- special_def_prefix(SPrefix,Match,_),
1332 (Match=prefect -> DefName=SPrefix ; atom_prefix(SPrefix,DefName)).
1333
1334 % only get definitions matching prefix; or if Prefix='' only show those not matching any special prefix
1335 get_useful_definition_for_bvisual2(Type,Prefix,DefName,pre_ctxt(ExpandedScope,DefSection,Machine), DefPos,Body,Error) :-
1336 ? b_sorted_b_definition_prefixed(Type,Prefix,DefName,DefPos),
1337 ? (Prefix='' -> \+ is_special_def_name(DefName) ; true),
1338 ? (b_get_typed_definition_with_error_list(Machine,DefSection,DefName,ExpandedScope,Body,
1339 ErrorsAndWarnings,Success)
1340 -> \+ dangerous_body(Body),
1341 (Success=true -> Error='$no_error'
1342 ? ; member(Err1,ErrorsAndWarnings),
1343 get_perror(Err1,_Kind,Msg,_Pos) -> Error=Msg
1344 )
1345 ; % the definition has parameters, TODO: pretty print a bit like theory operators
1346 fail, Error=failure,
1347 b_get_definition(DefName,_DefType,_Paras,RawDefBody,_Deps),
1348 with_bvisual2_translation_mode(translate_eventb_direct_definition_body(RawDefBody,DefBodyStr)),
1349 Body = b(string(DefBodyStr),string,[])
1350 ).
1351
1352 % we do not want to perform IO while expanding the state view
1353 % e.g., if you include LibraryIO.def you would have GET_CODE_STDIN whose evaluation waits for user input
1354 % TODO: we should probably also check during evaluation that we do not perform io or that IO is possible?
1355 :- use_module(probsrc(external_functions), [ performs_io/1]).
1356 dangerous_body(b(external_function_call(FUNCTION,_),_,_)) :- performs_io(FUNCTION).
1357
1358 % ASSERT_LTL
1359 % at the top-level we generate named formulas; we only parse when expanding later
1360 % solves issues e.g., in CSP-B mode where the formulas use CSP constructs but the csp-guide has not been added yet
1361 % see tests 1257, 1259, 1644, 1647
1362 get_ltl_named_formula(ltl_named_formula(FullName,FormulaAsString)) :-
1363 get_ltl_formula_strings(Names,Strings),
1364 nth1(Nr,Names,Name),
1365 ajoin(['ASSERT_LTL',Name],FullName), % in CSP mode this would actually be assert Main |= LTL "formula"
1366 (nth1(Nr,Strings,FormulaAsString) -> true).
1367
1368 gen_ltl_bv_sub(Tree,ltl_formula(String,Tree)) :-
1369 pp_ltl_formula(Tree,String).
1370
1371 get_bv_ltl_sub_formulas(ap(bpred(Pred)),Subs) :- !, Subs = [Pred].
1372 get_bv_ltl_sub_formulas(LTLTee,BV_Subs) :-
1373 get_ltl_sub_formulas(LTLTee,_,LTLSubs),!,
1374 maplist(gen_ltl_bv_sub,LTLSubs,BV_Subs).
1375 get_bv_ltl_sub_formulas(_,[]).
1376
1377
1378 :- use_module(probsrc(b_operation_guards),[get_unsimplified_operation_enabling_condition/5]).
1379 :- use_module(probsrc(bmachine),[b_top_level_operation/1]).
1380 get_top_level_guard(OpName,Params,Guard) :-
1381 ? b_top_level_operation(OpName),
1382 \+ is_initialisation_op(OpName),
1383 get_unsimplified_operation_enabling_condition(OpName,Params,Guard,_BecomesSuchVars,_Precise).
1384 get_subsidiary_guard(OpName,Params,Guard) :- % get guards for non-top-level operations
1385 ? get_unsimplified_operation_enabling_condition(OpName,Params,Guard,_BecomesSuchVars,_Precise),
1386 \+ b_top_level_operation(OpName),
1387 \+ is_initialisation_op(OpName).
1388
1389 is_initialisation_op('$setup_constants').
1390 is_initialisation_op('$initialise_machine').
1391
1392 :- use_module(probsrc(custom_explicit_sets),[construct_interval_closure/3]).
1393 :- use_module(probsrc(kernel_freetypes),[registered_freetype/2]).
1394 :- use_module(probsrc(bmachine),[b_get_machine_set/2]).
1395 :- use_module(probsrc(b_global_sets),[b_replaced_global_set/2]).
1396 bv_top_level_set(TSet,AllEls) :- b_or_z_mode,
1397 ? b_get_machine_set(Set,TSet),
1398 (b_get_fd_type_bounds(Set,_Low,inf)
1399 -> %L1 is Low+1, L2 is Low+2,
1400 %AllEls= [fd(Low,Set),fd(L1,Set),fd(L2,Set),string('...')] % TODO: avoid type error
1401 AllEls = string('infinite deferred set')
1402 ; all_elements_of_type(Set,AllEls)).
1403 bv_top_level_set(b(identifier(ID),any,[]),string(TS)) :- % replaced by record construction /detection
1404 ? b_replaced_global_set(ID,NewTypeExpr),
1405 with_bvisual2_translation_mode(translate_subst_or_bexpr_with_limit(NewTypeExpr,500,TS)).
1406 bv_top_level_set(b(identifier('INT'),set(integer),[]),INTVAL) :- % we can return both typed ids and atomic ids
1407 ? classical_b_mode, % INT only exists in pure B mode
1408 get_preference(maxint,MAXINT), get_preference(minint,MININT),
1409 construct_interval_closure(MININT,MAXINT,INTVAL).
1410
1411 top_level_freetype(Set,textnode3(TopSet,'',AllCases)) :-
1412 animation_minor_mode(eventb), % here types contain Prolog variables (polymorphism) + we have the constant(_) type
1413 ? registered_freetype(SetP,Cases),
1414 (SetP =.. [Set|TypeParas] -> true ; add_error(bvisual2,'Cannot instantiate type paras:',SetP)),
1415 get_freetype_params(Set,TypeParaNames,TypeParas),
1416 (TypeParaNames = [] -> TopSet = Set ; ajoin_with_sep(TypeParaNames,',',Ps),ajoin([Set,'(',Ps,')'],TopSet)),
1417 findall(textnode3(Case,CaseString,Subs),
1418 (member(case(CaseP,T),Cases),functor(CaseP,Case,_),
1419 bv_pretty_type(T,TS), ajoin([Case,':',TS],CaseString),
1420 findall(textnode3(Destructor,TD,[]),get_destructor_for_freetype(SetP,Case,Destructor,TD),Subs)
1421 ),AllCases).
1422 top_level_freetype(Set,AllCases) :- b_or_z_mode, \+ animation_minor_mode(eventb),
1423 ? registered_freetype(Set,Cases),
1424 % TO DO: improve presentation, maybe use translate:type_set(_Type,TDom)
1425 findall(field(Case,Value),
1426 (member(case(Case,T),Cases),gen_case_value(T,Value)),
1427 Fields),
1428 AllCases = bind(Set,struct(Fields)).
1429
1430 get_freetype_params(Set,TypeParaNames,VirtualParaTypes) :-
1431 (stored_operator_direct_definition(Set,_Proj,_Theory,TypeParaNames,_Def,_WD,_TypeParas, datatype_definition)
1432 -> maplist(convert_name_to_type,TypeParaNames,VirtualParaTypes)
1433 ; add_error(bvisual2,'Unknown freetype:',Set),TypeParaNames=[]).
1434 convert_name_to_type(ParaName,VirtualType) :-
1435 (VirtualType=global(ParaName) -> true ; VirtualType=any),
1436 atom(ParaName),!. % so that pretty_type works
1437 convert_name_to_type(Type,_) :- add_error(bvisual,'Cannot convert parameter type:',Type).
1438
1439 get_destructor_for_freetype(Set,Case,Name,TypeAsString) :-
1440 ? stored_operator_direct_definition(Name,_Proj,_Theory,[argument(Case,_CType)],_Def,_WD,_TypeParameters,
1441 destructor(Set,ReturnType)),
1442 bv_pretty_type(ReturnType,TypeAsString).
1443
1444 :- use_module(probsrc(b_global_sets),[b_type2_set/2]).
1445 gen_case_value(constant(List),Res) :- List=[_], !, Res=[]. % the constant has no arguments, provide empty set
1446 gen_case_value(Type,Value) :- b_type2_set(Type,Value).
1447
1448 bv_pretty_type(Type,Res) :- with_bvisual2_translation_mode(pretty_type(Type,TS)),!,Res=TS.
1449 bv_pretty_type(Type,Res) :- add_error(bvisual2,'Cannot convert type:',Type), Res='?'.
1450
1451 register_top_level_formula(Id,Formula,Subs) :-
1452 assertz( stored_formula(Id,Formula) ),
1453 register_formulas(Subs,Id,_),
1454 assertz( top_level_node(Id) ),
1455 assertz( expanded(Id) ).
1456
1457 delete_top_level_formula(Id) :-
1458 retract( top_level_node(Id) ),
1459 delete_formula(Id),
1460 fail.
1461 delete_top_level_formula(_).
1462
1463 delete_formula(Id) :-
1464 retractall( expanded(Id) ),
1465 retractall( stored_formula(Id,_Formula) ),
1466 retract( subnode(Id,ChildId)),
1467 retractall( supernode(ChildId,Id)),
1468 delete_formula(ChildId),
1469 fail.
1470 delete_formula(_).
1471
1472
1473 register_formulas([],_Parent,[]).
1474 register_formulas([Formula|Frest],Parent,[SubId|Srest]) :-
1475 register_formula(Formula,Parent,SubId),
1476 register_formulas(Frest,Parent,Srest).
1477 register_formula(Formula,Parent,Id) :-
1478 get_new_id(Id),
1479 assertz( stored_formula(Id,Formula) ),
1480 assertz( subnode(Parent,Id) ),
1481 assertz( supernode(Id,Parent) ).
1482
1483 get_new_id(Id) :-
1484 (retract(id_counter(Old)) -> true ; Old = 0),
1485 Id is Old+1,
1486 assertz( id_counter(Id) ).
1487
1488
1489 disjunction_to_list(A,B,Out) :-
1490 disjunction_to_list2(A,[B],Out,[]).
1491 disjunction_to_list2(Expr,Rest) -->
1492 {get_texpr_expr(Expr,disjunct(A,B)),!},
1493 disjunction_to_list2(A,[B|Rest]).
1494 disjunction_to_list2(Expr,Rest) -->
1495 [Expr],disjunction_to_list3(Rest).
1496 disjunction_to_list3([]) --> !.
1497 disjunction_to_list3([H|T]) --> disjunction_to_list2(H,T).
1498
1499
1500 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1501 % some predicates for the support of the Tcl/Tk UI
1502
1503 call_with_temp_preference(Prefs,Values,Call) :-
1504 maplist(get_preference,Prefs,OldValues),
1505 maplist(set_preference,Prefs,Values),
1506 call_cleanup(Call,maplist(set_preference,Prefs,OldValues)),!.
1507
1508 bv_get_values_unlimited(Ids,StateId,Values) :-
1509 assertz(get_unlimited_value),
1510 call_cleanup(call_with_temp_preference([expand_avl_upto],[-1],bv_get_values(Ids,StateId,Values)),
1511 retractall(get_unlimited_value)).
1512
1513 bv_get_value_unlimited(Id,StateId,Value) :-
1514 visited_expression(StateId,State),!,
1515 get_preference(time_out,Timeout),
1516 assertz(get_unlimited_value),
1517 call_cleanup(call_with_temp_preference([expand_avl_upto],[-1],bv_get_value(Id,State,StateId,Timeout,Value)),
1518 retractall(get_unlimited_value)).
1519 bv_get_value_unlimited(_Id,_StateId,e('unknown state')).
1520
1521 bv_get_value_unlimited_and_unprocessed(Id,StateId,Value) :-
1522 visited_expression(StateId,State),!,
1523 get_preference(time_out,Timeout),
1524 call_with_temp_preference([expand_avl_upto],[-1],bv_get_value_unprocessed(Id,State,StateId,Timeout,Value)).
1525 bv_get_value_unlimited_and_unprocessed(_Id,_StateId,e('unknown state')).
1526
1527 % get the raw value in Prolog encoding
1528 bv_get_btvalue(Id,StateId,BExpr,BValue) :-
1529 bv_get_value_unlimited_and_unprocessed(Id,StateId,V),!,
1530 (V=btvalue(Value,E)
1531 -> BExpr=E,BValue=Value
1532 ; V=i -> add_error(bvisual2,'Cannot obtain value of inactive entry:',Id),fail
1533 ; add_error(bvisual2,'Cannot extract value of entry:',Id:V),fail).
1534 bv_get_btvalue(Id,_,_,_) :-
1535 add_error(bvisual2,'Unknown identifier or section, cannot find value:',Id),fail.
1536
1537
1538 :- use_module(probsrc(tools_commands),[edit_file/2]).
1539 :- use_module(probsrc(error_manager),[extract_file_line_col/6,extract_span_description_with_opts/3]).
1540 bv_formula_origin(Id,Desc) :-
1541 bv_get_stored_formula_expr(Id,Formula),
1542 (extract_span_description_with_opts(Formula,Desc,[compact_pos_info,tail_file_name])
1543 -> true ; Desc = '').
1544
1545 bv_show_formula_origin(Id,Desc) :-
1546 bv_get_stored_formula_expr(Id,Formula),
1547 extract_file_line(Formula,FILE,LINE),
1548 (extract_span_description_with_opts(Formula,Desc,[]) -> true ; Desc = ''),
1549 edit_file(FILE,LINE).
1550 :- use_module(probsrc(bmachine),[get_machine_file_number/4]).
1551 extract_file_line(included_machine(Machine,_,_),FILE,LINE) :- !,
1552 get_machine_file_number(Machine,_Ext,_Nr,FILE),
1553 LINE=1.
1554 extract_file_line(Formula,FILE,LINE) :- extract_file_line_col(Formula,FILE,LINE,_COL,_Erow,_Ecol).
1555
1556 :- use_module(probsrc(bsyntaxtree),[get_texpr_description/2, get_texpr_labels/2]).
1557 bv_formula_description(Id,Desc) :-
1558 bv_get_stored_formula_expr(Id,Formula),
1559 get_desc(Formula,Desc).
1560 get_desc(included_machine(Machine,_,_),Desc) :- !,
1561 get_machine_short_desc(Machine,Desc).
1562 get_desc(Formula,Desc) :-
1563 is_texpr(Formula),
1564 get_texpr_description(Formula,Desc).
1565
1566 % Extended description with additional information,
1567 % such as the formula label and the number of sub-elements.
1568 % Tcl/Tk displays this description in the context menu in the evaluation view.
1569 % The ProB 2 UI displays similar information in tooltips in the state view,
1570 % but those tooltips are constructed on the Java side.
1571 bv_formula_extended_description(Id,Desc) :-
1572 bvisual2_translation_mode(Mode),
1573 with_translation_mode(Mode, bv_formula_extended_description_aux(Id,Desc)).
1574 bv_formula_extended_description_aux(Id,Desc) :-
1575 bv_get_stored_formula_expr(Id,Formula),
1576 bv_ext_desc2(Id,Formula,Desc).
1577 bv_ext_desc2(Id,Formula,Desc) :-
1578 is_texpr(Formula), !,
1579 (get_texpr_description(Formula,Desc0)
1580 -> (get_first_label(Formula,Label) -> ajoin(['@',Label,': ',Desc0],Desc1)
1581 ; Desc1=Desc0
1582 )
1583 ; get_first_label(Formula,Desc1)
1584 % ; Desc = 'No description available via @desc pragma')
1585 ; Desc1 = ''
1586 ),
1587 (bv_formula_discharged_description(Id,DInfo)
1588 -> ajoin_with_nl(Desc1,DInfo,Desc2)
1589 ; Desc2 = Desc1),
1590 (bv_formula_size_description(Id,SzeD)
1591 -> ajoin_with_nl(Desc2,SzeD,Desc3)
1592 ; Desc3 = Desc2),
1593 (texpr_contains_wd_condition(Formula)
1594 -> ajoin_with_nl(Desc3,'Formula has wd condition',Desc4)
1595 ; Desc4 = Desc3),
1596 (display_type(Formula,TS)
1597 -> ajoin(['Type: ',TS],TTS), ajoin_with_nl(Desc4,TTS,Desc)
1598 ; Desc = Desc4),
1599 Desc \= ''.
1600 bv_ext_desc2(_Id,Formula,Desc) :- get_desc(Formula,Desc). % use default
1601
1602 :- use_module(probsrc(translate),[pretty_type/2]).
1603 display_type(b(_,T,_),TS) :- \+ do_not_show_type(T), bv_pretty_type(T,TS).
1604 % ltl
1605 do_not_show_type(pred).
1606 do_not_show_type(subst).
1607 do_not_show_type(op(_)).
1608
1609 ajoin_with_nl('',D2,Res) :- !, Res=D2.
1610 ajoin_with_nl(D1,D2,Res) :- ajoin([D1,'\n',D2],Res).
1611
1612
1613 bv_formula_discharged_info(Id,DischargedInfo) :-
1614 bv_formula_discharged_info(Id,_,DischargedInfo).
1615 bv_formula_discharged_info(Id,Proven,DischargedInfo) :-
1616 bv_get_stored_formula_expr(Id,Formula),
1617 get_discharged_info(Formula,Proven,DischargedInfo).
1618
1619 get_discharged_info(Formula,Proven,DischargedInfo) :-
1620 is_texpr(Formula),
1621 get_texpr_info(Formula,I),
1622 member(proof_status(Proven,DischargedInfo),I),!.
1623
1624 :- use_module(probsrc(tools_strings),[ajoin_with_sep/3]).
1625 bv_formula_discharged_description(Id,Desc) :-
1626 bv_formula_discharged_info(Id,Proven,L),
1627 ajoin_with_sep(L,',',DInfo),
1628 ajoin(['Proof status is ',Proven,': ',DInfo],Desc).
1629
1630 % extract some info about size and top-level function symbol of an entry:
1631 bv_formula_size_description(Id,Desc) :-
1632 get_nr_of_subformulas(Id,Nr), Nr>=1,
1633 (stored_formula(Id,F), is_texpr(F)
1634 -> SubName = 'subformulas',
1635 (get_texpr_top_level_symbol(F,Symbol,_,_)
1636 -> ajoin(['Formula (',Symbol,')'],Entry) ; Entry='Formula')
1637 ; atom(Id),get_node_label(Id,SubName)
1638 -> Entry = 'Entry'
1639 ; SubName = 'children', Entry = 'Entry'
1640 ),
1641 ajoin([Entry, ' contains ', Nr, ' ', SubName],Desc).
1642
1643 % compute number of subformulas/entries of a node:
1644 get_nr_of_subformulas(Id,Nr) :- expanded(Id),!,
1645 findall(1, subnode(Id,_), L),
1646 length(L,Nr).
1647 get_nr_of_subformulas(Id,Nr) :-
1648 bv_get_stored_formula_expr(Id,Formula),
1649 findall(1,get_subformulas(Formula,_,_Kind),L),
1650 length(L,Nr).
1651
1652 % get the top-level symbol of a formula
1653 bv_get_formula_functor_symbol(Id,Symbol) :-
1654 stored_formula(Id,F), is_texpr(F),
1655 \+ top_level_node(Id),
1656 bvisual2_translation_mode(Mode),
1657 with_translation_mode(Mode, get_texpr_top_level_symbol(F,Symbol,_,_)).
1658
1659 bv_is_child_formula(Id) :- \+ bv_is_topmost_formula(Id).
1660 % check if node is topmost formula, attached to a top_level_node
1661 bv_is_topmost_formula(Id) :-
1662 supernode(Id,Super),
1663 top_level_node(Super).
1664
1665
1666 bv_formula_labels(Id,Labels) :-
1667 bv_get_stored_formula_expr(Id,Formula),
1668 is_texpr(Formula),
1669 (get_texpr_labels(Formula,Labels) -> true).
1670
1671 get_first_label(Formula,Desc) :- get_texpr_labels(Formula,Lbls) -> [Desc|_]=Lbls.
1672
1673 bv_is_typed_formula(Id) :- bv_get_stored_formula_expr(Id,Formula), is_texpr(Formula).
1674 bv_is_typed_predicate(Id) :- bv_get_stored_formula_expr(Id,Formula), Formula = b(_,pred,_).
1675 bv_is_typed_identifier(Id,IDName) :- bv_get_stored_formula_expr(Id,Formula), Formula = b(identifier(IDName),_,_).
1676
1677 % the formula of a node as text which can be parsed again (unlike its label, which can
1678 % e.g. be the name of an event for its guard, or have a proof info icon);
1679 % Kind is expression or predicate, or none if the node has no formula (Text = '')
1680 % or if the formula cannot be used on its own as it refers to quantified or local
1681 % identifiers, e.g. a part of the guard of an event with parameters
1682 bv_formula_text(Id,Kind,Text) :-
1683 bv_get_stored_formula_expr(Id,Formula), Formula = b(_,Type,_), Type \= subst,
1684 find_typed_identifier_uses(Formula,Used),
1685 \+ has_non_machine_identifier(Used),
1686 \+ has_identifier_bound_in_ancestor(Id,Used),
1687 with_bvisual2_translation_mode(translate_subst_or_bexpr_with_limit(Formula,100000,Text)),
1688 !,
1689 (Type=pred -> Kind=predicate ; Kind=expression).
1690 bv_formula_text(_,none,'').
1691
1692 % a free identifier (in the list of the formula's free identifiers) which is not a
1693 % variable or constant of the machine (global sets and their elements are not
1694 % considered free here), e.g. a parameter of an event
1695 :- use_module(probsrc(bsyntaxtree),[find_typed_identifier_uses/2]).
1696 has_non_machine_identifier(Used) :-
1697 member(TId,Used), get_texpr_id(TId,Name),
1698 \+ b_is_variable(Name), \+ b_is_constant(Name), !.
1699
1700 % a free identifier of the formula of node Id which is bound by an enclosing node,
1701 % e.g. by a quantifier or as the parameter of an event (the formula is a part of
1702 % its guard); it may have the same name as a variable or constant of the machine
1703 has_identifier_bound_in_ancestor(Id,Used) :-
1704 Used = [_|_],
1705 ancestor_node(Id,Ancestor),
1706 stored_formula(Ancestor,Stored),
1707 node_bound_identifier(Stored,Name),
1708 member(TId,Used), get_texpr_id(TId,Name), !.
1709
1710 ancestor_node(Id,Ancestor) :- supernode(Id,Parent),
1711 (Ancestor = Parent ; ancestor_node(Parent,Ancestor)).
1712
1713 % the names of the identifiers a node binds for its children
1714 node_bound_identifier(guard(_Name,Parameters,_Guard),Name) :- !,
1715 member(P,Parameters), get_texpr_id(P,Name).
1716 node_bound_identifier(guard_theorems(_Name,Parameters,_Guard,_Theorems),Name) :- !,
1717 member(P,Parameters), get_texpr_id(P,Name).
1718 node_bound_identifier(Stored,Name) :-
1719 extract_typed_formua(Stored,Formula),
1720 is_texpr(Formula),
1721 syntaxtraversion(Formula,_,_,_,_,Names),
1722 member(TName,Names), get_texpr_id(TName,Name).
1723
1724 bv_get_stored_formula_expr(Id,Formula) :-
1725 stored_formula(Id,Stored),
1726 extract_typed_formua(Stored,Formula).
1727
1728 extract_typed_formua(bind(LHS,_),Formula) :- !, Formula=LHS.
1729 extract_typed_formua(guard(Name,Parameters,Guard),Formula) :- !,
1730 get_guard_formula(Parameters,Guard,GF),
1731 (b_get_operation_description(Name,Desc) -> add_texpr_description(GF,Desc,Formula)
1732 ; Formula = GF).
1733 extract_typed_formua(variant(_Name,_ConvOrAnt,Variant),Formula) :- !, Formula=Variant.
1734 extract_typed_formua(named_subformula(_,Formula,_),Res) :- !, Res=Formula.
1735 extract_typed_formua(TF,TF).
1736
1737 get_guard_formula([],Guard,Res) :- !, Res=Guard.
1738 get_guard_formula(Parameters,Guard,Expr) :- create_or_merge_exists(Parameters,Guard,Expr).
1739 get_guard_theorems_formula([],_Guard,Theorems,Res) :- !, Res=Theorems.
1740 get_guard_theorems_formula(Parameters,Guard,Theorems,Expr) :-
1741 create_forall(Parameters,b(implication(Guard,Theorems),pred,[]),Expr).
1742
1743 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1744 %
1745 :- use_module(probsrc(tools_io)).
1746 bv_print_to_file(IdList,StateId,Filename) :-
1747 call_with_temp_preference([expand_avl_upto],[-1],bv_print_to_file_aux(IdList,StateId,Filename)).
1748 bv_print_to_file_aux(IdList,StateId,Filename) :-
1749 safe_open_file(Filename,write,S,[encoding(utf8)]),
1750 bv_print_to_stream_l(IdList,S,StateId,false),
1751 close(S).
1752
1753 bv_print_to_stream_l([],_S,_StateId,_WriteAnd).
1754 bv_print_to_stream_l([Id|Rest],S,StateId,WriteAnd) :-
1755 bv_print_to_stream(Id,S,StateId,OutType,WriteAnd),
1756 (OutType=predicate -> WriteAnd2=true ; WriteAnd2=WriteAnd),
1757 bv_print_to_stream_l(Rest,S,StateId,WriteAnd2).
1758
1759 bv_print_to_stream(Id,S,StateId,predicate,WriteAnd) :-
1760 stored_formula(Id,Formula),
1761 bv_print_formula_to_stream(Formula,Id,S,StateId,WriteAnd),!,nl(S).
1762 bv_print_to_stream(Id,S,StateId,other,_WriteAnd) :-
1763 get_node_label(Id,Label),
1764 bv_get_values([Id],StateId,[Value]),
1765 write(S,'/* '),write(S,Label),write(S,': '),
1766 bv_print_std_value(Value,S),write(S,' */\n').
1767 bv_print_std_value(e(Msg),S) :- write(S,'ERROR( '), write(S,Msg), write(S,' )').
1768 bv_print_std_value(p(Value),S) :- write(S,Value).
1769 bv_print_std_value(v(Value),S) :- write(S,Value).
1770 bv_print_std_value(i,S) :- write(S,'INACTIVE').
1771 bv_print_std_value(bv_info(I),S) :- write(S,I).
1772
1773 bv_print_formula_to_stream(Formula,Id,S,StateId,WriteAnd) :-
1774 is_texpr(Formula),
1775 get_texpr_type(Formula,Type),
1776 bv_get_value_unlimited_and_unprocessed(Id,StateId,Value),
1777 bv_print_formula_to_stream2(Type,Formula,Value,S,WriteAnd).
1778
1779 bv_print_formula_to_stream2(pred,Formula,p(Value),S,WriteAnd) :- !,
1780 bv_print_predicate_to_stream(Value,Formula,S,WriteAnd).
1781 bv_print_formula_to_stream2(Type,Formula,btvalue(Value,_),S,WriteAnd) :- !,
1782 create_texpr(value(Value),Type,[],TValue),
1783 create_texpr(equal(Formula,TValue),pred,[],Equal),
1784 write_bexpression(S,Equal,WriteAnd).
1785
1786 bv_print_predicate_to_stream(true,Formula,S,WriteAnd) :-
1787 write_bexpression(S,Formula,WriteAnd).
1788 bv_print_predicate_to_stream(false,Formula,S,WriteAnd) :-
1789 create_texpr(negation(Formula),pred,[],NegatedFormula),
1790 write(S,' /* FALSE */ '),write_bexpression(S,NegatedFormula,WriteAnd).
1791
1792 write_bexpression(Stream,Expression,WriteAnd) :-
1793 (WriteAnd = true -> write(Stream,' & \n') ; true),
1794 translate_bexpression_to_codes(Expression,Codes),
1795 put_codes(Codes,Stream).
1796
1797 bv_write_all_variables_and_constants(StateId,Filename) :-
1798 call_with_temp_preference([expand_avl_upto],[-1],bv_write_all_variables_and_constants_aux(StateId,Filename)).
1799 bv_write_all_variables_and_constants_aux(StateId,Filename) :-
1800 bv_expand_formula(constants,_CLabel,ConstNodes),
1801 bv_expand_formula(variables,_VLabel,VarNodes),
1802 append(ConstNodes,VarNodes,Subnodes),expand_all(Subnodes),
1803 append([constants|ConstNodes],[variables|VarNodes],Nodes),
1804 bv_print_to_file(Nodes,StateId,Filename).
1805 expand_all(Subnodes) :-
1806 member(Node,Subnodes),
1807 bv_expand_formula(Node,_,_),
1808 fail.
1809 expand_all(_Subnodes).
1810
1811
1812 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
1813 :- register_event_listener(clear_specification,clear_bvisual,
1814 'Clear module bvisual2.').
1815 :- register_event_listener(specification_initialised,reset_bvisual,
1816 'Initialise module bvisual2.').
1817 :- register_event_listener(change_of_animation_mode,reset_bvisual,
1818 'Initialise module bvisual2.').
1819
1820 :- use_module(probsrc(self_check)).
1821 % a very small use-case:
1822 :- assert_must_succeed((
1823 reset_bvisual,
1824 bv_get_top_level(T), %print(top(T)),nl,
1825 %T == [variables,constants,inv],
1826 member(inv,T),
1827 bv_expand_formula(inv,Text,Sub),
1828 %print(expand(Text,Sub)),nl,
1829 Text == 'INVARIANT',
1830 Sub = [H|_],
1831 bv_expand_formula(H,_Text1,_Sub1),
1832 %print(expand1(Text1,Sub1)),nl,
1833 bv_get_values(Sub,root,Values),
1834 %print(values(Values)),nl, % should be [i,...] or e('unknown state')
1835 Values = [VI|_], (VI=i ; VI=e(_)),
1836 reset_bvisual
1837 )).
1838
1839 % example bv_get_top_level_formula(theoremsc,Txt,Labels,Vals)
1840
1841 bv_get_top_level_formula(Category,CatText,Labels,Values) :-
1842 current_state_id(StateId),
1843 bv_get_top_level_formula(Category,CatText,StateId,Labels,Values).
1844 bv_get_top_level_formula(Category,CatText,StateId,Labels,Values) :-
1845 bv_get_top_level(TL),
1846 member(Category,TL),
1847 bv_expand_formula(Category,CatText,Subs),
1848 maplist(get_node_label,Subs,Labels),
1849 bv_get_values(Subs,StateId,Values).
1850
1851 % ------------------------------------
1852
1853 % provide HTML output of operation guards upto MaxLevel
1854 % TO DO: provide option to provide parameter values, output to Latex,...
1855 html_debug_operation_for_stateid(Stream,OpName,StateId,MaxLevel) :-
1856 stored_formula(Id,guard(OpName,_,_)),
1857 enter_level(Stream,0),
1858 traverse(Stream,StateId,0,MaxLevel,Id),
1859 exit_level(Stream,0).
1860
1861 :- use_module(probsrc(tools),[html_escape/2]).
1862 traverse(_,_StateId,Level,MaxLevel,_Id) :- Level>MaxLevel,!.
1863 traverse(Stream,StateId,Level,MaxLevel,Id) :-
1864 bv_expand_formula(Id,Label,Children), html_escape(Label,ELabel),
1865 bv_get_values([Id],StateId,[Value]),
1866 translate_value(Value,ValueS), html_escape(ValueS,EValueS),
1867 % format('~w : ~w = ~w [~w] (level ~w)~n',[Id,Label,Value,ValueS,Level]),
1868 stored_formula(Id,Formula),
1869 (color_based_on_value(Value,Col) -> format(Stream,'<font color="~w">',[Col]) ; true),
1870 (Formula = guard(_,_,_)
1871 -> format(Stream,'<li>Guard of ~w = ~w</li>~n',[ELabel,EValueS])
1872 ; format(Stream,'<li>~w = ~w</li>~n',[ELabel,EValueS])
1873 ),
1874 (color_based_on_value(Value,_) -> format(Stream,'</font>',[]) ; true),
1875 (Level < MaxLevel
1876 -> L1 is Level+1,
1877 enter_level(Stream,L1),
1878 maplist(traverse(Stream,StateId,L1,MaxLevel),Children),
1879 exit_level(Stream,L1)
1880 ; true).
1881
1882 color_based_on_value(p(false),'INDIANRED').
1883 color_based_on_value(p(true),'DARKGREEN').
1884 color_based_on_value(e(_),red).
1885 color_based_on_value(i,gray).
1886 color_based_on_value(bv_info(_),gray).
1887
1888 enter_level(Stream,L1) :- indent_ws(Stream,L1), format(Stream,'<ul>~n',[]).
1889 exit_level(Stream,L1) :- indent_ws(Stream,L1), format(Stream,'</ul>~n',[]).
1890
1891 indent_ws(_,X) :- X<1,!.
1892 indent_ws(Stream,X) :- write(Stream,' '), X1 is X-1, indent_ws(Stream,X1).
1893
1894
1895 translate_value(p(V),R) :- !,R=V.
1896 translate_value(v(V),R) :- R=V.
1897 translate_value(e(M),R) :- !, ajoin(['ERROR(',M,')'],R).
1898 translate_value(i,R) :- !, R='INACTIVE'.
1899 translate_value(bv_info(I),R) :- !, R=I.
1900 translate_value(V,V).
1901
1902 % --------------------------------
1903
1904 :- use_module(probsrc(error_manager),[add_error/3]).
1905 :- use_module(probsrc(bmachine),[b_parse_machine_predicate_from_codes_open/5, b_parse_machine_formula_from_codes/7]).
1906 tcltk_register_new_user_formula(F) :- tcltk_register_new_user_formula(formula,F).
1907 tcltk_register_new_user_formula(Kind,F) :-
1908 atom_codes(F,Codes),
1909 TypingScope=[prob_ids(visible),variables],
1910 (Kind=open_predicate
1911 -> b_parse_machine_predicate_from_codes_open(exists,Codes,[],TypingScope,Typed)
1912 ; b_parse_machine_formula_from_codes(Kind,Codes,TypingScope,Typed,_Type,true,Error)
1913 ),
1914 (Error=none -> true
1915 ; add_error(tcltk_register_new_user_formula,'Error occured while parsing formula: ',Error),fail),
1916 bv_insert_formula(Typed,user_formulas,_),
1917 (top_level_node(user_formulas) -> true ; register_top_level(user_formulas) ).
1918 %retractall(expanded(user_formulas)),
1919 %bv_insert_formula(Typed,user,_),.
1920
1921 % --------------------------------
1922
1923