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