1 % (c) 2009-2024 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(b_interpreter,
7 [b_test_boolean_expression/4, b_test_boolean_expression/6,
8 %b_test_boolean_expression_wf/3,
9 b_test_boolean_expression_cs/5,
10 b_test_boolean_expression_for_ground_state/4, b_test_boolean_expression_for_ground_state/5,
11 % b_det_test_boolean_expression/6,
12 b_not_test_boolean_expression/4, b_not_test_boolean_expression/6,
13 %b_not_test_boolean_expression_wf/3,
14 b_not_test_boolean_expression_cs/5,
15
16 b_convert_bool/5,
17 b_convert_bool_timeout/7,
18 b_compute_expression/5,
19 % b_execute_statement/6,
20 b_execute_top_level_statement/7,
21
22 b_compute_expression_nowf/4, b_compute_expression_nowf/6, b_compute_expression_nowf/7,
23
24 b_set_up_concrete_constants/2, b_partial_set_up_concrete_constants/1,
25 b_initialise_machine/4,
26
27 b_execute_top_level_operation_update/5, b_execute_top_level_operation_wf/8,
28
29 convert_list_of_expressions_into_set_wf/4,
30 %state_satisfies_negation_of_invariant/1,
31
32 b_state_violates_invariant/2,
33 state_violates_assertions/2,
34 analyse_invariant_for_state/1,
35
36 insert_before_substitution_variables/5, % add $0 values to a store
37
38 try_lookup_value_in_store_and_global_sets/3, lookup_value_in_store_and_global_sets_wf/7,
39 set_up_typed_localstate/6, set_up_typed_localstate2/8,
40 %set_up_localstate_for_let/7,
41
42 set_projection_on_static_assertions/1,
43
44 tcltk_unsatisfiable_components_exist/0,
45 tcltk_quick_describe_unsat_properties/2,
46
47 get_unsat_component_predicate/3,
48 properties_were_filtered/1, % true if PROPERTIES / axioms filtered due to prob-ignore pragmas
49 b_generate_for_all_list_domain_nolwf/8 % for predicate_evaluator
50 ]).
51
52 :- meta_predicate not_with_enum_warning_and_possible_delay(0,-,?,?).
53 :- meta_predicate not_with_enum_warning_delay(0,-,?,?).
54
55 %:- use_module('../extensions/profiler/profiler.pl').
56 %:- use_module('../extensions/profiler/profiler_te.pl').
57 %:- enable_profiling(b_test_boolean_expression/4).
58 %:- enable_profiling(b_test_boolean_expression_cs/5).
59
60 :- use_module(kernel_objects).
61 :- use_module(bsets_clp).
62 :- use_module(delay).
63
64
65 :- use_module(kernel_mappings).
66 :- use_module(b_global_sets).
67 :- use_module(store).
68 :- use_module(library(lists)).
69 :- use_module(library(ordsets)).
70 :- use_module(library(avl)).
71
72 :- use_module(b_global_sets).
73 :- use_module(bmachine).
74 :- use_module(b_enumerate, [b_enumerate_values_in_store/5,
75 b_tighter_enumerate_all_values/2, b_tighter_enumerate_values_in_ctxt/3]).
76 :- use_module(debug).
77 :- use_module(performance_messages).
78 :- use_module(self_check).
79 :- use_module(tools).
80
81 :- use_module(module_information,[module_info/2]).
82 :- module_info(group,interpreter).
83 :- module_info(description,'This module provides the basic interpreter for expressions, predicates and substitutions.').
84
85 :- use_module(preferences).
86 :- use_module(error_manager).
87 :- use_module(typechecker).
88 :- use_module(specfile,[state_corresponds_to_initialised_b_machine/2
89 ,state_corresponds_to_set_up_constants_only/2]).
90
91 :- use_module(bsyntaxtree).
92
93 :- use_module(translate).
94
95 :- use_module(kernel_waitflags).
96 :- use_module(kernel_reals).
97 :- use_module(kernel_records).
98
99 :- use_module(kodkodsrc(kodkod),[kodkod_request/5]).
100
101 :- use_module(custom_explicit_sets).
102 :- use_module(closures,[is_symbolic_closure/1,
103 mark_closure_as_symbolic/2, mark_closure_as_recursive/2, mark_closure/3]).
104
105 :- use_module(state_space).
106 :- use_module(b_interpreter_eventb).
107 :- use_module(tools_printing,[print_term_summary/1,print_functor/1]).
108 :- use_module(value_persistance,[load_partial_constants/3,lookup_cached_transitions/3]).
109 :- use_module(extrasrc(b_expression_sharing),[is_lazy_let_identifier/1]).
110 :- use_module(bool_pred,[negate/2]).
111 :- use_module(smt_solvers_interface(smt_solvers_interface),[smt_add_predicate/5]).
112
113 :- use_module(debug).
114 :- use_module(external_functions).
115
116 %:- use_module(tools,[bt_start_ms_timer/1, bt_stop_ms_timer/1]).
117 :- use_module(static_ordering,[sort_ids_by_usage/4,reorder_state/3]).
118 %:- use_module(bsyntaxtree,[predicate_has_ignore_pragma/1]).
119 :- use_module(tools_lists,[exclude_count/4, optimized_nth1/3]).
120 :- use_module(tools_meta, [safe_time_out/3]).
121
122 :- set_prolog_flag(double_quotes, codes).
123
124 /* ----------------------------------*/
125
126 /* For partial evaluation */
127
128 %:- use_module('~/cvs_root/cogen2/logen_source/runtime/logen_dispatcher.pl').
129
130 % new profiler
131 %:- use_module('../extensions/profiler/profiler.pl').
132 %:- use_module('../extensions/profiler/profiler_te.pl').
133 %:- enable_profiling_naming(b_interpreter:b_state_violates_invariant_aux/2,name).
134
135 %name(b_interpreter:b_state_violates_invariant_aux,_,INVERIANT).
136
137 %b_state_violates_invariant(ID,State) :-
138 % b_intepreter:b_state_violates_invariant_aux(ID,State).
139
140 % old profiler
141 :- use_module(runtime_profiler,[profile_single_call/3]).
142
143 % called by force_check_invariantKO and indirectly by model_checker (State was prepare_state_for_specfile_trans )
144 b_state_violates_invariant(ID,State) :-
145 b_state_violates_invariant_aux(ID,State).
146
147 b_state_violates_invariant_aux(ID,CurBState) :-
148 retract(specialized_inv(ID,AVL)), % Note: when we assert this we check that invariant holds in predecessor state
149 intersect_invs(AVL,SPO), !,
150 (SPO = b(truth,_,_) -> fail
151 ; profile_single_call('INVARIANT-Specialized',ID,b_interpreter:b_state_violates_spec_invariant(ID,SPO,CurBState))).
152 b_state_violates_invariant_aux(ID,CurBState) :-
153 profile_single_call('INVARIANT',ID,b_interpreter:state_violates_invariant(ID,CurBState)).
154
155 b_state_violates_spec_invariant(ID,SPO,CurBState) :-
156 \+ check_invariant_predicate_with_time_out(ID,SPO,CurBState).
157
158 intersect_invs(invariant_preserved,Inv) :- !, Inv= b(truth,pred,[]).
159 intersect_invs([],Inv) :- !, add_internal_error('Illegal empty specialized inv list:', intersect_invs([],Inv)),
160 Inv = b(falsity,pred,[]).
161 intersect_invs(A,InvList) :-
162 avl_domain(A,OpList),
163 get_mask(OpList,Mask), %print(check(OpList,Mask)),nl,
164 findall(nth1_invariant(Nr), member(Nr,Mask), InvList).
165
166 % intersect all masks of specialized invariant nrs to be checked
167 get_mask([],[]).
168 get_mask([H|T],Res) :-
169 b_specialized_invariant_mask_for_op(H,Mask),get_mask3(T,Mask,Res).
170 get_mask3([],Acc,Acc).
171 get_mask3([H|T],Acc,Res) :-
172 b_specialized_invariant_mask_for_op(H,Mask),
173 ord_intersection(Mask,Acc,A1),
174 get_mask3(T,A1,Res).
175 /* ----------------------------------*/
176
177 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
178
179
180 state_satisfies_invariant_aux(ID,State) :-
181 check_invariant_with_time_out(ID,State). % version without partial evaluation
182
183
184 :- use_module(library(timeout)).
185
186 :- use_module(tools_printing,[format_with_colour_nl/4]).
187 :- use_module(probsrc(specfile),[prepare_state_for_specfile_trans/3]).
188 % called by prob_cli when invariant violation found:
189 % we no longer have access to the specialized_inv facts
190 analyse_invariant_for_state(ID) :-
191 b_invariant_number_list(InvList),
192 visited_expression(ID,State),
193 prepare_state_for_specfile_trans(State,ID,PreparedCurState),
194 maplist(check_invariant(ID,PreparedCurState),InvList).
195 check_invariant(ID,State,InvariantNr) :-
196 enter_new_error_scope(L,check_invariant),
197 check_invariant_predicate_with_time_out_res(InvariantNr,State,TimeOutRes),
198 (TimeOutRes=success -> true
199 ; InvariantNr = nth1_invariant(Nr),
200 b_nth1_invariant(Nr,Invariant,_UsedIds),
201 translate_bexpression_with_limit(Invariant,TS),
202 translate_span(Invariant,SpanStr),
203 (TimeOutRes=failure -> InvRes=false ; InvRes=unknown),
204 format_with_colour_nl(user_output,[red,bold],
205 '*** Invariant ~w ~w is ~w (in state with id ~w):~n ~w',[Nr,SpanStr,InvRes,ID,TS]),
206 % add_message(check_invariant,'Invariant false: ',Nr,TS),
207 (debug_mode(off) -> true
208 ; translate:print_bstate(State),nl
209 )
210 % TODO: pass check dot_file_prefix or similar to analyse_invariant_for_state and call:
211 % bvisual:get_tree_from_expr(Tree, Invariant, [], State),
212 % bvisual:write_dot_graph_to_file(Tree,'invariant.dot')
213 ), exit_error_scope(L,_ErrOcc,check_invariant).
214
215
216
217 check_invariant_with_time_out(ID,State) :-
218 %b_get_invariant_from_machine(Invariant),
219 b_invariant_number_list(InvList), % ensures operation caching can be applied
220 % TO DO: we could just get unproven invariants; unless we are in an initial state
221 check_invariant_predicate_with_time_out(ID,InvList,State).
222
223
224 check_invariant_predicate_with_time_out(ID,Invariant,State) :-
225 (check_invariant_predicate_with_time_out_res(Invariant,State,TimeOutRes)
226 -> check_time_out_res(TimeOutRes,ID)).
227
228 check_invariant_predicate_with_time_out_res(b(truth,_,_),_State,TimeOutRes) :- !, % only typing in invariant
229 TimeOutRes = success.
230 check_invariant_predicate_with_time_out_res(Invariant,State,TimeOutRes) :-
231 set_error_context(checking_invariant),
232 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
233 call_cleanup(
234 (time_out_with_enum_warning_one_solution_no_new_error_scope(
235 b_interpreter:check_invariant_predicate_aux(Invariant,State ),
236 DebugTimeOut,TimeOutRes)
237 -> true
238 ; TimeOutRes = failure),
239 clear_error_context).
240
241 % process typed predicates, lists and special invariant(Nr) terms
242 check_invariant_predicate_aux(nth1_invariant(Nr),State) :- !,
243 (get_preference(try_operation_reuse,false)
244 ? -> check_nth1_invariant(Nr,State)
245 ? ; \+ b_operation_cache:check_invariant_violated_cache(Nr,State) % will call check_nth1_invariant if necessary
246 % note : for performance it is important that the State is prepared but not expanded
247 % (e.g. it should be expanded_const_and_vars with the info field containing the packed state)
248 ).
249 check_invariant_predicate_aux([],_) :- !.
250 check_invariant_predicate_aux([H|T],State) :- !,
251 ? check_invariant_predicate_aux(H,State),
252 ? check_invariant_predicate_aux(T,State).
253 check_invariant_predicate_aux(Invariant,State) :-
254 b_test_boolean_expression_for_ground_state(Invariant,[],State,'INVARIANT',0).
255
256 % check the nth invariant
257 check_nth1_invariant(Nr,State) :-
258 if(b_nth1_invariant(Nr,Invariant,_UsedIds),
259 ? b_test_boolean_expression_for_ground_state(Invariant,[],State,'INVARIANT',Nr), % add Nr to call_stack
260 add_internal_error('Invariant does not exist:',Nr)).
261
262
263 check_time_out_res(time_out,ID) :- !,
264 format('**** TIMEOUT during invariant evaluation in state ~w!~n',[ID]),
265 assert_time_out_for_invariant(ID),
266 fail.
267 check_time_out_res(virtual_time_out(_WARNING),ID) :- !,
268 format('**** VIRTUAL TIMEOUT during invariant evaluation in state ~w!~n',[ID]),
269 assert_time_out_for_invariant(ID),
270 fail.
271 check_time_out_res(failure,_) :- !, fail.
272 check_time_out_res(_,_).
273
274 % b_test_boolean_expression_for_ground_state:
275 % idea: check each conjunct individually; avoids multiplication of choice points between conjuncts
276
277 :- use_module(specfile,[expand_const_and_vars_to_full_store/2]).
278 b_test_boolean_expression_for_ground_state(b(Expr,_,Infos),LS,S,PredKind) :-
279 b_test_boolean_expression_for_ground_state(b(Expr,_,Infos),LS,S,PredKind,0).
280 b_test_boolean_expression_for_ground_state(b(Expr,_,Infos),LS,S,PredKind,Nr) :-
281 expand_const_and_vars_to_full_store(S,FS), % ensure we have full store
282 ? b_test_boolean_expression_for_ground_state2(Expr,Infos,LS,FS,PredKind,Nr).
283
284 b_test_boolean_expression_for_ground_state1(b(Expr,_,Infos),LS,S,Kind,Nr) :- !,
285 ? b_test_boolean_expression_for_ground_state2(Expr,Infos,LS,S,Kind,Nr).
286
287 b_test_boolean_expression_for_ground_state2(conjunct(LHS,RHS),_,LocalState,State,Kind,Nr) :- !,
288 % usually LHS is the nested conjunct and RHS atomic:
289 %it would be better to swap LHS and RHS: but does not seem to buy anything
290 ? b_test_boolean_expression_for_ground_state1(LHS,LocalState,State,Kind,Nr),
291 !, % do we need this cut; it makes partial evaluation more tricky
292 ? b_test_boolean_expression_for_ground_state1(RHS,LocalState,State,Kind,Nr).
293 % TO DO: treate lazy_let_pred ?
294 b_test_boolean_expression_for_ground_state2(BE,Infos,LS,S,Kind,Nr) :-
295 ? b_test_boolean_expression_cs(b(BE,pred,Infos),LS,S,Kind,Nr).
296
297 state_violates_invariant(ID,State) :-
298 State \== root,
299 State \= concrete_constants(_), % machine not yet initialised (cf state_corresponds_to_initialised_b_machine)
300 \+(state_satisfies_invariant_aux(ID,State)).
301
302
303 % new profiler
304 %:- use_module('../extensions/profiler/profiler.pl').
305 %:- use_module('../extensions/profiler/profiler_te.pl').
306 %:- enable_profiling_naming(b_interpreter:state_violates_assertions_aux/2,name2).
307
308 %name2(b_interpreter:state_violates_assertions_aux,_,ASSERTIONS).
309
310 %state_violates_assertions(ID,State) :-
311 % b_interpreter:state_violates_assertions_aux(ID,State).
312
313 % old profiler
314 :- use_module(runtime_profiler,[profile_single_call/3]).
315 :- use_module(bmachine,[get_assertions_from_machine/2, b_machine_has_dynamic_assertions/0, b_machine_has_static_assertions/0]).
316 state_violates_assertions(ID,State) :-
317 profile_single_call('ASSERTIONS',ID,b_interpreter:state_violates_assertions_aux(ID,State)).
318 state_violates_assertions_aux(ID,State) :-
319 b_machine_has_dynamic_assertions,
320 state_corresponds_to_initialised_b_machine(State,BState), !,
321 \+(state_satisfies_assertions(ID,dynamic,BState)).
322 state_violates_assertions_aux(ID,State) :-
323 b_machine_has_static_assertions,
324 state_corresponds_to_set_up_constants_only(State,BState),
325 \+(state_satisfies_assertions(ID,static,BState)).
326 state_satisfies_assertions(ID,Type,State) :-
327 ( get_assertions_from_machine(Type,Ass) ->
328 set_error_context(checking_assertions),
329 %enter_new_error_scope(Level,checking_assertions),
330 preferences:get_computed_preference(debug_time_out,DebugTimeOut),
331 %print(checking_assertions(ID)),nl,
332 time_out_with_enum_warning_one_solution(
333 b_test_list_of_boolean_expression_for_ground_state(Ass,'ASSERTION ',[],State),
334 DebugTimeOut,TimeOutRes, clear_errors),
335 % TO DO: in case of a virtual time-out (cf UML-B/drone_2_error.eventb) we could try and continue with the next assertion
336 clear_error_context,
337 (nonvar(TimeOutRes),
338 (TimeOutRes == time_out, Kind='TIMEOUT' ; TimeOutRes = virtual_time_out(_), Kind = 'Virtual TIMEOUT')
339 -> format('~n*** ~w during assertion checking for state id ~w!~n',[Kind,ID]),
340 assert_time_out_for_assertions(ID)
341 ; true
342 )
343 ; true
344 ).
345
346
347
348 /* ----------------------------------*/
349 /* b_test_boolean_expression */
350 /* ----------------------------------*/
351
352
353 :- type variable_id_list +--> list(type(variable_id)).
354
355 :- type boolean_expression +--> call(bsyntaxtree:check_if_typed_predicate).
356
357 % used for testing ASSERTIONS on a fully ground state
358 b_test_list_of_boolean_expression_for_ground_state(List,PredKind,LS,S) :-
359 b_test_list_of_boolean_expression_aux(List,PredKind,1,LS,S).
360
361 b_test_list_of_boolean_expression_aux([],_,_,_,_).
362 b_test_list_of_boolean_expression_aux([B1|T],PredKind,Nr,LS,S) :- %nl,print(nr(PredKind,Nr)),nl,
363 ? (b_test_boolean_expression_for_ground_state1(B1,LS,S,PredKind,Nr)
364 -> N1 is Nr+1, b_test_list_of_boolean_expression_aux(T,PredKind,N1,LS,S)
365 ; silent_mode(off),
366 (critical_enumeration_warning_occured_in_error_scope -> Res='UNKNOWN'
367 ; abort_error_occured_in_error_scope -> Res ='NOT-WELL-DEFINED'
368 ; Res='false'),
369 ajoin([PredKind, Nr, ' is ', Res,': '],Msg),
370 add_message(b_interpreter,Msg,B1,B1), % TO DO: get just label/location?
371 fail).
372
373
374 :- use_module(b_interpreter_components).
375
376
377 :- assert_pre(b_interpreter:b_test_boolean_expression_cs(E,LS,S,_,_),
378 (bsyntaxtree:check_if_typed_predicate(E),type_check(LS,store),type_check(S,store) )).
379 :- assert_post(b_interpreter:b_test_boolean_expression_cs(_,_,_,_,_), true ).
380
381
382 % --------------------- BOOLEAN EXPRESSIONS ----------------------------
383
384 :- use_module(b_interpreter_check).
385 :- use_module(kernel_propagation, [do_not_enumerate_binary_boolean_operator/3]).
386
387 % a version where we can provide an initial call stack entry for context
388 b_test_boolean_expression_cs(E,LS,S,PredKind,Nr) :-
389 init_wait_flags_cs(E,PredKind,Nr,b_test_boolean_expression_cs,WF),
390 % TO DO: call b_trace_test_components ?
391 ? b_test_boolean_expression(E,LS,S,WF),
392 ? ground_wait_flags(WF).
393
394 init_wait_flags_cs(E,PredKind,Nr,PP,WF) :-
395 (PredKind=none -> init_wait_flags(WF,[PP])
396 ; get_texpr_pos(E,Pos),
397 CallStackEntry = prob_command_context(check_pred_command(PredKind,Nr),Pos),
398 init_wait_flags_and_push_call_stack(no_wf_available,CallStackEntry,WF)
399 ).
400
401
402 b_test_boolean_expression(b(Expr,_,Infos),LS,S,WF) :- !,
403 (b_interpreter_check:composed(Expr) -> empty_avl(Ai)
404 ; Ai = no_avl), % simple expression: no sharing is possible: no need to register expressions
405 ? b_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,_).
406 b_test_boolean_expression(E,LS,S,WF) :- % will generate error message
407 empty_avl(Ai), b_test_boolean_expression(E,LS,S,WF,Ai,_).
408
409 :- assert_pre(b_interpreter:b_test_boolean_expression(E,LS,S,WF),
410 (nonvar(E),bsyntaxtree:check_if_typed_predicate(E),type_check(LS,store),type_check(S,store),
411 type_check(WF,wait_flag))).
412 :- assert_post(b_interpreter:b_test_boolean_expression(_,_,_,WF), type_check(WF,wait_flag)).
413
414
415 %b_test_boolean_expression(Expr,_,_,_) :- print('test: '),translate:print_bexpr(Expr),nl,print(Expr),nl,fail. %%
416
417 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
418 :- if(environ(prob_debug_watch_flag,true)).
419 b_test_boolean_expressiond(b(Expr,_,Infos),LS,S,WF,Ai,Ao) :- !,
420 b_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,Ao).
421 b_test_boolean_expression(Expr,LS,S,WF,Ai,Ao) :- !,
422 (waitflag0_is_set(WF)
423 -> debug:watch(300,b_interpreter:b_test_boolean_expressiond(Expr,LS,S,WF,Ai,Ao))
424 ; debug:watch_det(300,b_interpreter:b_test_boolean_expressiond(Expr,LS,S,WF,Ai,Ao)) ).
425 :- else.
426 b_test_boolean_expression(b(Expr,Type,Infos),LS,S,WF,Ai,Ao) :- !,
427 (preference(smt_supported_interpreter,true)
428 -> b_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,Ao),
429 get_wait_flag1(smt_call,WF,BeforeEnumWF),
430 gensym:gensym(smt_assertion_name,Symbol),
431 smt_add_predicate(BeforeEnumWF,b(Expr,Type,Infos),LS,S,Symbol)
432 ;
433 ? b_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,Ao)).
434 :- endif.
435 b_test_boolean_expression(E,LS,S,WF,Ai,Ao) :-
436 add_internal_error('Boolean expression not properly wrapped: ',
437 b_test_boolean_expression(E,LS,S,WF,Ai,Ao)),
438 b_test_boolean_expression2(E,[],LS,S,WF,Ai,Ao).
439
440
441 b_test_boolean_expression2(truth,_,_,_,_WF,Ai,Ao) :- !,Ai=Ao.
442 b_test_boolean_expression2(falsity,_,_,_,_WF,_Ai,_Ao) :- !,fail.
443 b_test_boolean_expression2(negation(BExpr),_,LocalState,State,WF,Ai,Ao) :- !,
444 ? b_not_test_boolean_expression(BExpr,LocalState,State,WF,Ai,Ao).
445 b_test_boolean_expression2(conjunct(LHS,RHS),_,LocalState,State,WF,Ai,Ao) :- !,
446 ? b_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii),
447 ? b_test_boolean_expression(RHS,LocalState,State,WF,Aii,Ao).
448 b_test_boolean_expression2(implication(LHS,RHS),Info,LocalState,State,WF,Ai,Ao) :-
449 %b_compiler:b_compile(LHS,[],LocalState,State,CLHS), % this slows down Cruise benchmark from 3.75 s to 4.3
450 !,
451 ? b_test_implication(LHS,RHS,Info,LocalState,State,WF,Ai,Ao).
452 b_test_boolean_expression2(equivalence(LHS,RHS),_,LocalState,State,WF,Ai,Ao) :- !,
453 ? b_test_equivalence(LHS,RHS,LocalState,State,WF,Ai,Ao).
454 b_test_boolean_expression2(disjunct(LHS,RHS),Info,LocalState,State,WF,Ai,Ao) :- !,
455 % TO DO: normalise disjunct first ?
456 copy_wf_start(WF,disjunct,CWF),
457 ? if(b_check_boolean_expression(LHS,LocalState,State,CWF,PredRes,Ai,Aii),
458 % we can check lhs
459 ? if(b_interpreter_check:b_check_boolean_expression0(pred_false,PredRes,RHS,LocalState,State,CWF,RR,Aii,Ao),
460 ( /* we can also check rhs */
461 ? b_interpreter_check:disjoin(PredRes,RR,pred_true,LHS,RHS,WF),
462 copy_wf_finish(WF,CWF)
463 ),
464 (
465 Ao=Aii,
466 copy_wf_finish(WF,CWF),
467 imply_test_boolean_expression(PredRes,pred_false,RHS,LocalState,State,WF,Aii),
468 perfmessagecall(choice_point,reification_of_disjunction_rhs_failed,translate:print_bexpr(RHS),Info),
469 enumerate_bool(PredRes,15,WF)
470 )
471 ),
472 % we cannot check lhs
473 if((always_well_defined(RHS),
474 b_check_boolean_expression(RHS,LocalState,State,CWF,PredRes,Ai,Aii)),
475 (
476 Ao=Aii,
477 copy_wf_finish(WF,CWF),
478 imply_test_boolean_expression(PredRes,pred_false,LHS,LocalState,State,WF,Aii),
479 perfmessagecall(choice_point,reification_of_disjunction_lhs_failed,translate:print_bexpr(LHS),Info),
480 enumerate_bool(PredRes,15,WF)
481 ),
482 % we cannot check neither lhs nor rhs:
483 (Ai=Ao,
484 get_priority_of_boolean_expression2(disjunct(LHS,RHS),StartPrio),
485 %get_wait_flag(Prio,disjunct,WF,WF2),
486 get_binary_choice_wait_flag_exp_backoff(StartPrio,disjunct,WF,WF2),
487 % be sure that e.g. for (x=2 or x=3) both branches will be tested once deterministic propagation is over
488 %print(prio(Prio)), print(' : '),print_bexpr(LHS), print(' or '), print_bexpr(RHS),nl,
489 perfmessagecall(choice_point,reification_of_disjunction_failed,translate:print_bexpr(b(disjunct(LHS,RHS),pred,Info)),Info),
490 b_test_disjunction(LHS,RHS,LocalState,State,WF,WF2,Ai)
491 )
492 )
493 ).
494 b_test_boolean_expression2(exists(Parameters,RHS),Infos,LocalState,State,WF,Ai,Ao) :- !,Ai=Ao,
495 ? b_test_exists(Parameters,RHS,Infos,LocalState,State,WF).
496 %b_test_boolean_expression2(forall(PARS,LHS,RHS),_Inf,LocalState,State,WF) :-
497 % PARS = [b(identifier(R1),integer,_),b(identifier(R2),integer,_)],
498 % LHS = b(conjunct(b(conjunct(MEM1,MEM2),pred,_I1),NEQ),pred,_I2),
499 % NEQ = b(not_equal(b(identifier(RR1),integer,_I3),b(identifier(RR2),integer,_I4)),pred,_I5),
500 % (RR1=R1, RR2=R2 ; RR1=R2, RR2=R1),
501 % MEM1 = b(member(b(identifier(RRR1),integer,_),b(SET,set(integer),_)),pred,_),
502 % MEM2 = b(member(b(identifier(RRR2),integer,_),b(SET,set(integer),_)),pred,_),
503 % (RRR1=R1, RRR2=R2 ; RRR1=R2, RRR2=R1),
504 % /* TO DO: check that RHS is symmetric ! */ /* TO DO : generalize symmetry breaking */
505 % !, % print(symmetry_breaking_forall(R1,R2)),nl,
506 % GT = b(less(b(identifier(R1),integer,_I3),b(identifier(R2),integer,_I4)),pred,_I5),
507 % NewLHS = b(conjunct(b(conjunct(MEM1,MEM2),pred,_I1),GT),pred,_I2),
508 % b_test_boolean_expression2(forall(PARS,NewLHS,RHS),_Inf,LocalState,State,WF).
509 b_test_boolean_expression2(forall(Parameters,LHS,RHS),Infos,LocalState,State,WF,Ai,Ao) :- !,Ai=Ao,
510 /* !ID.(LHS => RHS) */
511 % print_message(forall(Parameters,LHS,RHS)),
512 % get_wait_flag0(WF,WF0), when(nonvar(WF0),
513 ? b_for_all(Parameters,Infos,LHS,RHS,LocalState,State,WF). %).
514 b_test_boolean_expression2(let_predicate(Ids,AssignmentExprs,Pred),Infos,LocalState,State,WF,Ai,Ao) :- !,
515 Ai=Ao, % any expression inside the LET cannot be safely reused
516 (is_truth(Pred)
517 -> % useless let, only sense of computations below is in detecting WD errors
518 get_enumeration_starting_wait_flag(useless_let_predicate(Ids),WF,ESWF),
519 when(nonvar(ESWF),set_up_localstate_for_let(Ids,_,AssignmentExprs,LocalState,State,_LetState,WF))
520 ? ; set_up_localstate_for_let(Ids,ParaValues,AssignmentExprs,LocalState,State,LetState,WF),
521 opt_push_wait_flag_call_stack_quantifier_info(WF,let_quantifier,Ids,ParaValues,Infos,WF2),
522 ? b_test_boolean_expression(Pred,LetState,State,WF2)). % we could pass Ai in if Ids fresh
523
524 b_test_boolean_expression2(lazy_let_pred(Id,AssignmentExpr,Expr),_I,LocalState,State,WF,Ai,Ao) :- !,
525 add_lazy_let_id_and_expression(Id,AssignmentExpr,LocalState,State,NewLocalState,WF,Ai),
526 ? b_test_boolean_expression(Expr,NewLocalState,State,WF,Ai,Ao). % we could use Ai,Ao version as lazy lets never interfere with each other and never invalidate existing expressions
527 b_test_boolean_expression2(lazy_lookup_pred(Id),_Info,LocalState,_State,WF,Ai,Ao) :- !, Ai=Ao,
528 lookup_value_for_existing_id_wf(Id,LocalState,(Trigger,Value),WF), % should normally only occur in LocalState; value introduced by lazy_let
529 (Trigger,Value) = (pred_true,pred_true). % force evaluation
530 b_test_boolean_expression2(value(PredVal),_Info,_LocalState,_State,_WF,Ai,Ao) :- !, % this can occur when lazy_lookup_pred gets compiled by b_compiler
531 is_pred_true(PredVal),Ai=Ao.
532 b_test_boolean_expression2(Pred,Info,LocalState,State,WF,Ai,Ao) :-
533 % TO DO: we could put some of the operators into the Ai store (comparison operators)
534 ? b_interpreter_check:register_predicate(Pred,Info,pred_true,Reused,Ai,Ao),
535 (Reused==true
536 -> %% print('REUSED: '), translate:print_bexpr(Pred),nl
537 true
538 ? ; b_test_atomic_boolean_expression2(Pred,Info,LocalState,State,WF)).
539
540 :- block is_pred_true(-).
541 is_pred_true(X) :- (X=pred_true -> true ; X=pred_false -> fail ; add_internal_error('Illegal call: ',is_pred_true(X)),fail).
542 :- block is_pred_false(-).
543 is_pred_false(X) :- (X=pred_false -> true ; X=pred_true -> fail ; add_internal_error('Illegal call: ',is_pred_false(X)),fail).
544
545
546 % we could simply call disjunct(NegLHS,RHS) ?
547 % A => B has more of a feeling of a passive constraint than A or B
548 % hence we use a lower priority here for enumerate_bool below and do not
549 % try to reify rhs if lhs reification failed (but maybe we should)
550 b_test_implication(LHS,RHS,_Info,LocalState,State,WF,Ai,Ao) :-
551 copy_wf_start(WF,implication,CWF),
552 ? if(b_check_boolean_expression(LHS,LocalState,State,CWF,PredRes,Ai,Aii),
553 %% print('checking => '), print_bexpr(LHS), print(' '), print(PredRes),nl,
554 %% The following improves constraint propagation; but can be tricky with undefinedness
555 if((var(PredRes),always_well_defined(RHS),
556 b_check_boolean_expression(RHS,LocalState,State,CWF,RHSPredRes,Aii,Ao)),
557 (/* also propagate from right to left */
558 ? b_interpreter_check:imply_true(PredRes,RHSPredRes),
559 perfmessage_bexpr(good(reify),'Fully reified implication with LHS: ',LHS),
560 ? copy_wf_finish(WF,CWF)
561 ),
562 ( Aii=Ao,
563 ? copy_wf_finish(WF,CWF),
564 ? imply_test_boolean_expression(PredRes,pred_true,RHS,LocalState,State,WF,Aii),
565 (nonvar(PredRes) -> true
566 ; performance_monitoring_on,
567 \+always_well_defined(RHS) -> perfmessage_bexpr(reify,'Cannot reify RHS of => due to WD condition, creating choice point:',RHS)
568 ; perfmessage_bexpr(reify,'Cannot reify RHS of =>, creating choice point:',RHS)
569 ),
570 enumerate_bool(PredRes,10000,WF) % lower priority than disjunction (15); we could use last_finite_priority ?
571 )
572 ),
573 ( Ai=Ao,
574 perfmessage_bexpr(reify,'Cannot reify LHS of =>, creating binary choice point:',LHS),
575 get_binary_choice_wait_flag(implication,WF,WF2),
576 block_test_implication(LHS,RHS,LocalState,State,WF,WF2)
577 )
578 ).
579
580 % ------------
581
582 :- discontiguous b_test_atomic_boolean_expression2/5.
583 %b_test_atomic_boolean_expression2(Expr,T,LocalState,State,WF) :- print(eval(Expr,T)),nl,fail.
584 b_test_atomic_boolean_expression2(partition(LHS,RHS),_,LocalState,State,WF) :- !,
585 b_compute_expression(LHS,LocalState,State,SV1,WF), %print(lhs(SV1)),nl,
586 l_compute_expression(RHS,LocalState,State,SV2,WF), % RHS is Prolog list of expressions
587 ? kernel_call_predicate(partition_wf(SV1,SV2,WF),kernel_objects,WF,partition(LHS,RHS)).
588 b_test_atomic_boolean_expression2(member(TElem,TSet),_,LocalState,State,WF) :- !,
589 ? b_test_member_expression(TElem,TSet,LocalState,State,WF).
590 b_test_atomic_boolean_expression2(not_member(TElem,TSet),Info,LocalState,State,WF) :- !,
591 get_texpr_expr(TSet,Set),
592 ? b_test_notmember_expression(Set,TElem,TSet,Info,LocalState,State,WF).
593 b_test_atomic_boolean_expression2(freetype_case(Freetype,Case,Expr),_,LocalState,State,WF) :-
594 !,equal_object_wf(Value,freeval(Freetype,Case,_),b_test_atomic_boolean_expression2,WF),
595 b_compute_expression(Expr,LocalState,State,Value,WF). % NOT COVERED (16)
596 b_test_atomic_boolean_expression2(finite(SetExpr),_,LocalState,State,WF) :-
597 !, b_compute_expression(SetExpr,LocalState,State,Value,WF),
598 kernel_call_predicate(is_finite_set_wf(Value,WF),kernel_objects,WF,finite(SetExpr)).
599 /* Extension for Kodkod */
600 b_test_atomic_boolean_expression2(kodkod(ProblemId,_),_,LocalState,State,WF) :-
601 !,get_wait_flag1(kodkod_call,WF,WF0),
602 kodkod_request(ProblemId,pos,LocalState,State,WF0). % NOT COVERED (17)
603 %b_test_atomic_boolean_expression2(equal(Arg1,Arg2),_,LocalState,State,WF) :- get_texpr_type(Arg1,integer),!,
604 % b_compute_expression(Arg1,LocalState,State,ExprRes,WF),
605 % b_compute_expression(Arg2,LocalState,State,ExprRes,WF). /* avoids one extra variable compared to code below + could fail earlier ; but problem as b_compute_expression still uses = in some places */
606
607 :- include(b_arithmetic_expressions).
608 %The following clause improves Nqueens performance by about 50 %; by avoiding intermediate variables
609 % TO DO: do the same for >, <, >= ...
610 b_test_atomic_boolean_expression2(equal(Arg1,Arg2),Info,LocalState,State,WF) :- !,
611 ? b_test_atomic_equal_boolean_expression(Arg1,Arg2,Info,LocalState,State,WF).
612 b_test_atomic_boolean_expression2(not_equal(Arg1,Arg2),Info,LocalState,State,WF) :- !,
613 ? b_test_atomic_not_equal_boolean_expression(Arg1,Arg2,Info,LocalState,State,WF).
614 b_test_atomic_boolean_expression2(less_equal(Arg1,Arg2),_Info,LocalState,State,WF) :-
615 %get_texpr_type(Arg1,integer), % type checker already checks this
616 preferences:preference(use_clpfd_solver,true),
617 %\+ member(no_clpfd_arith_integer_expression,Info),
618 !,
619 ? b_compute_arith_expression(Arg1,LocalState,State,CLPFD_Expr1,WF),
620 ? b_compute_arith_expression(Arg2,LocalState,State,CLPFD_Expr2,WF),
621 clpfd_interface:clpfd_leq_expr(CLPFD_Expr1,CLPFD_Expr2).
622 b_test_atomic_boolean_expression2(greater_equal(Arg1,Arg2),_Info,LocalState,State,WF) :-
623 %get_texpr_type(Arg1,integer), % type checker already checks this
624 preferences:preference(use_clpfd_solver,true),
625 %\+ member(no_clpfd_arith_integer_expression,Info),
626 !,
627 b_compute_arith_expression(Arg1,LocalState,State,CLPFD_Expr1,WF),
628 b_compute_arith_expression(Arg2,LocalState,State,CLPFD_Expr2,WF),
629 clpfd_interface:clpfd_leq_expr(CLPFD_Expr2,CLPFD_Expr1).
630 b_test_atomic_boolean_expression2(less(Arg1,Arg2),_Info,LocalState,State,WF) :-
631 %get_texpr_type(Arg1,integer), % type checker already checks this
632 preferences:preference(use_clpfd_solver,true),
633 % \+ member(no_clpfd_arith_integer_expression,Info),
634 !,
635 ? b_compute_arith_expression(Arg1,LocalState,State,CLPFD_Expr1,WF),
636 ? b_compute_arith_expression(Arg2,LocalState,State,CLPFD_Expr2,WF),
637 clpfd_interface:clpfd_lt_expr(CLPFD_Expr1,CLPFD_Expr2).
638 b_test_atomic_boolean_expression2(greater(Arg1,Arg2),_Info,LocalState,State,WF) :-
639 %get_texpr_type(Arg1,integer), % type checker already checks this
640 preferences:preference(use_clpfd_solver,true),
641 %\+ member(no_clpfd_arith_integer_expression,Info),
642 !,
643 ? b_compute_arith_expression(Arg1,LocalState,State,CLPFD_Expr1,WF),
644 b_compute_arith_expression(Arg2,LocalState,State,CLPFD_Expr2,WF),
645 clpfd_interface:clpfd_lt_expr(CLPFD_Expr2,CLPFD_Expr1).
646 b_test_atomic_boolean_expression2(external_pred_call(FunName,Args),Info,LocalState,State,WF) :-
647 !,
648 (do_not_evaluate_args(FunName) -> EvaluatedArgs=[]
649 ? ; b_compute_expressions(Args, LocalState,State, EvaluatedArgs, WF)),
650 push_wait_flag_call_stack_info(WF,external_call(FunName,EvaluatedArgs,Info),WF2),
651 ? call_external_predicate(FunName,Args,EvaluatedArgs,LocalState,State,pred_true,Info,WF2).
652 b_test_atomic_boolean_expression2(Expression,Info,LocalState,State,WF) :-
653 preferences:preference(use_clpfd_solver,false),
654 special_binary_predicate(Expression,Module:Kernel_predicate,Arg1,T1,Arg2,T2),
655 (nonmember(contains_wd_condition,Info) -> true ; preference(disprover_mode,true)),
656 !,
657 % print('Special call: '), print_bexpr(Expression),nl, print(Kernel_predicate),print(' : '),nl,
658 %(Arg1==list_of_expressions -> b_compute_expressions ... % no longer needed
659 b_compute_expression(Arg1,LocalState,State,SV1,WF),
660 b_compute_expression(Arg2,LocalState,State,SV2,WF),
661 KernelCall =.. [Kernel_predicate,SV1,T1,SV2,T2,WF],
662 kernel_call_predicate(KernelCall,Module,WF,Expression).
663 b_test_atomic_boolean_expression2(Expression,_,LocalState,State,WF) :-
664 functor(Expression,BOP,2),
665 kernel_mappings:binary_boolean_operator(BOP,Module:Kernel_predicate,WFEnabled),!,
666 arg(1,Expression,Arg1), arg(2,Expression,Arg2),
667 ? b_compute_expression(Arg1,LocalState,State,SV1,WF),
668 (binary_boolean_operator_trivially_true(BOP,SV1)
669 -> check_well_defined(Arg2,LocalState,State,WF)
670 ? ; b_compute_expression(Arg2,LocalState,State,SV2,WF),
671 ( WFEnabled==yes ->
672 KernelCall =.. [Kernel_predicate,SV1,SV2,WF2],
673 (do_not_enumerate_binary_boolean_operator(BOP,Arg1,Arg2) % we assume: this is only true for WFEnabled predicates
674 -> add_wait_flag_info(WF,wfx_no_enumeration,WF2)
675 ; WF2=WF)
676 ; KernelCall =.. [Kernel_predicate,SV1,SV2], WF2=WF % note: WF2 still used in kernel_call_predicate
677 ),
678 ? kernel_call_predicate(KernelCall,Module,WF2,Expression)).
679 b_test_atomic_boolean_expression2(E,Info,_LS,_S,_WF) :-
680 add_internal_error('Uncovered boolean expression: ',b(E,pred,Info)),
681 print_functor(E),nl,
682 fail.
683
684
685 binary_boolean_operator_trivially_true(subset,X) :- X==[].
686
687 check_well_defined(Arg,_LocalState,_State,_WF) :-
688 always_well_defined(Arg),!.
689 check_well_defined(Arg,LocalState,State,WF) :-
690 b_compute_expression(Arg,LocalState,State,_,WF).
691
692 %:- use_module(specfile,[animation_minor_mode/1]).
693 :- use_module(b_machine_hierarchy,[abstract_constant/2, concrete_constant/2]).
694 b_test_atomic_equal_boolean_expression(Arg1,Arg2,_Info,LocalState,State,WF) :-
695 Arg1 = b(_,integer,_), %get_texpr_type(Arg1,integer),
696 preferences:preference(use_clpfd_solver,true),!,
697 (Arg2 = b(_,integer,_) -> true ; add_internal_error('Type error in AST, not wrapped integer: ',Arg2)),
698 ? b_test_arith_equal_boolean_expression(Arg1,Arg2,LocalState,State,WF).
699 b_test_atomic_equal_boolean_expression(Arg1,Arg2,Info,LocalState,State,WF) :-
700 ? member(prob_annotation('LAMBDA-EQUALITY'),Info),
701 \+ simple_expression(Arg2),
702 is_lambda_result_id(Arg1), %get_texpr_id(Arg1,'_lambda_result_'), % ensure we have not renamed it to was_lambda_result ?
703 !, % this is an equality for the result of a lambda abstraction; only evaluate at the end
704 b_compute_expression(Arg1,LocalState,State,SV1,WF), % this is the lambda result identifier _lambda_result_
705 %get_enumeration_finished_wait_flag(WF,EWF),
706 %get_wait_flag(10000,lambda_result,WF,EWF),
707 % compute deterministic parts of Arg2 in wf0 phase: avoid computing this stuff over again
708 %print('DELAY: '), translate:print_bexpr(Arg2),nl,
709 kernel_waitflags:copy_wf01e_wait_flags(WF,WF2), b_compute_expression(Arg2,LocalState,State,SV2,WF2),
710 get_last_wait_flag(lambda_result,WF,EWF),
711 ground_value_check(SV2,G2),
712 when((nonvar(G2);nonvar(SV1);nonvar(EWF)),b_lambda_result_equal_boolean_expression(SV1,SV2,WF,EWF,WF2)).
713 b_test_atomic_equal_boolean_expression(Arg1,Arg2,Info,LocalState,State,WF) :-
714 (LocalState = []
715 -> true % only check if we are at the outer level
716 % (not inside a quantifier,...) or if we have CSE introduzed lazy_lets:
717 ; preferences:preference(use_common_subexpression_elimination,true)
718 % TO DO: check that we have only added @nr to local state from lazy_let; ADD INFO FIELD
719 ),
720 get_texpr_type(Arg1,Type1), is_set_type(Type1,SetType1),
721 % previously we required SetType1 = couple(_,_)
722 get_texpr_id(Arg1,ID),
723 % we could check: \+ get_texpr_id(Arg2,_), % as we do not need to treat simple equations like ID = ID2; unless for memo?
724 ? (abstract_constant(ID,_) % check if ABSTRACT_CONSTANT
725 -> Kind=abstract,
726 ? kernel_objects:max_cardinality(Type1,MaxCard1),
727 (number(MaxCard1) % check that type is large enough to warrant recursive or symbolic treatment
728 -> (MaxCard1>100 -> true ; constant_variable_marked_as_memo(ID))
729 ; true)
730 ; %fail,
731 ? concrete_constant(ID,_)
732 -> Kind=concrete,
733 (constant_variable_marked_as_expand(ID)
734 -> true % note: we also check for expand annotation in store (expand_closure_value),
735 % but it is useful to expand ID already here to ease checking PROPERTIES
736 ; constant_variable_marked_as_memo(ID))
737 %; b_is_unused_constant(ID) -> ABSTRACT=true % TO DO: check if ID not used somewhere else in Properties ??!!
738 ),
739 % in future: we may do size change analysis, or something like that to check that we have properly defined
740 % recursive function
741 debug_format(19,'Equation defining ~w constant: ~w~n',[Kind,ID]),
742 !,
743 (constant_variable_marked_as_expand(ID) -> SymArg2 = Arg2 ; mark_bexpr_as_symbolic(Arg2,SymArg2)),
744 ? b_add_constant_definition(Kind,ID,Info,Arg1,SetType1,SymArg2,LocalState,State,WF).
745 b_test_atomic_equal_boolean_expression(Arg1,Arg2,_Info,LocalState,State,WF) :-
746 ? b_compute_expression(Arg1,LocalState,State,SV1,WF),
747 ? b_compute_expression(Arg2,LocalState,State,SV2,WF),
748 ? kernel_call_predicate_equal_object_optimized(SV1,SV2,WF).
749
750
751
752 % treat equality ID = Symbolic Function (or relation/set)
753 b_add_constant_definition(Kind,ID,Info,Arg1,SetType1,SymArg2,LocalState,State,WF) :-
754 % observe CTRL-C: e.g., in data validation models these abstract functions can be very large and costly to compute
755 ? observe_user_interrupt_signal(computing_value_for_abstract_constant(ID),SymArg2,
756 b_add_constant_definition_aux(Kind,ID,Info,Arg1,SetType1,SymArg2,LocalState,State,WF)).
757
758 b_add_constant_definition_aux(Kind,ID,_Info,Arg1,SetType1,SymArg2,LocalState,State,WF) :-
759 (preference(use_function_memoization,true), Kind=abstract ;
760 constant_variable_marked_as_memo(ID)), % description(memo) as info field using @desc memo pragma; see
761 !,
762 b_compute_expression(Arg1,LocalState,State,SV1,WF), % the identifier
763 (SymArg2 = b(recursive_let(TID,Body),_,_)
764 -> get_texpr_id(TID,RecID),
765 b_compute_expression(Body,[bind(RecID,RedIDVal)|LocalState],State,SV2,WF),
766 RecValue='$recursion_value'(RedIDVal)
767 ; b_compute_expression(SymArg2,LocalState,State,SV2,WF),
768 RecValue='$no_recursion'
769 ),
770 (nonvar(SV2), SV2 \= closure(_,_,_)
771 -> % value fully computed; no need to memoize
772 debug_println(19,not_memoizing(ID)),
773 kernel_call_predicate_equal_object_optimized(SV1,SV2,WF)
774 ; mark_closure_as_symbolic(SV2,SV3),
775 % what if SV2 is var?
776 memoization:register_memoization_function(ID,SV3,SetType1,RecValue,MEMOID,SV4),
777 debug_println(19,marking_for_memoization(ID,MEMOID)),
778 %print_term_summary(registered_fun(ID,MEMOID,SV4)),nl,
779 kernel_call_predicate_equal_object_optimized(SV1,SV4,WF)
780 ).
781 b_add_constant_definition_aux(_Kind,ID,Info,Arg1,_,SymArg2,LocalState,State,WF) :-
782 b_compute_expression(Arg1,LocalState,State,SV1,WF), % the identifier
783 ? b_compute_expression(SymArg2,LocalState,State,SV2,WF),
784 (constant_variable_marked_as_expand(ID)
785 -> b_expand_compute_comprehension_set(SV2,Info,SV3,WF)
786 ; definitely_expand_this_explicit_set(SV2) % check for a few patterns which should definitely be expanded;
787 % in case user puts a set accidentally into the ABSTRACT_CONSTANTS section
788 -> b_expand_compute_comprehension_set(SV2,Info,SV3,WF)
789 ; var(SV2) -> SV3=SV2
790 ; mark_closure_as_symbolic(SV2,SV3)
791 ),
792 kernel_call_predicate_equal_object_optimized(SV1,SV3,WF).
793
794 % treat not(Arg1 = Arg2) predicates
795 b_test_atomic_not_equal_boolean_expression(Arg1,Arg2,_Info,LocalState,State,WF) :-
796 get_texpr_type(Arg1,boolean),!, % special treatment : not_equal_object has no type information
797 b_compute_expression(Arg1,LocalState,State,B1,WF),
798 b_compute_expression(Arg2,LocalState,State,B2,WF),
799 negate(B1,B2). % from bool_pred
800 b_test_atomic_not_equal_boolean_expression(Arg1,Arg2,_Info,LocalState,State,WF) :-
801 get_texpr_type(Arg1,integer),
802 preferences:preference(use_clpfd_solver,true),
803 %\+ member(no_clpfd_arith_integer_expression,Info),
804 !,
805 % Note: calling b_compute_arith_expression will also instantiate a variable to at least the int(_) skeleton; thereby enabling propagation
806 % this is potentially better than calling the default versions of the predicates, which may wait until the int(_) skeleton is set up before propagation
807 ? b_compute_arith_expression(Arg1,LocalState,State,CLPFD_Expr1,WF),
808 ? b_compute_arith_expression(Arg2,LocalState,State,CLPFD_Expr2,WF),
809 clpfd_interface:clpfd_neq_expr(CLPFD_Expr1,CLPFD_Expr2).
810 b_test_atomic_not_equal_boolean_expression(Arg1,Arg2,_Info,LocalState,State,WF) :-
811 ? b_compute_expression(Arg1,LocalState,State,SV1,WF),
812 (nonvar(SV1), SV1=closure(_,_,_), % first argument is symbolic
813 Arg2 = b(comprehension_set(PP,CC),_,InfoCS) % second arg is a comprehension set;
814 % TODO: deal with other constructs which merit symbolic treatment; union of comprehension sets, ...
815 % (see line 147 in AMASS_mchs/oriented_abscissa.mch)
816 -> % print(symbolic_neq(PP)),nl,
817 b_compute_comprehension_set_symbolic(PP,CC,InfoCS,LocalState,State,SV2,WF)
818 % Note: this case occurs for symbolic abstract constants f when using DOUBLE_EVALUATION
819 % in the evaluation view which are defined by f = %x... when checking f /= %x....
820 ? ; b_compute_expression(Arg2,LocalState,State,SV2,WF)
821 ),
822 kernel_call_predicate_not_equal_object(SV1,SV2,WF,not_equal(Arg1,Arg2)).
823
824
825 simple_expression(b(A,_,_)) :- simple_expression_aux(A).
826 simple_expression_aux(boolean_true).
827 simple_expression_aux(boolean_false).
828 simple_expression_aux(empty_set).
829 simple_expression_aux(empty_sequence).
830 simple_expression_aux(integer(_)).
831 simple_expression_aux(max_int).
832 simple_expression_aux(min_int).
833 simple_expression_aux(string(_)).
834 simple_expression_aux(value(_)).
835
836
837 is_lambda_result_id(b(identifier('_lambda_result_'),_,_)).
838 % at the moment we only detect those identifiers; the info field is currently not updated for _was_lambda_result_
839 % and not available in other treatmens of _lambda_result_ (in b_enumerate)
840 %is_lambda_result_id(b(identifier(X),_,Info)) :-
841 % memberchk(lambda_result,Info).
842 % (X=='_lambda_result_' -> (memberchk(lambda_result,Info) -> true ; format('~n*** _lambda_result_ without info: ~w~n~N',[Info])) ; memberchk(lambda_result,Info)).
843
844 %:- block b_lambda_result_equal_boolean_expression(-,?,?, -,?). % we now use when above
845 % only compute lambda result when finished finding domain element, i.e., _EWF is grounded
846 b_lambda_result_equal_boolean_expression(SV1,SV2,WF,EWF,WF2) :-
847 kernel_call_predicate_equal_object_optimized(SV1,SV2,WF),
848 % print(' LAMBDA : '), print((SV1,_EWF)),nl,
849 % the inner waitflags are for evaluating the lambda_result Expression; unless there is a WD issue this should
850 % never fail; we can delay the enumeration as much as possible
851 % NOTE: even if SV2 is ground, Arg2 may not be (e.g., if Arg2 = prj2(..,..)(NotGr,Ground))
852 ? blocking_ground_copied_wait_flags(WF2,EWF). % without when we will ground WF0 which is shared with outer WF-store
853 :- block blocking_ground_copied_wait_flags(?,-).
854 blocking_ground_copied_wait_flags(WF2,_) :-
855 ? ground_constraintprop_wait_flags(WF2). % do not ground EF flag, as shared with outer WF and WF2 is copied
856
857 % TO DO: add avl_set+closure expansion
858 %b_test_member_expression(Expr,El,_Set,_LocalState,_State,_WF) :-
859 % print('test member: '),print_bexpr(Expr),nl,fail.
860 b_test_member_expression(TElem,b(Set,Type,Info),LocalState,State,WF) :-
861 ? b_test_member_expression2(Set,Type,Info,TElem,LocalState,State,WF).
862
863 % new profiler
864 %:- use_module('../extensions/profiler/profiler.pl').
865 %:- use_module('../extensions/profiler/profiler_te.pl').
866 %:- enable_profiling(b_test_member_expression2/7).
867
868 % old profiler
869 %:- use_module(covsrc(hit_profiler)).
870
871 b_test_member_expression2(comprehension_set(Par,Cond),_Type,_Info,El,LocalState,State,WF) :-
872 % used to call in next clause below: b_generate_closure_if_necessary(Par,Cond,LocalState,State,SetValue,WF) /* will not expand closure */
873 /* optimized case for dealing with comprehension_set ; however, does not seem to buy anything over older version with b_generate_closure_if_necessary in test 1079 */
874 /* new version buys about 6 % for {x| x:1..400000 & x:{n|n >= 9000 & n<= 600000 & n mod 100 = 0}} (Sep 3 2014) */
875 set_up_typed_localstate(Par,ValueList,_TypedVals,LocalState,NewLocalState,positive),
876 !,
877 convert_list_into_pairs(ValueList,ElementVal),
878 b_compute_expression(El,LocalState,State,ElementVal,WF),
879 b_test_boolean_expression(Cond,NewLocalState,State,WF).
880 b_test_member_expression2(SymbolicSetConstant,_Type,_Info,El,LocalState,State,WF) :-
881 %hit_profiler:add_profile_hit(SymbolicSetConstant),
882 cst_in_boolean_type(SymbolicSetConstant,Module:Kernel_predicate),!, % two cases : string_set and integer_set
883 b_compute_expression(El,LocalState,State,ElValue,WF),
884 functor(KernelCall,Kernel_predicate,2),
885 arg(1,KernelCall,ElValue),
886 arg(2,KernelCall,WF),
887 % print_message(cst_in_boolean_type_call(KernelCall)),
888 kernel_call_predicate(KernelCall,Module,WF,SymbolicSetConstant). % should be member(... SymbolicSetConstant)
889 b_test_member_expression2(Expression,_Type,Info,El,LocalState,State,WF) :-
890 functor(Expression,BOP,2),
891 binary_in_boolean_type(BOP,Module:Kernel_predicate),!,
892 b_compute_expression(El,LocalState,State,ElValue,WF),
893 arg(1,Expression,Arg1),arg(2,Expression,Arg2),
894 (binary_in_definitely_true(BOP,ElValue)
895 -> % no need to compute arguments; unless required for WD:
896 check_well_defined(Arg1,LocalState,State,WF),
897 check_well_defined(Arg2,LocalState,State,WF)
898 ; b_compute_expression(Arg1,LocalState,State,SV1,WF),
899 ? b_compute_expression(Arg2,LocalState,State,SV2,WF),
900 opt_push_wait_flag_call_stack_info(WF,b_operator_call(member,[ElValue,b_operator(BOP,[SV1,SV2])],Info),WF2),
901 ? binary_in_kernel_call(Module,Kernel_predicate,ElValue,SV1,SV2,WF2,Expression)
902 ).
903 b_test_member_expression2(Expression,_Type,Info,El,LocalState,State,WF) :-
904 functor(Expression,UnOP,1),
905 unary_in_boolean_type(UnOP,Module:Kernel_predicate),!,
906 b_compute_expression(El,LocalState,State,ElValue,WF),
907 arg(1,Expression,Arg1),
908 (unary_in_definitely_true(UnOP,ElValue)
909 -> % no need to compute arguments; unless required for WD:
910 check_well_defined(Arg1,LocalState,State,WF)
911 ? ; b_compute_expression(Arg1,LocalState,State,SV1,WF),
912 opt_push_wait_flag_call_stack_info(WF,b_operator_call(member,[ElValue,b_operator(UnOP,[SV1])],Info),WF2),
913 ? unary_in_kernel_call(Module,Kernel_predicate,ElValue,SV1,WF2,Expression)
914 ).
915 b_test_member_expression2(SetExpression,Type,Info,El,LocalState,State,WF) :-
916 ? b_compute_expression2(SetExpression,Type,Info,LocalState,State,SetValue,WF),
917 (always_well_defined_or_disprover_mode(El)
918 -> SetValue \== [] % if we have the empty set: check_element will always fail
919 ; true % we could check SetValue \== [] if find_abort_values=false ??
920 ),
921 ? b_compute_expression(El,LocalState,State,Element,WF),
922 Span = El, % Info is quite often the empty list
923 (not_invertible(El) % then no sense in setting up member constraint f(...) : SetValue ;
924 % we cannot used the info anyway; but we could enumerate
925 -> % we wait until Element is fully known before doing the check
926 ground_value_check(Element,GrEl),
927 when(nonvar(GrEl),kernel_call_predicate_check_element_of_wf(Element,SetValue,WF,Span))
928 ? ; kernel_call_predicate_check_element_of_wf(Element,SetValue,WF,Span)).
929
930 :- use_module(external_functions,[external_fun_can_be_inverted/1]).
931 not_invertible(b(E,_,_)) :- not_inv_aux(E).
932 not_inv_aux(external_function_call(FunName,_Args)) :- \+ external_fun_can_be_inverted(FunName).
933 % TO DO: capture other cases like function applications
934 % TO DO: also do this in b_interpreter_check ?
935 % TO DO: We should compute this information in ast_cleanup; e.g., what if we do STRING_TO_INT(s)+1 : SET
936
937 % TO DO: >>> 2:{x,v} --> special case for set_extension([b(identifier(x),integer,[nodeid(none)]),b(identifier(v),integer,[nodeid(none)])]) --> 2=x or 2=v --> evaluate [x,v] -> sort and then use list member (or should b_ast_cleanup do this) ?
938
939 :- use_module(kernel_lists,[not_element_of_list_wf/3]).
940 b_test_notmember_expression(set_extension(Ex),El,_Set,_,LocalState,State,WF) :- !,
941 b_compute_expressions(Ex,LocalState,State,ExValueList,WF),
942 b_compute_expression(El,LocalState,State,ElementVal,WF),
943 not_element_of_list_wf(ElementVal,ExValueList,WF).
944 b_test_notmember_expression(SymbolicSetCst,El,_Set,_,LocalState,State,WF) :-
945 kernel_mappings:cst_not_in_boolean_type(SymbolicSetCst,Module:Kernel_predicate),!,
946 b_compute_expression(El,LocalState,State,ElValue,WF),
947 functor(KernelCall,Kernel_predicate,1),
948 arg(1,KernelCall,ElValue),
949 % debug_print(cst_not_in_boolean_type(9,KernelCall)),
950 kernel_call_predicate(KernelCall,Module,WF,SymbolicSetCst).
951 b_test_notmember_expression(Expression,El,_Set,Info,LocalState,State,WF) :-
952 functor(Expression,BOP,2),
953 kernel_mappings:binary_not_in_boolean_type(BOP,Module:Kernel_predicate),!,
954 b_compute_expression(El,LocalState,State,ElValue,WF),
955 \+ binary_in_definitely_true(BOP,ElValue),
956 arg(1,Expression,Arg1),arg(2,Expression,Arg2),
957 b_compute_expression(Arg1,LocalState,State,SV1,WF),
958 b_compute_expression(Arg2,LocalState,State,SV2,WF),
959 % KernelCall =.. [Kernel_predicate,ElValue,SV1,SV2,WF],
960 opt_push_wait_flag_call_stack_info(WF,b_operator_call(not_member,[ElValue,b_operator(BOP,[SV1,SV2])],Info),WF2),
961 ? kernel_call_predicate3(Kernel_predicate,ElValue,SV1,SV2,Module,WF2,Expression).
962 b_test_notmember_expression(Expression,El,_Set,Info,LocalState,State,WF) :-
963 functor(Expression,UnOP,1),
964 unary_not_in_boolean_type(UnOP,Module:Kernel_predicate),!,
965 b_compute_expression(El,LocalState,State,ElValue,WF),
966 \+ unary_in_definitely_true(UnOP,ElValue),
967 arg(1,Expression,Arg1),
968 b_compute_expression(Arg1,LocalState,State,SV1,WF),
969 %KernelCall =.. [Kernel_predicate,ElValue,SV1,WF],
970 %kernel_call_predicate(KernelCall,Module,WF,Expression).
971 opt_push_wait_flag_call_stack_info(WF,b_operator_call(not_member,[ElValue,b_operator(UnOP,[SV1])],Info),WF2),
972 kernel_call_predicate2(Kernel_predicate,ElValue,SV1,Module,WF2,Expression).
973 b_test_notmember_expression(Expr,Elem,Set,_Info,LocalState,State,WF) :-
974 (Expr=comprehension_set(Par,Cond)
975 -> b_generate_closure_if_necessary(Par,Cond,LocalState,State,SetValue,WF) /* will not expand closure */
976 ; b_compute_expression(Set,LocalState,State,SetValue,WF)
977 ),
978 (SetValue == []
979 -> /* nothing can be member of empty set */
980 check_well_defined(Elem,LocalState,State,WF)
981 % we could disable this check if find_abort_values=true
982 ; b_compute_expression(Elem,LocalState,State,ElemValue,WF),
983 %kernel_call_predicate2(not_element_of_wf,ElemValue,SetValue,kernel_objects,WF,Expr)
984 %kernel_call_predicate(not_element_of_wf(ElemValue,SetValue,WF),kernel_objects,WF,Expr)
985 kernel_call_predicate_not_element_of_wf(ElemValue,SetValue,WF)
986 ).
987
988 :- block block_test_implication(?,?,?,?,?,-).
989 block_test_implication(LHS,RHS,LocalState,State,WF,_WF2) :-
990 ? b_test_inner_boolean_expression(LHS,LocalState,State,WF),
991 b_test_inner_boolean_expression(RHS,LocalState,State,WF).
992 block_test_implication(LHS,_RHS,LocalState,State,WF,_WF2) :-
993 b_not_test_inner_boolean_expression(LHS,LocalState,State,WF).
994
995
996 b_test_equivalence(LHS,RHS,LocalState,State,WF,Ai,Ao) :-
997 copy_wf_start(WF,equivalence,CWF),
998 ? if(b_check_boolean_expression(LHS,LocalState,State,CWF,PredRes,Ai,Aii),
999 ? (b_check_test_equivalence(PredRes,LHS,RHS,LocalState,State,CWF,Aii,Ao),
1000 copy_wf_finish(WF,CWF)),
1001 (% check LHS fails, We could check if RHS can be checked with b_check_boolean_expression
1002 Ai=Ao, get_binary_choice_wait_flag(equivalence,WF,WF2),
1003 b_enum_test_equivalence(LHS,RHS,LocalState,State,WF,WF2,Ai))).
1004 b_not_test_equivalence(LHS,RHS,LocalState,State,WF,Ai,Ao) :-
1005 copy_wf_start(WF,not_equivalence,CWF),
1006 if(b_check_boolean_expression(LHS,LocalState,State,CWF,PredRes,Ai,Aii),
1007 (negate(PredRes,NegPredRes), % from bool_pred
1008 ? b_check_test_equivalence(NegPredRes,LHS,RHS,LocalState,State,CWF,Aii,Ao),
1009 copy_wf_finish(WF,CWF)),
1010 (% check LHS fails, We could check if RHS can be checked with b_check_boolean_expression
1011 Ai=Ao, get_binary_choice_wait_flag(not_equivalence,WF,WF2),
1012 b_enum_not_test_equivalence(LHS,RHS,LocalState,State,WF,WF2,Ai))).
1013 b_check_test_equivalence(PredRes,LHS,RHS,LocalState,State,WF,Aii,Ao) :-
1014 % print('checking <=> '), print_bexpr(LHS), print(' '), print(PredRes),nl,
1015 (var(PredRes),b_check_boolean_expression(RHS,LocalState,State,WF,PredRes2,Aii,Ao) % TO DO <---- REPLACE CUT
1016 -> /* also propagate from right to left */
1017 ? equiv_bidrectional_test_boolean_expression(PredRes,PredRes2,LHS,RHS,LocalState,State,WF)
1018 ; Aii=Ao,
1019 ? equiv_test_boolean_expression(PredRes,pred_true,RHS,LocalState,State,WF,Aii)
1020 ). % should we also add a binary choice flag ?? what about a=2 <=> b/=3 ??
1021
1022 :- block b_enum_test_equivalence(?,?,?,?,?,-,?).
1023 b_enum_test_equivalence(LHS,RHS,LocalState,State,WF,_WF2,Ai) :-
1024 b_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii), % TO DO: we could call b_test_inner_boolean_expression with Ai
1025 b_test_boolean_expression(RHS,LocalState,State,WF,Aii,_).
1026 b_enum_test_equivalence(LHS,RHS,LocalState,State,WF,_WF2,Ai) :-
1027 b_not_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii),
1028 b_not_test_boolean_expression(RHS,LocalState,State,WF,Aii,_).
1029
1030 %enumerate_bool(X,WF) :- !.
1031 enumerate_bool(X,Prio,WF) :- (nonvar(X) -> true /* already set */
1032 ; get_wait_flag0(WF,WF0),
1033 enumerate_bool0(X,Prio,WF,WF0)).
1034
1035 :- block enumerate_bool0(?,?,?,-).
1036 enumerate_bool0(X,Prio,WF,_) :- (nonvar(X) -> true /* already set */
1037 ; %print(enum_bool(X)), translate:print_bexpr(LHS),nl,
1038 % get_binary_choice_wait_flag(enumerate_bool,WF,WF2),
1039 get_wait_flag(Prio,enumerate_bool,WF,WF2), % what priority should we use ?? give time for other enumerators to decide the lhs of the disjunct; actions_cbtc is slower to setup with low priority
1040 enumerate_bool_aux(X,WF2)).
1041 :- block enumerate_bool_aux(-,-).
1042 %enumerate_bool_aux(P,WF) :- var(P),print(forcing_bool(P,WF)),nl,fail. %
1043 enumerate_bool_aux(pred_true,_).
1044 enumerate_bool_aux(pred_false,_).
1045
1046 :- block b_test_disjunction(?,?,?,?,?,-,?).
1047 b_test_disjunction(LHS,_RHS,LocalState,State,WF,_WF2,Ai) :-
1048 ? b_test_boolean_expression(LHS,LocalState,State,WF,Ai,_).
1049 b_test_disjunction(LHS,RHS,LocalState,State,WF,_WF2,Ai) :-
1050 b_not_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii),
1051 ? b_test_boolean_expression(RHS,LocalState,State,WF,Aii,_).
1052
1053 :- block b_not_test_conjunction(?,?,?,?,?,-,?).
1054 b_not_test_conjunction(LHS,_RHS,LocalState,State,WF,_WF2,Ai) :-
1055 b_not_test_boolean_expression(LHS,LocalState,State,WF,Ai,_).
1056 b_not_test_conjunction(LHS,RHS,LocalState,State,WF,_WF2,Ai) :-
1057 ? b_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii),
1058 ? b_not_test_boolean_expression(RHS,LocalState,State,WF,Aii,_).
1059
1060 :- block b_enum_not_test_equivalence(?,?,?,?,?,-,?).
1061 b_enum_not_test_equivalence(LHS,RHS,LocalState,State,WF,_WF2,Ai) :-
1062 b_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii), % we could call b_test_inner_boolean_expression with Ai
1063 b_not_test_boolean_expression(RHS,LocalState,State,WF,Aii,_).
1064 b_enum_not_test_equivalence(LHS,RHS,LocalState,State,WF,_WF2,Ai) :-
1065 b_not_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii),
1066 b_test_boolean_expression(RHS,LocalState,State,WF,Aii,_).
1067
1068
1069
1070 /* --------------------------------------*/
1071 /* b_not_test_boolean_expression */
1072 /* --------------------------------------*/
1073
1074 b_not_test_list_of_boolean_expression([],_,_,_WF).
1075 b_not_test_list_of_boolean_expression([B1|T],LS,S,WF) :-
1076 b_not_test_boolean_expression(B1,LS,S,WF),
1077 b_not_test_list_of_boolean_expression(T,LS,S,WF).
1078
1079 :- assert_pre(b_interpreter:b_not_test_boolean_expression_cs(E,LS,S,_,_),
1080 (bsyntaxtree:check_if_typed_predicate(E),type_check(LS,store),type_check(S,store))).
1081 :- assert_post(b_interpreter:b_not_test_boolean_expression_cs(_,_,_,_,_), true).
1082
1083
1084 % a version where we can provide an initial call stack entry for context
1085 b_not_test_boolean_expression_cs(E,LS,S,PredKind,Nr) :-
1086 init_wait_flags_cs(E,PredKind,Nr,b_not_test_boolean_expression_cs,WF), % TODO: we could register negation info
1087 % TO DO: call b_trace_test_components ?
1088 ? b_not_test_boolean_expression(E,LS,S,WF),
1089 ? ground_wait_flags(WF).
1090
1091 b_not_test_boolean_expression(E,LS,S,WF) :-
1092 ? empty_avl(Ai), b_not_test_boolean_expression(E,LS,S,WF,Ai,_).
1093
1094 :- assert_pre(b_interpreter:b_not_test_boolean_expression(E,LS,S,WF),
1095 (type_check(E,boolean_expression),type_check(LS,store),type_check(S,store), type_check(WF,wait_flag))).
1096 :- assert_post(b_interpreter:b_not_test_boolean_expression(_,_,_,_), true).
1097
1098 :- if(environ(prob_debug_watch_flag,true)).
1099 b_not_test_boolean_expression(b(Expr,_,Infos),LS,S,WF,Ai,Ao) :- !,
1100 (waitflag0_is_set(WF)
1101 -> debug:watch(400,b_interpreter:b_not_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,Ao))
1102 ; debug:watch_det(400,b_interpreter:b_not_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,Ao)) ).
1103 :- else.
1104 b_not_test_boolean_expression(b(Expr,Type,Infos),LS,S,WF,Ai,Ao) :- !,
1105 (preference(smt_supported_interpreter,true)
1106 -> b_not_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,Ao),create_negation(b(Expr,Type,Infos),Neg),
1107 get_wait_flag1(smt_call,WF,BeforeEnumWF),
1108 gensym:gensym(smt_assertion_name,Symbol),
1109 smt_add_predicate(BeforeEnumWF,Neg,LS,S,Symbol)
1110 ? ; b_not_test_boolean_expression2(Expr,Infos,LS,S,WF,Ai,Ao)).
1111 :- endif.
1112 b_not_test_boolean_expression(E,LS,S,WF,Ai,Ao) :-
1113 add_internal_error('Boolean (not) expression not properly wrapped: ',
1114 b_not_test_boolean_expression(E,LS,S,WF,Ai,Ao)),
1115 b_not_test_boolean_expression2(E,[],LS,S,WF,Ai,Ao).
1116
1117 b_not_test_boolean_expression2(truth,_,_,_,_WF,_Ai,_Ao) :- !,fail.
1118 b_not_test_boolean_expression2(falsity,_,_,_,_WF,Ai,Ao) :- !,Ai=Ao. % NOT COVERED (2)
1119 b_not_test_boolean_expression2(negation(BExpr),_,LocalState,State,WF,Ai,Ao) :- !,
1120 b_test_boolean_expression(BExpr,LocalState,State,WF,Ai,Ao).
1121 % following makes test 349 fail:
1122 %b_not_test_boolean_expression2(conjunct(LHS,RHS),Infos,LocalState,State,WF,Ai,Ao) :- !,
1123 % nl, print(' NOT: '),translate:print_bexpr(b(conjunct(LHS,RHS),pred,Infos)),nl,
1124 % create_negation(LHS,NegLHS), % TO DO: avoid this construction by generalising code for disjunct
1125 % create_negation(RHS,NegRHS),
1126 % b_test_boolean_expression2(disjunct(NegLHS,NegRHS),Infos,LocalState,State,WF,Ai,Ao).
1127 b_not_test_boolean_expression2(conjunct(LHS,RHS),Infos,LocalState,State,WF,Ai,Ao) :- !,
1128 b(conjunct(LHS,RHS),pred,Infos) = Conj,
1129 copy_wf_start(WF,not_conjunct,CWF),
1130 ? if(b_check_boolean_expression(Conj,LocalState,State,CWF,PredRes,Ai,Ao),
1131 (PredRes=pred_false,
1132 ? copy_wf_finish(WF,CWF)
1133 ),
1134 if(b_check_boolean_expression(LHS,LocalState,State,CWF,LHSPredRes,Ai,Ao), % some redundant work with call above: TODO: avoid !
1135 (copy_wf_finish(WF,CWF),
1136 get_last_wait_flag(not_conjunct_rhs,WF,WF2), % before starting to enumerate infinite types: better try both possibilities:
1137 b_not_test_conjunction_rhs(LHSPredRes,RHS,LocalState,State,WF,Ai,WF2)
1138 ),
1139 (Ai=Ao,
1140 get_priority_of_boolean_expression2(disjunct(LHS,RHS),StartPrio),
1141 %get_wait_flag(Prio,not_conjunct,WF,WF2),
1142 get_binary_choice_wait_flag_exp_backoff(StartPrio,not_conjunct,WF,WF2),
1143 % TO DO: we could check if LHS or RHS are registered in Ai as pred_true/pred_false ??
1144 b_not_test_conjunction(LHS,RHS,LocalState,State,WF,WF2,Ai))
1145 )
1146 ).
1147
1148 b_not_test_boolean_expression2(implication(LHS,RHS),_,LocalState,State,WF,Ai,Ao) :- !,
1149 b_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii),
1150 ? b_not_test_boolean_expression(RHS,LocalState,State,WF,Aii,Ao).
1151 b_not_test_boolean_expression2(equivalence(LHS,RHS),_,LocalState,State,WF,Ai,Ao) :- !,
1152 ? b_not_test_equivalence(LHS,RHS,LocalState,State,WF,Ai,Ao).
1153 b_not_test_boolean_expression2(disjunct(LHS,RHS),_,LocalState,State,WF,Ai,Ao) :- !,
1154 b_not_test_boolean_expression(LHS,LocalState,State,WF,Ai,Aii),
1155 b_not_test_boolean_expression(RHS,LocalState,State,WF,Aii,Ao).
1156 b_not_test_boolean_expression2(lazy_let_pred(Id,AssignmentExpr,Expr),_I,LocalState,State,WF,Ai,Ao) :- !,
1157 add_lazy_let_id_and_expression(Id,AssignmentExpr,LocalState,State,NewLocalState,WF,Ai),
1158 b_not_test_boolean_expression(Expr,NewLocalState,State,WF,Ai,Ao). % we could use Ai,Ao version as lazy lets never interfere with each other and never invalidate existing expressions
1159 b_not_test_boolean_expression2(lazy_lookup_pred(Id),_Info,LocalState,_State,WF,Ai,Ao) :- !, Ai=Ao,
1160 lookup_value_for_existing_id_wf(Id,LocalState,(Trigger,Value),WF), % should normally only occur in LocalState; value introduced by lazy_let
1161 (Trigger,Value) = (pred_true,pred_false). % force evaluation
1162 b_not_test_boolean_expression2(value(PredVal),_Info,_LocalState,_State,_WF,Ai,Ao) :- !, % this can occur when lazy_lookup_pred gets compiled by b_compiler
1163 is_pred_false(PredVal),Ai=Ao.
1164 b_not_test_boolean_expression2(Expr,Info,LocalState,State,WF,Ai,Ao) :-
1165 % TO DO: we could put some of the operators into the Ai store (comparison operators)
1166 ? b_not_test_atomic_boolean_expression2(Expr,Info,LocalState,State,WF,Ai,Ao).
1167
1168 % Other boolean expressions, not involving boolean connectives
1169 b_not_test_atomic_boolean_expression2(exists(Parameters,RHS),Infos,LocalState,State,WF,Ai,Ao) :- !,
1170 /* #ID.(RHS) */
1171 Ai=Ao,
1172 ? b_not_test_exists(Parameters,RHS,Infos,LocalState,State,compile,WF).
1173 b_not_test_atomic_boolean_expression2(forall(Parameters,LHS,RHS),Infos,LocalState,State,WF,Ai,Ao) :- !,
1174 /* !ID.(LHS => RHS) */
1175 Ai=Ao,
1176 safe_create_texpr(negation(RHS),pred,Negation),
1177 conjunct_predicates_with_pos_info(LHS,Negation,Condition),
1178 % conjunct_predicates merges the used_ids Info in Condition
1179 b_test_exists(Parameters,Condition,Infos,LocalState,State,WF).
1180 /* TODO(DP, 2.8.2008): Extension for Z: a let-statement as predicate */
1181 b_not_test_atomic_boolean_expression2(let_predicate(Ids,AssignmentExprs,Pred),Infos,LocalState,State,WF,Ai,Ao) :-
1182 !,Ai=Ao, % any expression inside the LET cannot be safely reused
1183 ? set_up_localstate_for_let(Ids,ParaValues,AssignmentExprs,LocalState,State,LetState,WF),
1184 opt_push_wait_flag_call_stack_quantifier_info(WF,let_quantifier,Ids,ParaValues,Infos,WF2),
1185 b_not_test_boolean_expression(Pred,LetState,State,WF2). % NOT COVERED (10)
1186 /* TODO(DP, 2.8.2008): */
1187 b_not_test_atomic_boolean_expression2(freetype_case(Freetype,Case,Expr),_,LocalState,State,WF,Ai,Ao) :-
1188 !,Ai=Ao,b_compute_expression(Expr,LocalState,State,freeval(Freetype,RealCase,_),WF),
1189 dif(RealCase,Case). % NOT COVERED (11)
1190 b_not_test_atomic_boolean_expression2(finite(SetExpr),_,LocalState,State,WF,Ai,Ao) :-
1191 !, Ai=Ao,b_compute_expression(SetExpr,LocalState,State,Value,WF),
1192 kernel_call_predicate(is_infinite_set_wf(Value,WF),kernel_objects,WF,finite(SetExpr)).
1193 /* Extension for Kodkod */
1194 b_not_test_atomic_boolean_expression2(kodkod(ProblemId,_),_,LocalState,State,WF,Ai,Ao) :-
1195 !,Ai=Ao,get_wait_flag1(kodkod_negative_call,WF,WF0),
1196 kodkod_request(ProblemId,neg,LocalState,State,WF0). % NOT COVERED (12)
1197 b_not_test_atomic_boolean_expression2(partition(LHS,RHS),Info,LocalState,State,WF,Ai,Ao) :- !,
1198 b_interpreter_check:register_predicate(partition(LHS,RHS),Info,pred_false,Reused,Ai,Ao),
1199 (Reused==true -> true
1200 ; b_compute_expression(LHS,LocalState,State,SV1,WF),
1201 l_compute_expression(RHS,LocalState,State,SV2,WF), % RHS is Prolog list of expressions
1202 kernel_call_predicate(not_partition_wf(SV1,SV2,WF),kernel_objects,WF,partition(LHS,RHS))
1203 ).
1204 b_not_test_atomic_boolean_expression2(external_pred_call(FunName,Args),Info,LocalState,State,WF,Ai,Ao) :-
1205 !, Ai=Ao,
1206 (do_not_evaluate_args(FunName) -> EvaluatedArgs=[]
1207 ; b_compute_expressions(Args, LocalState,State, EvaluatedArgs, WF)),
1208 push_wait_flag_call_stack_info(WF,external_call(FunName,EvaluatedArgs,Info),WF2),
1209 call_external_predicate(FunName,Args,EvaluatedArgs,LocalState,State,pred_false,Info,WF2).
1210 b_not_test_atomic_boolean_expression2(Pred,Info,LocalState,State,WF,Ai,Ao) :-
1211 b_interpreter_check:register_predicate(Pred,Info,pred_false,Reused,Ai,Ao),
1212 (Reused==true
1213 -> %% print('REUSED (not): '), translate:print_bexpr(Pred),nl,
1214 true
1215 ? ; b_not_test_atomic_boolean_expression3(Pred,Info,LocalState,State,WF)).
1216 b_not_test_atomic_boolean_expression3(Expression,Info,LocalState,State,WF) :-
1217 functor(Expression,BOP,2),
1218 ? kernel_mappings:negate_binary_boolean_operator(BOP,NBOP),
1219 arg(1,Expression,Arg1),arg(2,Expression,Arg2),!,
1220 NExpression =.. [NBOP,Arg1,Arg2],
1221 ? b_test_atomic_boolean_expression2(NExpression,Info,LocalState,State,WF).
1222 b_not_test_atomic_boolean_expression3(Expression,Info,LocalState,State,WF) :-
1223 functor(Expression,BOP,2),
1224 kernel_mappings:negate_binary_boolean_operator_swap(BOP,NBOP),
1225 arg(1,Expression,Arg1),arg(2,Expression,Arg2),!,
1226 NExpression =.. [NBOP,Arg2,Arg1],
1227 b_test_atomic_boolean_expression2(NExpression,Info,LocalState,State,WF).
1228 b_not_test_atomic_boolean_expression3(E,_,_,_,_WF) :-
1229 add_internal_error('Uncovered boolean expression (not): ',E),
1230 print_functor(E),nl,fail.
1231
1232
1233 % test RHS of not-conjunction depending on outcome of LHS
1234 :- block b_not_test_conjunction_rhs(-,?,?,?,?,?,-).
1235 b_not_test_conjunction_rhs(pred_false,_RHS,_LocalState,_State,_WF,_Ai,_LWF).
1236 b_not_test_conjunction_rhs(pred_true,RHS,LocalState,State,WF,Ai,_LWF) :-
1237 ? b_not_test_boolean_expression(RHS,LocalState,State,WF,Ai,_).
1238
1239 /* -----------------------------*/
1240 /* b_compute_expression */
1241 /* -----------------------------*/
1242
1243
1244
1245 :- assert_must_succeed((b_interpreter:b_compute_expression(b(pow_subset(
1246 b(identifier(nm),set(integer),[])),set(set(integer)),[]),
1247 [], [bind(nm,[])],R,_WF),
1248 nonvar(R), custom_explicit_sets:expand_custom_set_to_list(R,[[]]))).
1249 :- assert_must_succeed((b_interpreter:b_compute_expression(b(pow_subset(
1250 b(identifier(nm),set(boolean),[])),set(set(boolean)),[]),[],
1251 [bind(nm,[pred_false /* bool_false */])],R,_WF),
1252 nonvar(R), custom_explicit_sets:expand_custom_set_to_list(R,ER),
1253 kernel_objects:equal_object(ER,[[pred_false /* bool_false */],[]]))).
1254
1255 :- assert_pre(b_interpreter:b_compute_expression(Exp,LS,State,_Val,WF),
1256 (nonvar(Exp),
1257 bsyntaxtree:check_if_typed_expression(Exp),
1258 type_check(LS,store),type_check(State,store), type_check(WF,wait_flag))).
1259 :- assert_post(b_interpreter:b_compute_expression(_E,_LS,_State,Val,WF),
1260 (b_interpreter:value_type(Val), type_check(WF,wait_flag))). %, nonvar(Val)
1261
1262 b_compute_expression_nowf(E,LS,S,R) :-
1263 b_compute_expression_nowf(E,LS,S,R,none,0).
1264
1265 b_compute_expression_nowf(E,LS,S,R,FormulaKind,Nr) :-
1266 get_texpr_info(E,Info),
1267 ? b_compute_expression_nowf(E,LS,S,R,FormulaKind,Nr,Info).
1268 b_compute_expression_nowf(E,LS,S,R,FormulaKind,Nr,Span) :-
1269 %add_message(b_compute_expression,'Called Version wo WFLAGS: ', b_compute_expression(E,LS,S,R)),
1270 (FormulaKind = none -> init_wait_flags(WF,[b_compute_expression_nowf])
1271 ; CallStackEntry = prob_command_context(eval_expr_command(FormulaKind,Nr),Span),
1272 init_wait_flags_and_push_call_stack(no_wf_available,CallStackEntry,WF)
1273 ),
1274 ? b_compute_expression(E,LS,S,R,WF),
1275 ? ground_wait_flags(WF), % this will add abort errors and fail before enumerating the result:
1276 init_wait_flags(WF2,[b_compute_expression_nowf2]),
1277 get_texpr_type(E,Type),
1278 b_enumerate:b_tighter_enumerate_single_value(R,Type,Span,b_compute_expression_nowf,WF2), %should rarely be necessary
1279 % a non-ground result only occurs when WD error appears and in this case ground_wait_flags will fail after
1280 % adding the abort error (and thus no value is returned)
1281 % exceptions are test 1066 with a complicated set comprehension used in a function application
1282 % test 1861 relies on two phase enumeration
1283 ground_wait_flags(WF2).
1284
1285 l_compute_expression([],_LS,_S,[],_WF).
1286 l_compute_expression([H|T],LS,S,[CH|CT],WF) :-
1287 b_compute_expression(H,LS,S,CH,WF),
1288 l_compute_expression(T,LS,S,CT,WF).
1289
1290 :- if(environ(prob_debug_watch_flag,true)).
1291 b_compute_expressiond(b(Expr,Type,Info),LS,S,R,WF) :- !,
1292 ((ground(Type), Type \== pred, Type \== subst) -> true
1293 ; add_error_wf(b_compute_expression,'Expression has illegal type: ',b(Expr,Type,Info),WF)),
1294 check_value(R,b(Expr,Type,Info)),
1295 b_compute_expression2(Expr,Type,Info,LS,S,R,WF).
1296 :- block check_value(-,?).
1297 check_value(pred_true,_) :- !. check_value(pred_false,_) :- !.
1298 check_value(string(_),_) :- !.
1299 check_value([],_) :- !.
1300 check_value([H|T],E) :- !, check_value(H,E), check_value(T,E).
1301 check_value((A,B),E) :- !, check_value(A,E), check_value(B,E).
1302 check_value(fd(N,T),E) :- !, (nonvar(T) -> check_fd(N,T,E) ; check_err(fd(N,T),E)).
1303 check_value(global_set(GS),E) :- !,(nonvar(GS) -> true ; check_err(global_set(GS),E)).
1304 check_value(avl_set(AS),E) :- !,((nonvar(AS),AS=node(_,_,_,_,_)) -> true ; check_err(global_set(AS),E)).
1305 check_value(int(X),E) :- !,check_int(X,E).
1306 check_value(closure(P,T,B),E) :- !,
1307 (ground(P),ground(T),nonvar(B)
1308 -> (same_length(P,T) -> bsyntaxtree:check_ast(B) ; check_err(closure_not_same_length(P,T)))
1309 ; check_err(closure(P,T,B),E)).
1310 check_value(rec(_),_) :- !. %TODO: check
1311 check_value(X,E) :- check_err(uncovered(X),E).
1312 % TO DO: add records + more thorough checking of global_set and closures and avl_sets
1313 :- block check_int(-,?).
1314 check_int(X,E) :- (number(X) -> true ; check_err(int(X),E)).
1315 :- block check_fd(-,?,?).
1316 check_fd(X,T,E) :- (number(X),b_get_fd_type_bounds(T,Low,Up),X>=Low,X=<Up -> true ; check_err(fd(X,T),E)).
1317
1318 check_err(V,E) :- add_internal_error('Illegal value when computing expression: ',V:E).
1319 b_compute_expression(E,LS,S,R,WF) :- !,
1320 (waitflag0_is_set(WF)
1321 -> debug:watch(100,b_interpreter:b_compute_expressiond(E,LS,S,R,WF))
1322 ; debug:watch_det(100,b_interpreter:b_compute_expressiond(E,LS,S,R,WF))).
1323 :- else.
1324 b_compute_expression(b(Expr,Type,Info),LS,S,R,WF) :- !,
1325 ((ground(Type), Type \== pred, Type \== subst) -> true
1326 ; add_internal_error_wf(b_interpreter,'Expression has non-ground type: ',b(Expr,Type,Info),Info,WF)
1327 ),
1328 ? b_compute_expression2(Expr,Type,Info,LS,S,R,WF).
1329 :- endif.
1330 b_compute_expression(Expr,LS,S,R,WF) :-
1331 add_internal_error('Expression not properly wrapped: ',b_compute_expression(Expr,LS,S,R,WF)),
1332 b_compute_expression2(Expr,unknown,[],LS,S,R,WF).
1333
1334
1335 :- use_module(bsyntaxtree,[get_texpr_set_type/2]).
1336
1337 %:- use_module(b_global_sets,[b_type2_set/2]).
1338 %b_compute_expression2(V,T,I,LS,S,R,_WF) :- nonvar(R), print('result_instantiated: '(R:V)),nl,fail.
1339 ?b_compute_expression2(value(Val),_T,_I,_LS,_S,V,WF) :- !, equal_object_wf(Val,V,WF). %Val=V.
1340 b_compute_expression2(boolean_true,_T,_I,_LState,_State,Res,_WF) :- !, Res = pred_true /* bool_true */. % for simple types we can use ordinary unification
1341 b_compute_expression2(boolean_false,_T,_I,_LState,_State,Res,_WF) :- !, Res = pred_false /* bool_false */.
1342 b_compute_expression2(integer_set(NSET),_T,_I,_LState,_State,Res,WF) :- !, equal_object_wf(Res,global_set(NSET),WF). %Res = global_set(NSET).
1343 b_compute_expression2(bool_set,_T,_I,_LState,_State,Res,WF) :- !, % b_type2_set(bool,Res).
1344 equal_object_wf(Res,avl_set(node(pred_false,true,1,empty,node(pred_true,true,0,empty,empty))),WF).
1345 % was equal_object(Res,[pred_true /* bool_true */,pred_false /* bool_false */]) % changing this to avl used to break test 800 Bosch Deadlock v9; probably because of identity closure detection instantiation
1346 b_compute_expression2(float_set,_T,_I,_LState,_State,Res,WF) :- !, equal_object_wf(Res,global_set('FLOAT'),WF).
1347 b_compute_expression2(real_set,_T,_I,_LState,_State,Res,WF) :- !, equal_object_wf(Res,global_set('REAL'),WF).
1348 b_compute_expression2(string_set,_T,_I,_LState,_State,Res,WF) :- !, equal_object_wf(Res,global_set('STRING'),WF).
1349 % was all_strings(Res). %% NOT COVERED (6)
1350 b_compute_expression2(string(S),_T,_I,_LState,_State,Res,_WF) :- !,
1351 % TODO(ML,26.8.2008): Check if we should use a different functor for syntax tree vs data
1352 Res = string(S).
1353 b_compute_expression2(typeset,Type,_I,_LState,_State,Res,WF) :- !,
1354 is_set_type(Type,ElType), % we could generate global_set('STRING'),... for certain types
1355 equal_object_wf(Res,closure('_zzzz_unary',[ElType],b(truth,pred,[])),WF).
1356 b_compute_expression2(empty_set,_T,_I,_LState,_State,Res,_WF) :- !, empty_set(Res).
1357 b_compute_expression2(empty_sequence,_T,_I,_LState,_State,Res,_WF) :- !, empty_sequence(Res).
1358 b_compute_expression2(event_b_identity,EType,_I,_LState,_State,Res,WF) :-
1359 get_set_type(EType,couple(Type,Type)),!,
1360 event_b_identity_for_type(Type,Res,WF).
1361 b_compute_expression2(integer(Val),_T,_I,_LocalState,_State,Res,_WF) :- !, Res = int(Val).
1362 b_compute_expression2(max_int,_T,_I,_LS,_S,Res,_WF) :-
1363 preferences:get_preference(maxint,CVal),!, Res = int(CVal).
1364 b_compute_expression2(min_int,_T,_I,_LS,_S,Res,_WF) :-
1365 preferences:get_preference(minint,CVal),!, Res = int(CVal).
1366 b_compute_expression2(identifier(Id),Type,Info,LocalState,State,Res,WF) :- !,
1367 lookup_value_in_store_and_global_sets_wf(Id,Type,LocalState,State,Value,Info,WF),
1368 equal_object_wf(Res,Value,WF).
1369 b_compute_expression2(lazy_lookup_expr(Id),_Type,_Info,LocalState,_State,Res,WF) :- !,
1370 lookup_value_for_existing_id_wf(Id,LocalState,(Trigger,Value),WF), % should normally only occur in LocalState; value introduced by lazy_let
1371 Trigger = pred_true, % force evaluation
1372 equal_object_wf(Res,Value,WF).
1373 b_compute_expression2(lazy_let_expr(Id,AssignmentExpr,Expr),_T,_I,LocalState,State,Value,WF) :-
1374 !,
1375 add_lazy_let_id_and_expression(Id,AssignmentExpr,LocalState,State,NewLocalState,WF),
1376 %Trigger = pred_true, % expressions cannot be delayed !? (TO DO: more refined check)
1377 %block_lazy_compute_expression(Trigger,_,AssignmentExpr,LocalState,State,IdValue,WF,Ai),
1378 b_compute_expression(Expr,NewLocalState,State,Value,WF).
1379 b_compute_expression2(real(Atom),_T,_I,_LocalState,_State,Res,_WF) :- !, construct_real(Atom,Res).
1380 b_compute_expression2(rec(Fields),_T,_I,LocalState,State,Record,WF) :- !,
1381 ? l_compute_field(Fields,LocalState,State,FieldValues,WF),
1382 ? construct_record_wf(FieldValues,Record,WF).
1383 b_compute_expression2(record_field(RecEx,Name),_T,_I,LocalState,State,Value,WF) :- !,
1384 ? b_compute_expression(RecEx,LocalState,State,RecValue,WF),
1385 access_record_wf(RecValue,Name,Value,WF).
1386 b_compute_expression2(freetype_set(Id),_T,_I,_LState,_State,Val,_WF) :- !, Val=freetype(Id). %% NOT COVERED (17)
1387 b_compute_expression2(function(Function,FunArg),Type,Info,LocalState,State,Res,WF) :- !,
1388 ? b_compute_expression_function(Function,FunArg,Type,Info,LocalState,State,Res,WF).
1389 b_compute_expression2(card(b(Arg1,Type,Info)),integer,OuterInfo,LocalState,State,Card,WF) :- !,
1390 ? b_compute_card(Arg1,Type,Info,OuterInfo,LocalState,State,Card,WF).
1391 b_compute_expression2(max(b(Arg1,Type,Info)),integer,_I,LocalState,State,Max,WF) :- !,
1392 b_compute_max(Arg1,Type,Info,LocalState,State,Max,WF).
1393 b_compute_expression2(min(b(Arg1,Type,Info)),integer,_I,LocalState,State,Min,WF) :- !,
1394 b_compute_min(Arg1,Type,Info,LocalState,State,Min,WF).
1395 b_compute_expression2(set_extension(Ex),Type,_I,LocalState,State,Res,WF) :- !,
1396 ? b_compute_expressions(Ex,LocalState,State,ExValue,WF),
1397 kernel_call(b_interpreter:convert_list_of_expressions_into_set_wf(ExValue,ValueSet,Type,WF),ExValue,WF, set_extension(Ex)),
1398 ? equal_object_wf(Res,ValueSet,WF).
1399 %kernel_call_convert_list_of_expressions_into_set_wf(ExValue,ValueSet,Type, WF).
1400 %b_compute_expression('ListTermes'(ListOfEx),LocalState,State,ValueSet,WF) :- !,
1401 % /* convert list of expressions of CASE statement into set of elements */
1402 % b_compute_expression(ListOfEx,LocalState,State,Value,WF),
1403 % init_wait_flags(WF),convert_list_of_expressions_into_set_wf(Value,ValueSet,set(any),WF),ground_wait_flags(WF).
1404 b_compute_expression2(sequence_extension(Ex),_T,_I,LocalState,State,ValueSeq,WF) :- !,
1405 ? b_compute_expressions(Ex,LocalState,State,Value,WF),
1406 kernel_call(b_interpreter:convert_list_of_expressions_into_sequence(Value,ValueSeq),Value,WF,sequence_extension(Ex)).
1407 b_compute_expression2(convert_bool(PRED),_T,_I,LocalState,State,Val,WF) :- !, /* B bool(.) operator */
1408 ? b_convert_bool(PRED,LocalState,State,WF,Val).
1409 b_compute_expression2(couple(El1,El2),_T,_I,LocalState,State,Result,WF) :- !, Result = (Val1,Val2),
1410 ? b_compute_expression(El1,LocalState,State,Val1,WF),
1411 ? b_compute_expression(El2,LocalState,State,Val2,WF).
1412 b_compute_expression2(comprehension_set(Parameters,Condition),_T,Info,LocalState,State,Result,WF) :- !,
1413 ? b_compute_comprehension_set(Parameters,Condition,Info,LocalState,State,Result,WF).
1414 b_compute_expression2(recursive_let(TId,TSet),OrigType,OrigInfo,LocalState,State,Result,WF) :- !,
1415 % LET TId = TSet in TSet
1416 ( get_texpr_expr(TSet,comprehension_set(Parameters,Condition)) ->
1417 true % if the argument TSet is a comprehension set,
1418 % we just add a recursive parameter
1419 ; get_texpr_set_type(TSet,Type) ->
1420 % if not, we construct a new comprehension set {x | x:TSet}
1421 unique_typed_id("_tmparg_",Type,TArg),
1422 Parameters=[TArg],
1423 safe_create_texpr(member(TArg,TSet),pred,Condition)
1424 ;
1425 add_internal_error('Expected set as argument to recursive_let',
1426 b_compute_expression2(recursive_let(TId,TSet),OrigType,OrigInfo,LocalState,State,Result,WF)),fail
1427 ),
1428 % Generate closure where the references to the recursion are kept
1429 % add recursion ID to parameters to prevent removal of references during compilation
1430 generate_recursive_closure(TId,recursion,[TId|Parameters],Condition,LocalState,State,Closure1,WF),
1431 % add_message(b_interpreter,'Recursive Let for: ',TId,TId),
1432 % remove recursion ID from parameters after compilation
1433 Closure1=closure([_|P],[_|T],Cond),RClosure=closure(P,T,Cond),
1434 % Generate closure where the references to the recursion are kept
1435 generate_recursive_closure(TId,RClosure,Parameters,Condition,LocalState,State,Result,WF).
1436 b_compute_expression2(general_sum(Ids,Condition,Expression),Type,Info,LocalState,State,SumResult,WF) :- !,
1437 b_general_sum_or_mul(Ids,Condition,Expression,Type,Info,LocalState,State,SumResult,WF,sum).
1438 b_compute_expression2(general_product(Ids,Condition,Expression),Type,Info,LocalState,State,MulResult,WF) :- !,
1439 b_general_sum_or_mul(Ids,Condition,Expression,Type,Info,LocalState,State,MulResult,WF,mul).
1440 /* Begin: Extensions for Z */
1441 b_compute_expression2(if_then_else(If,Then,Else),T,_I,LocalState,State,Value,WF) :- !,
1442 ? b_try_check_boolean_expression_wf(If,LocalState,State,WF,PredRes),
1443 (var(PredRes), can_get_full_fd_value(T), preferences:preference(use_clpfd_solver,true),
1444 always_well_defined(Then), always_well_defined(Else)
1445 % Note: always_well_defined_or_disprover_mode probably not ok, as we evaluate the expressions unconditionally
1446 -> b_clpfd_if_then_else(PredRes,T,Then,Else,LocalState,State,Value,WF)
1447 ; b_compute_if_then_else(PredRes,Then,Else,LocalState,State,Value,WF)
1448 ).
1449 b_compute_expression2(let_expression_global(Ids,AssignmentExprs,Expr),_T,Info,LocalState,State,Value,WF) :-
1450 debug_println(4,global_let(Ids,Info)),
1451 % store variables globally (not in LocalState) to be visible to subsidiary operation_calls
1452 !, set_up_localstate_for_global_let(Ids,AssignmentExprs,LocalState,State,LetState,WF),
1453 b_compute_expression(Expr,LocalState,LetState,Value,WF).
1454 b_compute_expression2(let_expression(Ids,AssignmentExprs,Expr),_T,_I,LocalState,State,Value,WF) :-
1455 ? !, set_up_localstate_for_let(Ids,_ParaValues,AssignmentExprs,LocalState,State,LetState,WF),
1456 ? b_compute_expression(Expr,LetState,State,Value,WF). %% NOT COVERED (30)
1457 b_compute_expression2(freetype_constructor(Id,Case,Expr),_T,_I,LocalState,State,FreeValue,WF) :-
1458 !, FreeValue = freeval(Id,Case,Value),
1459 b_compute_expression(Expr,LocalState,State,Value,WF). %% NOT COVERED (32)
1460 b_compute_expression2(freetype_destructor(Id,Case,Expr),_T,Info,LocalState,State,Value,WF) :-
1461 !, b_compute_expression(Expr,LocalState,State,freeval(Id,VCase,VValue),WF),
1462 check_freetype_case(Id,Case,VCase,VValue,Value,Info,WF).
1463 /* End: Extensions for Z */
1464 b_compute_expression2(assertion_expression(Cond,ErrMsg,Expr),T,Info,LocalState,State,Value,WF) :- !,
1465 opt_push_wait_flag_call_stack_info(WF,
1466 span_predicate(b(assertion_expression(Cond,ErrMsg,b(value(string('')),string,[])),T,Info),LocalState,State),WF2),
1467 % should we use another term for call stack?
1468 (get_preference(disprover_mode,true) -> PredRes = pred_true ; true), % in Disprover mode we know Cond must be true
1469 ? b_try_check_boolean_expression_no_enum_wf(Cond,LocalState,State,WF2,PredRes), % DO NOT ENUM, unless we cannot reify
1470 % does not make sense to enumerate PredRes as with pred_false we get no value anyway
1471 % however, we may get pending co-routines if Cond cannot be reified
1472 ( PredRes==pred_false ->
1473 translate_bexpression_with_limit(Cond,100,CS),
1474 add_wd_error_span(ErrMsg,CS,span_predicate(Cond,LocalState,State),WF2),
1475 get_last_wait_flag(assertion_expression,WF2,WFC),
1476 when(nonvar(WFC),
1477 (ground_value(Value) -> true % we have a WD Error, any Value goes
1478 ; b_compute_expression(Expr,LocalState,State,Value,WF2) % compute Value; avoid infinite enumeration of possible values; useful e.g. for prj1/prj2 assertion expressions
1479 ))
1480 ? ; b_compute_expression(Expr,LocalState,State,Value,WF),
1481 add_wd_error_if_false(PredRes,ErrMsg,Cond,span_predicate(Cond,LocalState,State),WF2)
1482 ). %% NOT COVERED (34)
1483 b_compute_expression2(multiplication(Arg1,Arg2),integer,Info,LocalState,State,Value,WF) :-
1484 same_texpr(Arg1,Arg2), !, % is less useful when CLPFD is already turned on, calls square(Arg1,Value,WF)
1485 b_compute_expression(Arg1,LocalState,State,SV1,WF),
1486 unary_kernel_call(kernel_objects,square,SV1,Value,WF,multiplication(Arg1,Arg1),integer,Info).
1487 b_compute_expression2(image(Relation,Set),_EType,_Info,LocalState,State,Value,WF) :-
1488 special_operator_for_image(Relation,Kind,Args),
1489 % we have closure1(Rel)[Set] or similar -> avoid computing full closure
1490 !,
1491 ? b_compute_expression(Set,LocalState,State,SV,WF),
1492 b_compute_expressions(Args,LocalState,State,EArgs,WF),
1493 ? kernel_call(bsets_clp:image_for_special_operator(Kind,EArgs,SV,Value,WF),[SV|EArgs],WF,image(Relation,Set)).
1494 b_compute_expression2(external_function_call(FunName,Args),EType,Info,LocalState,State,Value,WF) :-
1495 !,
1496 ? b_compute_expressions(Args, LocalState,State, EvaluatedArgs, WF),
1497 push_wait_flag_call_stack_info(WF,external_call(FunName,EvaluatedArgs,Info),WF2),
1498 ? call_external_function(FunName,Args,EvaluatedArgs,Value,EType,Info,WF2).
1499 b_compute_expression2(Expression,EType,Info,LocalState,State,Res,WF) :-
1500 is_set_type(EType,Type),
1501 /* avoid evaluating certain expensive expressions:
1502 convert them into symbolic closures and expand only if really required */
1503 functor(Expression,UnOp,1),
1504 symbolic_closure_unary_operator(UnOp),
1505 /* TO DO: UNFOLD THIS OR WRAP in CONSTRUCTOR */
1506 arg(1,Expression,BType),
1507 !, %preferences:get_preference(convert_types_into_closures,true),!,
1508 % print_message(delayed_un_op(UnOp,BType)),
1509 ? b_compute_expression(BType,LocalState,State,ArgValue,WF),
1510 ( do_not_keep_symbolic_unary(UnOp,ArgValue), unary_function(UnOp,Module,KernelFunction) ->
1511 /* special treatment for empty set: no need to keep symbolic */
1512 ? unary_kernel_call(Module,KernelFunction,ArgValue,Res,WF,Expression,EType,Info)
1513 ;
1514 get_texpr_type(BType,ArgType),
1515 create_texpr(value(ArgValue),ArgType,[],TValue),
1516 ClosureSetExpression =.. [UnOp,TValue],
1517 construct_member_closure('_zzzz_unary',Type,Info,ClosureSetExpression,Value),
1518 ? (unop_to_be_marked_as_symbolic(UnOp,ArgValue) ->
1519 mark_closure_as_symbolic(Value,SValue),
1520 equal_object_wf(Res,SValue,WF)
1521 ; equal_object_wf(Res,Value,WF))
1522
1523 ).
1524 b_compute_expression2(Expression,EType,Info,LocalState,State,Res,WF) :-
1525 is_set_type(EType,Type),
1526 /* avoid evaluating certain expensive expressions:
1527 convert them into symbolic closures and expand only if really required */
1528 functor(Expression,BinOp,2),
1529 arg(1,Expression,BType1),
1530 arg(2,Expression,BType2),
1531 kernel_mappings:symbolic_closure_binary_operator(BinOp),
1532 !,
1533 %preferences:get_preference(convert_types_into_closures,true),!,
1534 ? b_compute_expression(BType1,LocalState,State,ArgValue1,WF),
1535 (binary_arg1_determines_value(BinOp,ArgValue1,DetResult)
1536 -> /* print(det(BinOp,ArgValue1)),nl, */
1537 equal_object_wf(Res,DetResult,b_compute_expression2(BinOp),WF)
1538 ; b_compute_expression(BType2,LocalState,State,ArgValue2,WF),
1539 % print_message(delayed_bin_op(BinOp,ArgValue1,ArgValue2)),
1540 (is_definitely_empty(BinOp,ArgValue1,ArgValue2)
1541 -> empty_set(Res)
1542 ; if(do_not_keep_symbolic(BinOp,ArgValue1,ArgValue2,ERes,WF),
1543 % then:
1544 equal_object_wf(Res,ERes,b_compute_expression2(BinOp),WF),
1545 % else:
1546 (get_texpr_type(BType1,TypeArg1), create_texpr(value(ArgValue1),TypeArg1,[],TArg1),
1547 get_texpr_type(BType2,TypeArg2), create_texpr(value(ArgValue2),TypeArg2,[],TArg2),
1548 ClosureSetExpression =.. [BinOp,TArg1,TArg2],
1549 construct_member_closure('_zzzz_unary',Type,Info,ClosureSetExpression,Value),
1550 % print('Constructed Symbolic Closure : '), translate:print_bvalue(Value),nl,
1551 ? (binop_to_be_marked_as_symbolic(BinOp,ArgValue1,ArgValue2) ->
1552 mark_closure_as_symbolic(Value,SValue),
1553 equal_object_wf(Res,SValue,WF)
1554 ; equal_object_wf(Res,Value,WF))
1555 )
1556 ) % if
1557 )
1558 ).
1559 b_compute_expression2(Expression,Type,Info,LocalState,State,Value,WF) :-
1560 functor(Expression,Op,1),
1561 unary_function(Op,Module,KernelFunction),
1562 arg(1,Expression,Arg1),!,
1563 %opt_push_wait_flag_call_stack_info(WF,b_operator_arg_evaluation(Op,1,[SV1],Arg1),WF1),
1564 ? b_compute_expression(Arg1,LocalState,State,SV1,WF),
1565 ? unary_kernel_call(Module,KernelFunction,SV1,Value,WF,Expression,Type,Info).
1566 b_compute_expression2(Expression,Type,Info,LocalState,State,Value,WF) :-
1567 functor(Expression,Op,2),
1568 binary_function(Op,Module,KernelFunction),
1569 arg(1,Expression,Arg1),
1570 arg(2,Expression,Arg2),!,
1571 %opt_push_wait_flag_call_stack_info(WF,b_operator_arg_evaluation(Op,1,[SV1,_],Arg1),WF1),
1572 ? b_compute_expression(Arg1,LocalState,State,SV1,WF),
1573 (binary_arg1_determines_value(Op,SV1,Result) % we could disable this if find_abort_values=true or if SV1 not guaranteed to be wd
1574 ->
1575 equal_object_wf(Value,Result,b_compute_expression2(Op),WF)
1576 ? ; b_compute_expression(Arg2,LocalState,State,SV2,WF),
1577 ? binary_kernel_call(Module,KernelFunction,SV1,SV2,Value,WF,Expression,Type,Info)
1578 ).
1579 b_compute_expression2(operation_call_in_expr(Operation,Parameters),_T,Info,LocalState,State,Value,WF) :-
1580 !, def_get_texpr_id(Operation,op(OperationName)),
1581 % TODO: check that this is a query operation; probably done in type checker
1582 b_execute_operation_in_expression(OperationName,LocalState,State,Parameters,Value,Info,WF).
1583 b_compute_expression2(E,T,Info,_L,_S,_R,_WF) :-
1584 (T==pred -> add_internal_error('Uncovered expression; looks like a predicate in the wrong place: ',b(E,T,Info))
1585 ; T==subst -> add_internal_error('Uncovered expression; looks like a substitution in the wrong place: ',b(E,T,Info))
1586 ; add_internal_error('Uncovered expression: ',b(E,T,Info))
1587 ),
1588 print_functor(E), print(' : '), print(T),nl,fail.
1589
1590 make_couplise([A],R) :- !,R=A.
1591 make_couplise([A,B],R) :- !,R=(A,B).
1592 make_couplise([A,B|Rest],Result) :- !,
1593 make_couplise([(A,B)|Rest],Result).
1594 make_couplise(A,_) :- add_internal_error('Illegal operation call result:',A),fail.
1595
1596 % ---
1597
1598
1599 % check if a symbolic_closure_unary_operator result should be marked with prob_annotation(SYMBOLIC)
1600 % because direct sub-args are marked SYMBOLIC
1601 unop_to_be_marked_as_symbolic(UnOp,Value) :- nonvar(Value),
1602 ? to_be_marked_as_symbolic_aux(UnOp,Value).
1603 to_be_marked_as_symbolic_aux(struct,rec(Fields)) :- !,
1604 ? member(field(_,SymbolicClosure),Fields),
1605 ? is_symbolic_closure(SymbolicClosure).
1606 %to_be_marked_as_symbolic_aux(pow_subset,SymbolicClosure) :- is_symbolic_closure(SymbolicClosure).
1607 %to_be_marked_as_symbolic_aux(pow1_subset,SymbolicClosure) :- is_symbolic_closure(SymbolicClosure).
1608 ?to_be_marked_as_symbolic_aux(_,SymbolicClosure) :- is_symbolic_closure(SymbolicClosure).
1609
1610 % check if a symbolic_closure_binary_operator result should be marked with prob_annotation(SYMBOLIC)
1611 % because direct sub-args are marked SYMBOLIC
1612 binop_to_be_marked_as_symbolic(interval,_,_) :- !, fail.
1613 %binop_to_be_marked_as_symbolic(overwrite,_,_) :- !, true. % TO DO: fix by detecting infinite <+ closures
1614 ?binop_to_be_marked_as_symbolic(set_subtraction,ArgVal1,_) :- !, is_symbolic_closure(ArgVal1).
1615 binop_to_be_marked_as_symbolic(intersection,ArgVal1,ArgVal2) :-
1616 ? (finite_reasonably_sized_set(ArgVal1) ; finite_reasonably_sized_set(ArgVal2)), !,
1617 fail. % intersection is finite and reasonably sized
1618 ?binop_to_be_marked_as_symbolic(_,ArgVal1,_) :- is_symbolic_closure(ArgVal1).
1619 ?binop_to_be_marked_as_symbolic(_,_,ArgVal2) :- is_symbolic_closure(ArgVal2).
1620 % ---
1621
1622 % check if we have a finite known set that can be reasonably represented
1623 % see small_known_set/1 is kernel_mappings
1624 finite_reasonably_sized_set(AVL) :- nonvar(AVL), AVL=avl_set(_). % already expanded; so it can be represented in memory
1625 finite_reasonably_sized_set(Closure) :- nonvar(Closure),
1626 custom_explicit_sets:is_interval_closure(Closure,From,To), integer(From), integer(To),
1627 1+To-From < 250000. % what value should we use here?
1628
1629 lazy_compute_expression(TRIGGER,AssignmentExpr,LocalState,State,IdValue,WF,Ai) :-
1630 get_enumeration_finished_wait_flag(WF,F),
1631 block_lazy_compute_expression(TRIGGER,F,AssignmentExpr,LocalState,State,IdValue,WF,Ai).
1632
1633 :- block block_lazy_compute_expression(-,-,?,?,?, ?,?,?).
1634 block_lazy_compute_expression(TRIGGER,_F,_AssignmentExpr,_LocalState,_State,_IdValue,_WF,_Ai) :-
1635 var(TRIGGER),!.
1636 block_lazy_compute_expression(pred_true,_,AssignmentExpr,LocalState,State,IdValue,WF,Ai) :-
1637 AssignmentExpr = b(Expr,Type,Infos),
1638 (Type \== pred -> b_compute_expression2(Expr,Type,Infos,LocalState,State,IdValue,WF)
1639 ; IdValue == pred_true -> b_test_boolean_expression2(Expr,Infos,LocalState,State,WF,Ai,_)
1640 ; IdValue == pred_false -> b_not_test_boolean_expression2(Expr,Infos,LocalState,State,WF,Ai,_)
1641 ; b_check_boolean_expression(AssignmentExpr,LocalState,State,WF,PredVal,Ai,_) -> IdValue = PredVal
1642 ; % reification of check_boolean_expression failed:
1643 b_try_check_failed(AssignmentExpr,LocalState,State,'$ENUMERATION',WF,IdValue,'$GENERATE_ON_DEMAND')
1644 ).
1645 block_lazy_compute_expression(pred_false,_,_AssignmentExpr,_LocalState,_State,[],_WF,_Ai). % maybe generate any value ??
1646
1647 % ---
1648
1649 :- block add_wd_error_if_false(-,?,?,?,?).
1650 add_wd_error_if_false(pred_true,_,_,_,_).
1651 add_wd_error_if_false(pred_false,ErrMsg,Cond,Span,WF) :-
1652 translate_bexpression_with_limit(Cond,100,CS),
1653 %(Span=span_predicate(P,LS,State) -> tcltk_interface:write_dot_file_for_pred_expr_and_state(P, LS, State,'/tmp/prob_wd_error.dot') ; true),
1654 add_wd_error_span(ErrMsg,CS,Span,WF).
1655
1656 % ---
1657
1658
1659 :- use_module(kernel_tools,[ground_value/1]).
1660 % compute function application:
1661 b_compute_expression_function(Function,FunArg,Type,Info,LocalState,State,Res,WF) :-
1662 preferences:preference(find_abort_values,false), % the treatment below will not check, e.g., if the set extension is really a function
1663 is_extension_function(Function,FInfo,ExFun), !,
1664 /* a set extension applied to an argument: in some cases we can can first evaluate the argument,
1665 and then avoid having to compute the set_extension for all non-matching args */
1666 b_compute_expression(FunArg,LocalState,State,ArgValue,WF),
1667 % TO DO : should we only do this if ArgValue is known ?? otherwise the standard treatment is better ??
1668 % Note: b_compiler has a special rule to not remove this optimisation
1669 Span = span_predicate(b(function(Function,FunArg),Type,Info),LocalState,State),
1670 opt_push_wait_flag_call_stack_info(WF,function_call(Function,ArgValue,Info),WF2), % small performance hit; hence we only push onto call_stack in TRACE_INFO mode
1671 ((memberchk(contains_wd_condition,FInfo) ; % relevant for test 1302; but machine seems to contain real WD error
1672 preferences:preference(use_clpfd_solver,false) ;
1673 ground_value(ArgValue))
1674 -> b_apply_function_set_extension(ExFun,ArgValue,LocalState,State,Res,WF2,Span)
1675 ; /* the standard treatment can infer information about the result,... in clpfd_mode */
1676 b_compute_expression(Function,LocalState,State,FValue,WF),
1677 get_texpr_type(Function,FunctionType),
1678 kernel_call_apply_to(FValue,ArgValue,Res,FunctionType,Span,WF2)).
1679 %b_compute_expression_function(b(comprehension_set(Parameters,Condition),_,SInfo),Arg,Type,Info,LocalState,State,Value,WF) :- !,
1680 % b_compute_comprehension_set_symbolic(Parameters,Condition,SInfo,LocalState,State,FValue,WF),
1681 % b_compute_expression(Arg,LocalState,State,ArgValue,WF),
1682 % Span = span_predicate(b(function(Function,Arg),Type,Info),LocalState,State),
1683 % get_texpr_type(Function,FunctionType),
1684 % kernel_call_apply_to(FValue,ArgValue,Value,FunctionType,Span,WF).
1685 b_compute_expression_function(Function,FunArg,_Type,Info,LocalState,State,Value,WF) :-
1686 special_operator_for_image(Function,Kind,Args),!, % detect e.g. iterate(rel,k)(x)
1687 b_compute_expression(FunArg,LocalState,State,SV,WF),
1688 b_compute_expressions(Args,LocalState,State,EArgs,WF),
1689 kernel_call(bsets_clp:apply_fun_for_special_operator(Kind,EArgs,SV,Value,WF,Info),
1690 [SV|EArgs],WF,function(Function,FunArg)).
1691 b_compute_expression_function(Function,Arg,Type,Info,LocalState,State,Value,WF) :-
1692 opt_push_wait_flag_call_stack_info(WF,function_call(Function,ArgValue,Info),WF2),
1693 ? b_compute_expression(Function,LocalState,State,FValue,WF2),
1694 ? b_compute_expression(Arg,LocalState,State,ArgValue,WF2),
1695 Span = span_predicate(b(function(Function,Arg),Type,Info),LocalState,State),
1696 get_texpr_type(Function,FunctionType),
1697 % TODO: do we still need the span predicate when we have the function_call call_stack infos?
1698 ? kernel_call_apply_to(FValue,ArgValue,Value,FunctionType,Span,WF2).
1699
1700
1701 :- use_module(bsyntaxtree,[get_set_type/2,is_set_type/2]).
1702 :- use_module(kernel_cardinality_attr,[finite_cardinality_as_int_with_type_wf/5]).
1703 b_compute_card(Arg1,Type,Info,OuterInfo,LocalState,State,Card,WF) :-
1704 ? b_compute_card2(Arg1,Type,Info,OuterInfo,LocalState,State,Card,WF),
1705 % maybe we should move this code below inside kernel_objects ??
1706 (ground(Card) -> true
1707 ; get_set_type(Type,SetElType), % TO DO: only needed for cardinality_of_set_extension_list
1708 ? kernel_objects:max_cardinality(SetElType,MaxCard), % this could be precomputed statically
1709 (number(MaxCard) -> kernel_objects:in_nat_range(Card,int(0),int(MaxCard))
1710 ; kernel_objects:greater_than_equal(Card,int(0)) % not sure this is required
1711 )
1712 ).
1713 b_compute_card2(set_extension(Ex),_,_,_,LocalState,State,Card,WF) :- !,
1714 b_compute_expressions(Ex,LocalState,State,ExValue,WF),
1715 kernel_objects:cardinality_of_set_extension_list(ExValue,Card,WF).
1716 b_compute_card2(range(F),_,_,_,LocalState,State,Card,WF) :- !,
1717 b_compute_expression(F,LocalState,State,SV1,WF),
1718 kernel_objects:cardinality_of_range(SV1,Card,WF).
1719 b_compute_card2(comprehension_set(Parameters,Condition),Type,Info,OuterInfo,LocalState,State,Card,WF) :- !,
1720 get_set_type(Type,SetElType),
1721 % ensure that we keep the closure and don't expand it:
1722 ? b_compute_comprehension_set_symbolic(Parameters,Condition,Info,LocalState,State,SV1,WF),
1723 ? kernel_mappings:must_succ_kernel_call(
1724 kernel_cardinality_attr:finite_cardinality_as_int_with_type_wf(SV1,SetElType,OuterInfo,Card,WF),SV1,WF,card).
1725 % TO DO: treat comprehension set + things like card({x|x>1 & x<2**e & x mod 2 = 0}) = 0
1726 b_compute_card2(Arg1,Type,Info,OuterInfo,LocalState,State,Card,WF) :-
1727 get_set_type(Type,SetElType),
1728 b_compute_expression2(Arg1,Type,Info,LocalState,State,SV1,WF),
1729 ? kernel_mappings:must_succ_kernel_call(
1730 kernel_cardinality_attr:finite_cardinality_as_int_with_type_wf(SV1,SetElType,OuterInfo,Card,WF),SV1,WF,card).
1731
1732 b_compute_max(set_extension(Ex),_,Info,LocalState,State,Max,WF) :- !,
1733 b_compute_expressions(Ex,LocalState,State,ExValue,WF),
1734 kernel_objects:maximum_of_set_extension_list(ExValue,Max,Info,WF).
1735 b_compute_max(Arg1,Type,Info,LocalState,State,Max,WF) :-
1736 b_compute_expression2(Arg1,Type,Info,LocalState,State,SV1,WF),
1737 kernel_mappings:must_succ_kernel_call(kernel_objects:maximum_of_set(SV1,Max,Info,WF),SV1,WF,max).
1738 b_compute_min(set_extension(Ex),_,Info,LocalState,State,Min,WF) :- !,
1739 b_compute_expressions(Ex,LocalState,State,ExValue,WF),
1740 kernel_objects:minimum_of_set_extension_list(ExValue,Min,Info,WF).
1741 /* doesnot really buy a lot: */
1742 /*b_compute_min(union(Arg1,Arg2),_,Info,LocalState,State,Min,WF) :-
1743 Arg1 = b(set_extension(Ex),Type1,Info1),
1744 !,
1745 b_compute_min(set_extension(Ex),Type1,Info1,LocalState,State,Min1,WF),
1746 b_compute_expression(Arg2,LocalState,State,SV2,WF),
1747 b_compute_min2(SV2,Min1,Min,Info,WF).
1748 :- block b_compute_min2(-,?,?,?,?).
1749 b_compute_min2([],Min1,Res,_,_WF) :- !, Res=Min1.
1750 b_compute_min2(SV1,Min1,Res,Info,WF) :-
1751 kernel_mappings:must_succ_kernel_call(kernel_objects:minimum_of_set(SV1,Min2,Info,WF),SV1,WF,min),
1752 min(Min1,Min2,Res).
1753 min(int(A),int(B),int(Res)) :- kernel_objects:minimum(A,B,Res). */
1754 b_compute_min(Arg1,Type,Info,LocalState,State,Min,WF) :-
1755 b_compute_expression2(Arg1,Type,Info,LocalState,State,SV1,WF),
1756 kernel_mappings:must_succ_kernel_call(kernel_objects:minimum_of_set(SV1,Min,Info,WF),SV1,WF,min).
1757
1758 generate_recursive_closure(TRecId,RecValue,Parameters,Condition,LocalState,State,Result,WF) :-
1759 get_texpr_id(TRecId,RecId),
1760 add_var_to_localstate(RecId,RecValue,LocalState,State1),
1761 debug_println(9,generating_recursive_closure(RecId,Parameters)),
1762 b_generate_rec_closure_aux(RecId,Parameters,Condition,State1,State,RClosure1,WF),
1763 mark_closure_as_recursive(RClosure1,RClosure2),
1764 mark_closure(RClosure2,[recursive(TRecId)],Result),
1765 ( debug_mode(off) -> true
1766 ; ground_value(Result) -> true
1767 ; term_variables(Result,TV),
1768 add_message(b_interpreter,'non-ground closure generated: ',TV:Result,Condition)
1769 ).
1770 % a variation of b_generate_closure
1771 b_generate_rec_closure_aux(RecId,Parameters,Condition,LocalState,State,Result,WF) :-
1772 split_names_and_types(Parameters,Names,Types),
1773 construct_closure(Names,Types,ClosurePred,Result),
1774 % now add RecId to parameters to prevent looking up recursive calls
1775 b_compiler:b_compile(Condition,[RecId|Names],LocalState,State,ClosurePred,WF).
1776
1777 % check if a freetype value has the expected case, if not
1778 % generate a WD-error
1779 check_freetype_case(Id,Case,VCase,Inner,Value,Info,WF) :-
1780 get_enumeration_finished_wait_flag(WF,F),
1781 check_freetype_case2(Id,Case,VCase,Inner,Value,Info,F,WF).
1782 :- block check_freetype_case2(?,?,-,?,?,?,-,?).
1783 check_freetype_case2(Id,Case,VCase,Inner,Value,Info,_F,WF) :-
1784 ( nonvar(VCase) ->
1785 ( Case=VCase -> equal_object_wf(Inner,Value,check_freetype_case2,WF)
1786 ;
1787 ajoin(['cannot apply destructor for data type ',Id,
1788 ', expected constructor ',Case,', but got: '],Msg),
1789 add_wd_error_set_result(Msg,VCase,Inner,Value,Info,WF))
1790 ; % the computation has finished without value,
1791 true). % just drop the check
1792
1793 % check if we have a set_extension argument representing an explicit function
1794 % {a |-> f1, b |-> f2, ...} or [f1,f2]
1795 is_extension_function(b(A,_,Info),Info,C) :- is_extension_function_aux(A,C).
1796 is_extension_function_aux(set_extension(Ex),CaseList) :- is_set_extension_function(Ex,CaseList).
1797 is_extension_function_aux(sequence_extension(Ex),CaseList) :- is_sequence_extension_function(Ex,1,CaseList).
1798 is_set_extension_function([],[]).
1799 is_set_extension_function([b(Couple,TC,_)|T],[case(A,B)|ST]) :- is_couple(Couple,TC,A,B),
1800 is_set_extension_function(T,ST).
1801 is_sequence_extension_function([],_,[]).
1802 is_sequence_extension_function([B|T],Nr,[case(b(value(int(Nr)),integer,[]),B)|ST]) :- N1 is Nr+1,
1803 is_sequence_extension_function(T,N1,ST).
1804
1805 is_couple(couple(A,B),_,A,B).
1806 is_couple(value((VA,VB)),couple(TA,TB), b(value(VA),TA,[]), b(value(VB),TB,[])).
1807
1808 :- use_module(kernel_equality,[equality_objects_wf/4]).
1809 b_apply_function_set_extension([],FunArgVal,_LocalState,_State,_Res,WF,Span) :-
1810 add_wd_error_span('Function applied outside of domain (#8): ','@fun'(FunArgVal,[]),Span,WF).
1811 b_apply_function_set_extension([case(A,B)|T],FunArgVal,LocalState,State,Res,WF,Span) :-
1812 b_compute_expression(A,LocalState,State,AVal,WF),
1813 equality_objects_wf(AVal,FunArgVal,EqRes,WF),
1814 % TO DO: if Res is known, we can call equality_objects(BVal,Res,ResEqRes)
1815 ? b_apply_function_set_extension_aux(EqRes,B,T,FunArgVal,LocalState,State,Res,WF,Span).
1816
1817 :- block b_apply_function_set_extension_aux(-,?,?,?, ?,?,?,?,?).
1818 b_apply_function_set_extension_aux(pred_true,B,_T,_FunArgVal,LocalState,State,Res,WF,_Span) :-
1819 b_compute_expression(B,LocalState,State,BVal,WF), %print(value(BVal)),nl,
1820 ? equal_object_wf(BVal,Res,b_apply_function_set_extension_aux,WF).
1821 b_apply_function_set_extension_aux(pred_false,_B,T,FunArgVal,LocalState,State,Res,WF,Span) :-
1822 ? b_apply_function_set_extension(T,FunArgVal,LocalState,State,Res,WF,Span).
1823
1824
1825 % --------------------- SIGMA & PI ------------------------
1826 :- use_module(bsyntaxtree,[is_membership_or_equality/3,same_id/3]).
1827 /* first clause: try to do a specific treatment for formulas of the form SIGMA(ID).(ID:SET|EXPR) */
1828 /* Advantage: will not delay as long before computing comprehension_set SET ; see test 1312 */
1829 b_general_sum_or_mul([TID],Condition,Expression,Type,_Info,LocalState,State,SumResult,WF,SUMorMUL) :-
1830 is_membership_or_equality(Condition,MID,SET),
1831 same_id(TID,MID,_),!,
1832 b_compute_expression(SET,LocalState,State,SETResult,WF),
1833 b_general_sum_or_mul_over_set([TID],SETResult,Expression,Type,LocalState,State,SumResult,WF,SUMorMUL).
1834 b_general_sum_or_mul(Ids,Condition,Expression,Type,Info,LocalState,State,SumMulResult,WF,SUMorMUL) :-
1835 b_compute_comprehension_set(Ids,Condition,Info,LocalState,State,SETResult,WF),
1836 (var(SETResult) -> perfmessagecall(sigma_pi_not_expanded_or_reified(SUMorMUL),
1837 translate:print_bexpr(Condition),Condition) ; true),
1838 b_general_sum_or_mul_over_set(Ids,SETResult,Expression,Type,LocalState,State,SumMulResult,WF,SUMorMUL).
1839
1840
1841 :- block b_general_sum_or_mul_over_set(?,-, ?,?,?,?, ?,?,?).
1842 b_general_sum_or_mul_over_set([TID],SETResult,Expression,Type,_LS,_S,SumResult,WF,SUMorMUL) :-
1843 Type=integer, % TO DO: also for real
1844 get_texpr_id(Expression,ID), % check if we just sum the elements of the list SIGMA(x).(x:S|x)
1845 get_texpr_id(TID,ID),
1846 ? sum_or_mul_of_explicit_set(SETResult,SUMorMUL,R),!,
1847 equal_object_wf(SumResult,R,b_general_sum_or_mul_over_set,WF).
1848 b_general_sum_or_mul_over_set(IDs,SETResult,Expression,Type,LocalState,State,SumResult,WF,SUMorMUL) :-
1849 expand_custom_set_to_list_wf(SETResult,ESETResult,_Done,b_general_sum_or_mul_over_set,WF),
1850 ? b_sum_or_mul_over_list(ESETResult,IDs,Expression,Type,LocalState,State,SumResult,WF,SUMorMUL).
1851
1852 b_sum_or_mul_over_list(L,IDs,Expr,Type,LS,State,Result,WF,SUMorMUL) :-
1853 get_acc_base(SUMorMUL,Type,Acc),
1854 (Type = integer -> get_wait_flag0(WF,WF0) ; true), % for real: delay until values known
1855 ? b_sum_or_mul_over_list_acc(L,IDs,Expr,Type,LS,State,Acc,Result,WF,SUMorMUL,WF0).
1856
1857 :- block b_sum_or_mul_over_list_acc(-, ?, ?,?,?,?,?, ?,?,?,?).
1858 % better if list is fully known: no constraint propagation performed during computation !
1859 % for example: SIGMA(x).(x:{-1} \/ 1..30000|x+1) goes down from 2050 ms to 1210 ms
1860 b_sum_or_mul_over_list_acc([],_,_,Type,_,_,Acc,Result,_WF,_SUMorMUL,_) :-
1861 ? get_acc_result(Type,Acc,Result).
1862 b_sum_or_mul_over_list_acc([H|T],IDs,Expr,Type,LocalState,State,Acc,Result,WF,SUMorMUL,WF0) :-
1863 add_typed_vars_to_localstate(IDs,H,LocalState,NewLocalState),
1864 b_compute_expression(Expr,NewLocalState,State,HExprVal,WF),
1865 b_sum_or_mul_over_list_acc2(HExprVal,T,IDs,Expr,Type,LocalState,State,Acc,Result,WF,SUMorMUL,WF0).
1866
1867 :- block b_sum_or_mul_over_list_acc2(?,-, ?, ?,?,?,?,?, ?,?,?,?),
1868 b_sum_or_mul_over_list_acc2(?,?, ?, ?,?,?,?,-, ?,?,?,-),
1869 b_sum_or_mul_over_list_acc2(-,?, ?, ?,?,?,?,?, ?,?,?,-). % wait until T nonvar and either Acc & HExprVal known or WF0 set
1870 % purpose: try and remain in non-CLPFD mode as long as possible to avoid overflows,... (see eg. test 1642, 1708)
1871 b_sum_or_mul_over_list_acc2(HExprVal,T,IDs,Expr,Type,LocalState,State,Acc, Result,WF,SUMorMUL,WF0) :-
1872 (nonvar(T),nonvar(Acc),ground(HExprVal)
1873 -> % we can continue computing the system without constraint propagation; is faster
1874 get_value(Type,HExprVal,HVal),
1875 compose_acc(SUMorMUL,Acc,HVal,NewAcc),
1876 b_sum_or_mul_over_list_acc(T,IDs,Expr,Type,LocalState,State,NewAcc,Result,WF,SUMorMUL,WF0)
1877 ; T==[], number(Acc), get_acc_base(SUMorMUL,Type,Acc) ->
1878 /* we have just a single element left and no operator has to be applied -> no need for clpfd treatment */
1879 equal_object_wf(HExprVal,Result,b_sum_or_mul_over_list_acc)
1880 ; Type=real -> % no CLP(FD) treatment possible yet
1881 when(ground(HExprVal),
1882 b_sum_or_mul_over_list_acc2(HExprVal,T,IDs,Expr,Type,LocalState,State,Acc, Result,WF,SUMorMUL,WF0))
1883 ; init_clp_acc(SUMorMUL,HExprVal,int(Acc),CLPAccumulator),
1884 b_sum_or_mul_over_list_clp(T,IDs,Expr,LocalState,State,CLPAccumulator,Result,WF,SUMorMUL)
1885 ).
1886
1887 % add set comprehension solution ValueForTypedIDs as individual values for every TypedIDs to LocalState
1888 add_typed_vars_to_localstate(TypedIDs,ValueForTypedIDs,LocalState,NewLocalState) :-
1889 (flatten_pairs(TypedIDs,ValueForTypedIDs,ValAsList),
1890 add_typed_vars_to_localstate_aux(TypedIDs,ValAsList,LocalState,R)
1891 -> NewLocalState = R
1892 ; add_internal_error('Call failed: ',add_typed_vars_to_localstate(TypedIDs,ValueForTypedIDs,LocalState,NewLocalState)),
1893 fail
1894 ).
1895 % set comprehension results for {a,b,c|P} are nested like this ((a,b),c)
1896 % first argument only used for length (to know how deep the pairs are nested)
1897 flatten_pairs(L,Pairs,FlatList) :- flatten_pairs(L,Pairs,FlatList,[]).
1898 flatten_pairs([_],A) --> !, [A].
1899 flatten_pairs([_|T],(A,B)) --> flatten_pairs(T,A) ,[B].
1900 add_typed_vars_to_localstate_aux([],_,LS,LS).
1901 add_typed_vars_to_localstate_aux([TID],[H],LocalState,NewLocalState) :- !,
1902 get_texpr_id(TID,ID), get_texpr_type(TID,TYPE),
1903 add_typed_var_to_localstate(ID,H,TYPE,LocalState,NewLocalState).
1904 add_typed_vars_to_localstate_aux([TID1|Ids],[H1|Hs],LocalState,NewLocalState) :- !,
1905 get_texpr_id(TID1,ID1), get_texpr_type(TID1,TYPE),
1906 add_typed_var_to_localstate(ID1,H1,TYPE,LocalState,LS1),
1907 add_typed_vars_to_localstate_aux(Ids,Hs,LS1,NewLocalState).
1908
1909
1910 :- block b_sum_or_mul_over_list_clp(-, ?, ?,?,?, ?, ?,?,?).
1911 b_sum_or_mul_over_list_clp([],_, _,_,_, Acc, Result,_WF,SUMorMUL) :-
1912 finalise_clp(SUMorMUL,Acc,Result).
1913 b_sum_or_mul_over_list_clp([H|T],IDs,Expr,LocalState,State,Acc, Result,WF,SUMorMUL) :-
1914 add_typed_vars_to_localstate(IDs,H,LocalState,NewLocalState),
1915 b_compute_expression(Expr,NewLocalState,State,HExprVal,WF),
1916 compose_clp(SUMorMUL,HExprVal,Acc,NewAcc),
1917 b_sum_or_mul_over_list_clp(T,IDs,Expr,LocalState,State,NewAcc,Result,WF,SUMorMUL).
1918
1919 :- use_module(kernel_reals,[is_real/2]).
1920 get_acc_base(sum,integer,R) :- !, R=0.
1921 get_acc_base(sum,real,0.0).
1922 get_acc_base(mul,integer,R) :- !, R=1.
1923 get_acc_base(mul,real,1.0).
1924 get_acc_result(integer,Nr,int(Nr)).
1925 get_acc_result(real,Nr,Real) :- is_real(Real,Nr).
1926 get_value(integer,int(Val),Val) :- !.
1927 get_value(real,Real,Nr) :- is_real(Real,Nr).
1928
1929 compose_acc(sum,A,B,C) :- C is A+B.
1930 compose_acc(mul,A,B,C) :- C is A*B.
1931 init_clp_acc(sum,int(A),int(B),Res) :- (B==0 -> Res=[A] ; Res=[A,B]). % A always not ground
1932 init_clp_acc(mul,A,B,C) :- times(A,B,C).
1933 compose_clp(sum,int(A),Acc,NewAcc) :- NewAcc = [A|Acc].
1934 compose_clp(mul,A,B,C) :- times(A,B,C).
1935 :- use_module(clpfd_interface,[clpfd_sum/2]).
1936 finalise_clp(sum,Acc,int(Result)) :-
1937 clpfd_sum(Acc,Result). % using clpfd_sum can be much more efficient: no intermediate variables set up
1938 finalise_clp(mul,int(Acc),int(Acc)).
1939
1940 /* for if-then-else in Z: compute Then or Else,
1941 depending on the outcome of the predicate */
1942 :- block b_compute_if_then_else(-,?,?,?,?,?,?).
1943 b_compute_if_then_else(pred_true,Then,_Else,LocalState,State,Value,WF) :-
1944 ? b_compute_expression(Then,LocalState,State,Value,WF).
1945 b_compute_if_then_else(pred_false,_Then,Else,LocalState,State,Value,WF) :-
1946 ? b_compute_expression(Else,LocalState,State,Value,WF).
1947
1948 :- use_module(clpfd_interface,[clpfd_if_then_else/4]).
1949 % a more sophisticated treatment, can also work backwards forcing PredRes
1950 % examples:
1951 % x = IF a<10 THEN 0 ELSE 5 END & x:6..10 & a:1..23
1952 % see must_fail_clpfd_det 132 and 133
1953 % problematic if Else contains recursion; but then we should have WD condition
1954 b_clpfd_if_then_else(PredRes,Type,Then,Else,LocalState,State,Value,WF) :-
1955 get_wait_flag0(WF,WF0),
1956 b_clpfd_if_then_else_block(PredRes,WF0,Type,Then,Else,LocalState,State,Value,WF).
1957 :- block b_clpfd_if_then_else_block(-,-,?,?,?,?,?,?,?).
1958 b_clpfd_if_then_else_block(PredRes,_,Type,Then,Else,LocalState,State,Value,WF) :- var(PredRes),!,
1959 get_full_fd_value(Type,Value,FDValue),
1960 b_compute_expression(Then,LocalState,State,ThenValue,WF),
1961 get_full_fd_value(Type,ThenValue,FDThenValue),
1962 b_compute_expression(Else,LocalState,State,ElseValue,WF),
1963 get_full_fd_value(Type,ElseValue,FDElseValue),
1964 % TO DO: catch CLPFD overflow and use equality_objects
1965 clpfd_if_then_else(PredRes,FDThenValue,FDElseValue,FDValue).
1966 b_clpfd_if_then_else_block(pred_true,_,_Type,Then,_Else,LocalState,State,Value,WF) :-
1967 b_compute_expression(Then,LocalState,State,Value,WF).
1968 b_clpfd_if_then_else_block(pred_false,_,_Type,_Then,Else,LocalState,State,Value,WF) :-
1969 b_compute_expression(Else,LocalState,State,Value,WF).
1970
1971 :- use_module(b_global_sets,[get_global_type_value/3]).
1972 % try and get full_fd_value; true if full value can be translated to CLP(FD) value
1973 get_full_fd_value(global(T),FY,X) :- get_global_type_value(FY,T,X).
1974 get_full_fd_value(integer,int(X),X).
1975 get_full_fd_value(boolean,B,FD) :- kernel_equality:prop_eq_01(B,FD).
1976 % record with single field ?
1977
1978 can_get_full_fd_value(global(_)).
1979 can_get_full_fd_value(integer).
1980 can_get_full_fd_value(boolean).
1981
1982 % a slightly improved version over set_up_localstate (not sure it is really much faster):
1983 add_lazy_let_id_to_local_state(b(identifier(ID),_,_),Trigger,IdValue,LocalState,NewState) :-
1984 % should we delete any old occurence of ID in LocalState?
1985 NewState = [bind(ID,(Trigger,IdValue))|LocalState].
1986
1987 add_lazy_let_id_and_expression(Id,IdExpr,LocalState,InState,NewLocalState,WF) :-
1988 empty_avl(Ai),
1989 add_lazy_let_id_and_expression(Id,IdExpr,LocalState,InState,NewLocalState,WF,Ai).
1990 add_lazy_let_id_and_expression(Id,IdExpr,LocalState,InState,NewLocalState,WF,Ai) :-
1991 add_lazy_let_id_to_local_state(Id,Trigger,IdValue,LocalState,NewLocalState),
1992 lazy_compute_expression(Trigger,IdExpr,LocalState,InState,IdValue,WF,Ai).
1993
1994 /* for let-statements in Z and now in B: expand localstate by new variables and assign
1995 values to them ;
1996 now Expressions are evaluated in state *with* the new identifiers !
1997 */
1998 %set_up_localstate_for_let_no_reuse(Ids,Exprs,LocalState,State,LetState,WF) :-
1999 % set_up_localstate(Ids,Vars,LocalState,LetState),
2000 % compute_let_expressions(Exprs,Vars,LocalState,State,WF).
2001 set_up_localstate_for_let(Ids,Vars,Exprs,LocalState,State,LetState,WF) :-
2002 set_up_localstate(Ids,Vars,LocalState,LetState),
2003 %external_functions:observe_variables(Ids,Vars),
2004 ? compute_let_expressions(Exprs,Vars,LetState,State,WF).
2005 compute_let_expressions([],[],_,_,_).
2006 compute_let_expressions([Expr|RestExprs],[Var|RestVars],LocalState,State,WF) :-
2007 ? b_compute_expression(Expr,LocalState,State,Value,WF),
2008 equal_object_optimized(Var,Value,compute_let_expressions),
2009 ? compute_let_expressions(RestExprs,RestVars,LocalState,State,WF).
2010
2011 set_up_localstate_for_global_let(Ids,Exprs,LocalState,State,LetState,WF) :-
2012 set_up_localstate(Ids,Vars,State,LetState),
2013 compute_let_expressions(Exprs,Vars,LocalState,LetState,WF).
2014
2015
2016 l_compute_field([],_LS,_S,[],_WF).
2017 l_compute_field([Field|T],LS,S,[FVal|CT],WF) :-
2018 ? b_compute_field(Field,LS,S,FVal,WF),
2019 ? l_compute_field(T,LS,S,CT,WF).
2020
2021 b_compute_field(field(Name,TypeOrVal),LocalState,State,field(Name,TypeOrFieldValue),WF) :-
2022 ? b_compute_expression(TypeOrVal,LocalState,State,TypeOrFieldValue,WF).
2023
2024
2025
2026 :- use_module(b_compiler).
2027
2028 /* :- type bsets_closure +--> closure(list(type(variable_id)),
2029 list(type(basic_type_descriptor)),type(boolean_expression)). */
2030
2031 :- assert_pre(b_interpreter:b_compute_comprehension_set(Parameters,Cond,_Info,LS,State,_R,_WF),
2032 (ground_check(Parameters),
2033 bsyntaxtree:check_if_typed_predicate(Cond),type_check(LS,store),type_check(State,store)) ).
2034
2035 :- assert_post(b_interpreter:b_compute_comprehension_set(_P,_C,_Info,_LS,_State,Val,_WF),
2036 (b_interpreter:value_type(Val))). %, nonvar(Val)
2037
2038
2039
2040 b_compute_comprehension_set_symbolic(Parameters,Condition,_Info,LocalState,State,Result,WF) :-
2041 % a version which never expands the generated closure
2042 ? b_generate_closure_if_necessary(Parameters,Condition,LocalState,State,CResult,WF),
2043 Result=CResult.
2044 % we could catch Parameters = [TID], Condition = b(member(b(identifier(ID),_TYPE,_),SET)
2045 b_compute_comprehension_set(Parameters,Condition,Info,LocalState,State,Result,WF) :-
2046 ? b_generate_closure_if_necessary(Parameters,Condition,LocalState,State,CResult,WF),
2047 b_compute_comprehension_set_aux(CResult,Info,Result,WF).
2048
2049 :- use_module(clpfd_interface,[catch_clpfd_overflow_call2/2]).
2050 b_compute_comprehension_set_aux(CResult,_,Result,_WF) :-
2051 (var(CResult) ; \+ functor(CResult,closure,3) ),!,
2052 Result=CResult.
2053 b_compute_comprehension_set_aux(CResult,Info,Result,_WF) :-
2054 ? member(prob_annotation('SYMBOLIC'),Info),!,
2055 mark_closure_as_symbolic(CResult,CRS),Result=CRS.
2056 b_compute_comprehension_set_aux(CResult,_Info,Result,_WF) :-
2057 (preferences:get_preference(convert_comprehension_sets_into_closures,true),
2058 \+ definitely_expand_this_explicit_set(CResult)
2059 ;
2060 dont_expand_symbolic_explicit_set(CResult)),!,
2061 Result=CResult.
2062 b_compute_comprehension_set_aux(CResult,Info,Result,WF) :-
2063 b_expand_compute_comprehension_set(CResult,Info,Result,WF).
2064
2065 b_expand_compute_comprehension_set(CResult,Info,Result,WF) :-
2066 % using just get_wait_flag1(b_compute_comprehension_set,WF,WF0), makes many benchmarks faster ; but e.g., test 268 fails; maybe we sholud pre-compute bexpr_variables ? and pass this to expand_only_custom_closure_global
2067 (preferences:preference(use_smt_mode,false)
2068 -> get_wait_flag(1000,b_compute_comprehension_set,WF,WF0) % ideally we should say WF0 = _ ; but for some benchmarks Rule_DB_SIGAREA_0024_ori.mch this is important to avoid expanding closures before other stuff fails
2069 % only in SMT mode can there be any benefit in expanding a non-ground closure (when it is a lambda closure)
2070 % => hence delay expansion longer, possibly detecting enumeration warnings while expanding
2071 % TO DO: for lambda closures with known domain: expand earlier !
2072 ; get_wait_flag(2,b_compute_comprehension_set,WF,WF0)),
2073 kernel_objects:mark_as_to_be_computed(Result), % avoid that we instantiate this set (e.g., in check_element_of_wf: we will get a full description of the set later; see test 1353
2074 (var(WF0),var(Result) -> ground_value_check(CResult,CGr) ; true),
2075 block_compute_comprehension_set_aux(CResult,Info,Result,WF,WF0,CGr).
2076
2077 :- block block_compute_comprehension_set_aux(?,?,-,?,-,-).
2078 block_compute_comprehension_set_aux(CResult,Info,Result,WF,_WF0,_CGr) :-
2079 (
2080 nonvar(Result)
2081 ? -> equal_object_wf(CResult,Result,WF) % this may expand CResult or do other tests;
2082 % like emptyness test or symbolic equality;
2083 % if Result=[_|_] then the closure needs to be expanded anyhow, so need to try and keep symbolic
2084 ;
2085 ? catch_clpfd_overflow_call2(
2086 on_enumeration_warning_with_continue(expand_only_custom_closure_global(CResult,Expansion,check_no_inf,WF),
2087 % check_no_inf: we know it is not definitely infinite; and we do not want warnings for virtual time-outs
2088 % an enumeration warning occured in the expansion scope: keep closure symbolic after all
2089 % NOTE: for this detection to work it is better to delay until the body is ground (CGr)
2090 % and not use a priority too low for WF0, otherwise Expansion will be var and enum warning may occur later
2091 b_compute_comprehension_set_sym_msg(CResult,Info,Result,WF) % Backup Call in case of enum warning
2092 ,
2093 equal_object_wf(Result,Expansion,WF) % TrueContinuation
2094 % instantiating Result can trigger other code which fails and confuses on_enumeration_warning
2095 ),
2096 b_compute_comprehension_set_sym(CResult,Result,WF)
2097 ) % catch_clpfd_overflow_call2
2098 ).
2099
2100 b_compute_comprehension_set_sym_msg(CResult,Info,Result,WF) :- CResult = closure(P,_T,B),
2101 silent_mode(off),
2102 % TO DO: should we check that this closure has not been constructed by ProB, e.g., for UNION ??
2103 % e.g., P = ['__RANGE_LAMBDA__'] what about '_zzzz_unary', '_zzzz_binary', '_prj_arg1__', ...
2104 % also: what if the enumeration warning has a pending_abort_error
2105 !,
2106 Msg = 'Keeping comprehension-set symbolic (you may want to use the /*@symbolic*/ pragma to prevent this message, unless it was due to a WD-Error), identifiers: ',
2107 (contains_info_pos(Info) -> Span=Info ; Span=B),
2108 add_message(b_compute_comprehension_set,Msg,P,Span),
2109 b_compute_comprehension_set_sym(CResult,Result,WF).
2110 b_compute_comprehension_set_sym_msg(CResult,_,Result,WF) :-
2111 b_compute_comprehension_set_sym(CResult,Result,WF).
2112
2113
2114 b_compute_comprehension_set_sym(CResult,Result,WF) :-
2115 mark_closure_as_symbolic(CResult,CRS), % prevent doing the same mistake again
2116 equal_object_wf(Result,CRS,b_compute_comprehension_set_sym,WF).
2117
2118
2119 :- use_module(closures,[construct_closure_if_necessary/4]).
2120 b_generate_forall_closure(Parameters,Condition,LocalState,State,Result,WF) :-
2121 split_names_and_types(Parameters,Names,Types),
2122 construct_closure(Names,Types,ClosurePred1,Result),
2123 (LocalState==[],State==[]
2124 -> ClosurePred = Condition % no lookups can be performed anyway; no need to compile
2125 ; b_compiler:b_compile(Condition,Names,LocalState,State,ClosurePred,WF) ),
2126 add_texpr_infos(ClosurePred,[quantifier_kind(forall)],ClosurePred1). % info for call_stack
2127
2128
2129
2130 b_generate_closure_if_necessary(Parameters,Condition,LocalState,State,Result,WF) :-
2131 split_names_and_types(Parameters,Names,Types),
2132 ? b_compiler:b_compile(Condition,Names,LocalState,State,ClosurePred,WF),
2133 %print('COMPILED: '),translate:print_bexpr(ClosurePred),nl,
2134 construct_closure_if_necessary(Names,Types,ClosurePred,Result).
2135
2136
2137 :- public convert_list_of_expressions_into_sequence/2.
2138 convert_list_of_expressions_into_sequence(List,SeqValue) :-
2139 convert_list_of_expressions_into_sequence(List,1,Seq),
2140 ? equal_object_optimized(Seq,SeqValue,convert_list_of_expressions_into_sequence).
2141
2142 convert_list_of_expressions_into_sequence([],_,[]).
2143 convert_list_of_expressions_into_sequence([H|T],Cur,[(int(Cur),H)|ConvT]) :-
2144 C1 is Cur+1,
2145 convert_list_of_expressions_into_sequence(T,C1,ConvT).
2146
2147 convert_list_of_expressions_into_set_wf(ListOfElements,Set,Type,WF) :-
2148 list_of_expressions_is_ground(ListOfElements,Ground,OrderedListOfElements),
2149 ? convert_list_of_expressions_into_set1(Ground,OrderedListOfElements,Set,Type,WF).
2150 convert_list_of_expressions_into_set1(true,ListOfElements,Set,_Type,WF) :- %var(Set),
2151 ? \+ (ListOfElements = [H|_], is_symbolic_closure(H)), % list contains symbolic closures, do not try to expand to avl
2152 % see should_be_converted_to_avl_from_lists ?
2153 !, construct_avl_from_lists_wf(ListOfElements,AVLSet,WF),
2154 ? equal_object_wf(AVLSet,Set,convert_list_of_expressions_into_set1,WF).
2155 convert_list_of_expressions_into_set1(_,Seq,Set,Type,WF) :-
2156 ? kernel_objects:max_cardinality(Type,TypeMaxCard),
2157 ? convert_list_of_expressions_into_set2(Seq,1,[],Set,TypeMaxCard,WF).
2158
2159 % TO DO: sort elements : ground elements first
2160 convert_list_of_expressions_into_set2([],_,Set,Res,_,WF) :-
2161 ? equal_object_wf(Set,Res,convert_list_of_expressions_into_set2,WF).
2162 convert_list_of_expressions_into_set2([H|T],MaxSze,SetSoFar,OutSet,TypeMaxCard,WF) :-
2163 %kernel_objects:basic_type_set(Type,IntSet,MaxSze),
2164 check_set_lists_bounded(IntSet,TypeMaxCard,MaxSze),
2165 % TO DO: optimize; avoid traversing or typing elements over and over again
2166 % maybe add a max. sze argument to add_element
2167 add_element_wf(H,SetSoFar,IntSet,WF), % print(add_el(H,SetSoFar,IntSet)),nl,
2168 % TO DO: check if H in OutSet and keep track of which elements have already been covered in OutSet
2169 %check_element_of_wf(H,OutSet,WF), makes tests 114, 115, 118-120, 1063 fail ! % we could also call lazy_try_check_element_of if this turns out to be too expensive
2170 kernel_objects:lazy_try_check_element_of(H,OutSet,WF),
2171 M1 is MaxSze+1,
2172 ? convert_list_of_expressions_into_set2(T,M1,IntSet,OutSet,TypeMaxCard,WF).
2173
2174
2175 :- use_module(inf_arith).
2176 % check that a set does not exceed a certain bound (to prevent infinite
2177 % or overeager enumeration of sets); Warning: will not check custom_explicit_set sizes
2178 check_set_lists_bounded(Set,TypeMaxCard,Bound) :-
2179 inf_arith:infmin(TypeMaxCard,Bound,Card),
2180 (Card=inf -> true
2181 ; Card<1 -> empty_set(Set)
2182 ; check_set_bounded_aux(Set,Card)).
2183
2184 :- block check_set_bounded_aux(-,?).
2185 check_set_bounded_aux(CustomSet,_) :- is_custom_explicit_set(CustomSet,check_set_bounded_aux),!.
2186 check_set_bounded_aux([],_).
2187 check_set_bounded_aux([_|T],Card) :-
2188 C1 is Card-1,
2189 (C1=0 -> empty_set(T) ; check_set_bounded_aux(T,C1)).
2190
2191
2192
2193 % check if the list can be converted into AVL form; if not: re-order list so that ground elements are present first
2194 list_of_expressions_is_ground([],true,[]).
2195 list_of_expressions_is_ground([E|T],Ground,ResList) :-
2196 (should_be_converted_to_avl(E) -> ResList=[E|RT], list_of_expressions_is_ground(T,Ground,RT)
2197 ; Ground=false,
2198 bring_ground_elements_forward(T,[E],ResList)
2199 ).
2200
2201 bring_ground_elements_forward([],Acc,Acc).
2202 bring_ground_elements_forward([H|T],Acc,Res) :-
2203 (should_be_converted_to_avl(H) -> Res=[H|RT], bring_ground_elements_forward(T,Acc,RT)
2204 ; bring_ground_elements_forward(T,[H|Acc],Res)).
2205
2206 % compute cardinality of a list of parameters, such as for forall
2207 parameter_list_cardinality([],1).
2208 parameter_list_cardinality([b(identifier(_),BasicType,_)|T],Res) :-
2209 ? parameter_list_cardinality(T,TCard),
2210 (TCard=inf -> Res=inf
2211 ? ; kernel_objects:max_cardinality(BasicType,Card),
2212 kernel_objects:safe_mul(Card,TCard,Res)
2213 ).
2214 % see also basic_type_list_cardinality, now moved to custom_explicit_sets
2215
2216 b_for_all(Parameters,Infos,LHS,RHS,LocalState,State,WF) :-
2217 get_wait_flag1(for_all(Parameters),WF,LWF), % hack: give total_function,... priority to set up domain/range
2218 ? b_for_all_aux(LWF,Parameters,Infos,LHS,RHS,LocalState,State,WF).
2219
2220 :- block b_for_all_aux(-,?,?,?,?,?,?,?).
2221 b_for_all_aux(_,Parameters,Infos,LHS,RHS,LocalState,State,WF) :-
2222 split_names_and_types(Parameters,Names,Types),
2223 ? b_compile(LHS,Names,LocalState,State,CLHS,WF),
2224 ? b_compile(RHS,Names,LocalState,State,CRHS,WF),
2225 ? b_for_all_aux2(Parameters,Names,Types,Infos,CLHS,CRHS,WF).
2226
2227 :- use_module(kernel_tools,[ground_bexpr/1, ground_bexpr_check/2]).
2228 b_for_all_aux2(_,_,_,_,LHS,RHS,_) :-
2229 (is_falsity(LHS) ; is_truth(RHS)),
2230 !. % quantifier always true
2231 b_for_all_aux2(Parameters,CParameters,CParameterTypes,Infos,LHS,RHS,WF) :-
2232 ground_bexpr(LHS),
2233 ? \+ obvious_enumeration(LHS,CParameters), % if we have an obvious (small) enumeration in the LHS it is often better simply to enumerate and check the RHS for every instance
2234 ground_bexpr(RHS), %print(not_exists_forall(Parameters,LHS,RHS)),nl,
2235 !,
2236 b_for_all_find_counter_example(Parameters,CParameters,CParameterTypes,Infos,LHS,RHS,WF).
2237 b_for_all_aux2(Parameters,CParameters,CParameterTypes,Infos,LHS,RHS,WF) :-
2238 ? parameter_list_cardinality(Parameters,ParCard),
2239 peel_implications(Parameters,ParCard,LHS,RHS, LHS2,RHS2),
2240 ? b_for_all_aux3(Parameters,ParCard,CParameters,CParameterTypes,Infos,LHS2,RHS2,WF).
2241
2242 b_for_all_aux3(Parameters,ParCard,CParameters,CParameterTypes,Infos,LHS,RHS,WF) :-
2243 %large_domain(Parameters,ParCard,LHS),
2244 is_infinite_or_very_large_explicit_set(closure(CParameters,CParameterTypes,LHS),10000000),
2245 % the domain is so large that we cannot possibly check all instances
2246 % in this case: we prefer to look for a counter example in the hope that the constraint solver can narrow down the search by combining LHS and not(RHS)
2247 !,
2248 perfmessage(forall,'Large forall domain: ',ParCard,Infos),
2249 ground_bexpr_check(LHS,LG),
2250 ground_bexpr_check(RHS,RG),
2251 when((nonvar(LG),nonvar(RG)),
2252 b_for_all_find_counter_example(Parameters,CParameters,CParameterTypes,Infos,LHS,RHS,WF)
2253 ).
2254 b_for_all_aux3(Parameters,ParCard,_CP,_,Infos,LHS,RHS,WF) :-
2255 if(expand_forall_quantifier(Parameters,LHS,RHS,Infos,WF,ReificationVariable),
2256 (
2257 perfmessage(good(forall),'Reified forall by expanding into conjunction: ',LHS),
2258 ReificationVariable=pred_true),
2259 ( % print(normal_forall(Parameters)),nl,
2260 b_generate_for_all_list_domain1(Parameters,ParCard,LHS,RHS,[],[],AllSolList,NewRHS,WF),
2261 ? expand_forall1(AllSolList,NewRHS,Parameters,WF)
2262 )).
2263
2264
2265 % a treatment of for all where we look for counter examples satisfying LHS & not(RHS)
2266 b_for_all_find_counter_example(Parameters,CParameters,CParameterTypes,Infos,LHS,RHS,WF) :-
2267 % if LHS is Parameters: avl_set(V) then we probably should not apply this rule ?
2268 create_negation(RHS,NegRHS),
2269 conjunct_predicates_with_pos_info(LHS,NegRHS,Pred0),
2270 % format('looking for: ~w ',[CParameters]), translate:print_bexpr(LHS),nl, translate:print_bexpr(NegRHS),nl,
2271 perfmessage(good(forall),translating_forall_into_not_exists(CParameters),LHS),
2272 add_texpr_infos(Pred0,[quantifier_kind(forall)],ClosureBody1), % for call_stack
2273 init_quantifier_wait_flag(WF,not(forall),Parameters,ParValues,Infos,LocalWF), % relevant for test 1904
2274 not_with_enum_warning_and_possible_delay(
2275 (custom_explicit_sets:b_test_closure(CParameters,CParameterTypes,ClosureBody1,ParValues,negative,LocalWF),
2276 perfmessage_bexpr(forall,forall_counter_example(CParameters,ParValues),LHS)
2277 ),LocalWF, forall(CParameters), Infos),
2278 copy_wfe_from_inner_if_necessary(LocalWF,WF), % TODO: pass this goal to not_with.._delay in case negation is delayed
2279 re_attach_pending_inner_abort_errors(negative,WF).
2280
2281 :- use_module(library(timeout),[time_out/3]).
2282 not_with_enum_warning_and_possible_delay(C,WF,PP,Span) :-
2283 get_preference(disprover_mode,true),
2284 !,
2285 % delay potentially expensive quantifications in the hope of finding other contradictions earlier
2286 if( (time_out(not_with_enum_warning(C,WF,PP,Span),20,TRes),TRes \== time_out),
2287 true,
2288 (get_wait_flag(2,not_with_enum_warning_and_possible_delay,WF,LWF), % which priority to use ??
2289 debug_println(19,delaying_not),
2290 not_with_enum_warning_delay(C,LWF,PP,Span))).
2291 not_with_enum_warning_and_possible_delay(C,WF,PP,Span) :-
2292 not_with_enum_warning(C,WF,PP,Span).
2293
2294 :- block not_with_enum_warning_delay(?,-,?,?).
2295 not_with_enum_warning_delay(C,_,PP,Span) :- debug_println(19,trigger_not_with_enum_warning_delay),
2296 not_with_enum_warning(C,no_wf_available,PP,Span).
2297
2298 :- use_module(avl_tools,[quick_avl_approximate_size/2]).
2299 obvious_enumeration(LHS,[Id]) :-% TO DO : use multiple ids
2300 % TO DO: unify with is_for_all_set_membership_predicate code below
2301 LHSMembership = b(member(b(identifier(Id),_,_),b(value(VAL),_,_)),pred,_),
2302 ? member_conjunct(LHSMembership,LHS,_),
2303 nonvar(VAL), VAL = avl_set(AVL), % TO DO: also support interval closures ?
2304 quick_avl_approximate_size(AVL,Size),
2305 Size<256.
2306 % also check equality ?
2307
2308 % expands forall quantifier and thus enables that we also propagate from right to left
2309 % This helps for test 1397 (HandshakeSimple_TotFun)
2310 % TO DO: directly call the code which tries to expand a forall quantifier
2311 expand_forall_quantifier(Parameters,LHS,RHS,Infos,WF,ReificationVariable) :-
2312 (preferences:preference(use_smt_mode,true) -> true
2313 ; preferences:preference(solver_strength,SS), SS>9), % sometimes contrapositive checking maybe not useful; see test 1368
2314 % TO DO: investigate and provide more principled heuristic
2315 b_interpreter_check:b_check_forall_wf(Parameters,LHS,RHS,Infos,[],[],WF,ReificationVariable).
2316
2317 % rewrite !(x,..).( TRUTH => (LHS2 => RHS2)) into !(x,...).(LHS2 => RHS2)
2318 peel_implications(Parameters,ParCard,LHS,RHS, NewLHS,NewRHS) :-
2319 %print(forall),nl, print(Parameters),nl,print(LHS),nl,
2320 % this patterns occurs often in Event-B translations to classical B
2321 LHS=b(truth,_,_),
2322 RHS=b(implication(LHS2,RHS2),_,_), % TO DO: maybe also accept nested forall and then add to Parameters?
2323 (ParCard=inf -> true ; ParCard>50), % larger bound than below: maybe the user explicitly wants to expand it
2324 !,
2325 peel_implications(Parameters,ParCard,LHS2,RHS2, NewLHS,NewRHS).
2326 peel_implications(_,_,LHS,RHS, LHS,RHS).
2327
2328 b_generate_for_all_list_domain_nolwf(Parameters,LHS,RHS,LS,S,ForAllDomain,NewRHS,WF) :-
2329 ? parameter_list_cardinality(Parameters,ParCard),
2330 peel_implications(Parameters,ParCard,LHS,RHS, LHS2,RHS2),
2331 b_generate_for_all_list_domain1(Parameters,ParCard,LHS2,RHS2,LS,S,OForAllDomain,NewRHS,WF),
2332 optlist_to_list(OForAllDomain,ForAllDomain). % resolve any optional_value/2 items
2333
2334 % generate the domain of a Universally Quantified Formula as a list
2335 b_generate_for_all_list_domain1(Parameters,_ParCard,LHS,RHS,LS,S,ForAllDomain,NewRHS,WF) :-
2336 % optimized treatment for formulas of the form !x.(x:S => RHS) or !(x,y).(x|->y:S => RHS)
2337 % to do: expand to more formulas, such as !(x,y).(x:S & y:T => RHS)
2338 % or !y.(y:1..(n-1) & f(y)=TRUE => f(y+1)=TRUE) --> !y.(y:1..(n-1) => (f(y)=TRUE => f(y+1)=TRUE))
2339 % or we could try and reify set membership for small domains and trigger implication
2340 is_for_all_set_membership_predicate(LHS,Parameters,Set,Pattern,ParameterValues),!,
2341 perfmessages_bexpr_call(good(forall),['Detected forall set membership over ',Ps,': '],
2342 LHS,bsyntaxtree:def_get_texpr_ids(Parameters,Ps)),
2343 NewRHS=RHS,
2344 b_generate_set_for_all_domain(Set,LS,S,Pattern,ParameterValues,ForAllDomain,WF).
2345 b_generate_for_all_list_domain1(Parameters,ParCard,LHS,RHS,LS,S,ForAllDomain,NewRHS,WF) :-
2346 b_generate_forall_closure(Parameters,LHS,LS,S,Closure,WF), % POSSIBLY NO NEED TO COMPILE
2347 b_generate_for_all_domain2(Closure,Parameters,ParCard,LHS,RHS,ForAllDomain,NewRHS,WF).
2348
2349 b_generate_for_all_domain2(Closure,_Parameters,_,LHS,RHS,ForAllDomain,NewRHS,WF) :-
2350 (LHS=b(truth,pred,_) ; ground_value(Closure)),
2351 !, NewRHS=RHS, % nl,print('FORALL EXPAND: '),(ground_value(Closure) -> print(ground(_Parameters)),nl, print_bexpr(LHS),nl ; print('NONGROUND!!'),nl,print_bexpr(RHS),nl), %%
2352 b_expand_closure_forall_to_list(Closure,ForAllDomain,WF).
2353 b_generate_for_all_domain2(_,Parameters,_,LHS,RHS,ForAllDomain,NewRHS,WF) :-
2354 is_a_conjunct(LHS,_,_), % otherwise we have already checked for set_membership above !
2355 LHS_Membership = b(member(_,_),_,_), % TO DO: also allow conjuncts
2356 ? member_conjunct(LHS_Membership,LHS,RestLHS),
2357 % !(x). ( x:Set & RestLHS => RHS) ---> !(x).(x:Set => (RestLHS => RHS))
2358 is_for_all_set_membership_predicate(LHS_Membership,Parameters,Set,Pattern,ParameterValues),
2359 ? max_cardinality_ok_for_expansion(Set,100,[],[]), % TO DO: simplify LS,S argument <----
2360 !,
2361 % as we expand Set without RHS predicate, check if this is ok
2362 % indeed maximum cardinality of Set could be infinite !! !x.(x:NATURAL1 & x<N => P)
2363 % print('Splitting for all conjunct: '), print(Parameters),nl, print_bexpr(LHS_Membership),nl,print_bexpr(RestLHS),nl, %%
2364 perfmessage_bexpr(good(forall),'Splitting LHS of forall: ',LHS),
2365 NewRHS = b(implication(RestLHS,RHS),pred,[]), % TO DO: extract & join info
2366 b_generate_set_for_all_domain(Set,[],[],Pattern,ParameterValues,ForAllDomain,WF).
2367 b_generate_for_all_domain2(Closure,_Parameters,ParCard,LHS,RHS,ForAllDomain,NewRHS,WF) :-
2368 (ParCard=inf -> true ; ParCard>8),
2369 !,
2370 NewRHS=RHS,
2371 perfmessage_bexpr(forall,'No optimisations applicable to forall (will delay until all variables are bound): ',LHS), % maybe we should generate this message only if ForAllDomain is var ?
2372 b_expand_closure_forall_to_list(Closure,ForAllDomain,WF).
2373 b_generate_for_all_domain2(_Closure,Parameters,ParCard,LHS,RHS,ForAllDomain,NewRHS,WF) :-
2374 NewLHS=b(truth,pred,[]), NewRHS=b(implication(LHS,RHS),pred,[]),
2375 b_generate_forall_closure(Parameters,NewLHS,[],[],Closure,WF),
2376 perfmessages_bexpr(good(forall),['Expanding forall with finite parameter type, card = ',ParCard,': '],LHS),
2377 b_expand_closure_forall_to_list(Closure,ForAllDomain,WF).
2378
2379 % code to decide whether a for all should be expanded if the
2380 % predicate contains a set membership predicate : !x.( (P & x:S & P') => Q)
2381 max_cardinality_ok_for_expansion(b(Expr,Type,_Info),Limit,LS,S) :- % which value to choose for Limit ??
2382 ? kernel_objects:max_cardinality(Type,TypeCard),
2383 ( (number(TypeCard),TypeCard =< Limit) -> true ;
2384 max_cardinality_ok_for_expansion2(Expr,Limit,TypeCard,LS,S)).
2385
2386 max_cardinality_ok_for_expansion1(b(E,_,_),Limit,TC,LS,S) :-
2387 max_cardinality_ok_for_expansion2(E,Limit,TC,LS,S).
2388
2389 :- use_module(custom_explicit_sets,[efficient_card_for_set/3]).
2390
2391 max_cardinality_ok_for_expansion2(set_extension(E),Limit,_TC,_,_) :- !, length(E,Len), Len =< Limit.
2392 max_cardinality_ok_for_expansion2(interval(Up,Low),Limit,_TC,LS,S) :- !,
2393 get_integer(UpI,Up,LS,S), get_integer(LowI,Low,LS,S),
2394 UpI-LowI<Limit.
2395 max_cardinality_ok_for_expansion2(integer_set(GS),Limit,_TC,_LS,_S) :- !, b_global_set_cardinality(GS,Card),
2396 number(Card), Card =< Limit.
2397 max_cardinality_ok_for_expansion2(set_subtraction(A,_),Limit,TC,LS,S) :- !,
2398 max_cardinality_ok_for_expansion1(A,Limit,TC,LS,S).
2399 max_cardinality_ok_for_expansion2(image(RelA,_),Limit,TC,LS,S) :- !,
2400 max_cardinality_ok_for_expansion1(RelA,Limit,TC,LS,S).
2401 max_cardinality_ok_for_expansion2(function(_RelA,_),_Limit,_TC,_LS,_S) :- !,
2402 fail. % TO DO: we should look at the size of the range elements
2403 % max_cardinality_ok_for_expansion1(_RelA,_Limit,_TC,_LS,_S).
2404 max_cardinality_ok_for_expansion2(intersection(A,B),Limit,TC,LS,S) :- !,
2405 (max_cardinality_ok_for_expansion1(A,Limit,TC,LS,S) -> true ; max_cardinality_ok_for_expansion1(B,Limit,TC,LS,S)).
2406 max_cardinality_ok_for_expansion2(union(A,B),Limit,TC,LS,S) :- !,
2407 max_cardinality_ok_for_expansion1(A,Limit,TC,LS,S), max_cardinality_ok_for_expansion1(B,Limit,TC,LS,S).
2408 max_cardinality_ok_for_expansion2(range(A),Limit,TC,LS,S) :- !,
2409 max_cardinality_ok_for_expansion1(A,Limit,TC,LS,S).
2410 max_cardinality_ok_for_expansion2(domain(A),Limit,TC,LS,S) :- !,
2411 max_cardinality_ok_for_expansion1(A,Limit,TC,LS,S).
2412 max_cardinality_ok_for_expansion2(direct_product(A,B),Limit,TC,LS,S) :- !,
2413 max_cardinality_ok_for_expansion2(cartesian_product(A,B),Limit,TC,LS,S).
2414 max_cardinality_ok_for_expansion2(parallel_product(A,B),Limit,TC,LS,S) :- !,
2415 max_cardinality_ok_for_expansion2(cartesian_product(A,B),Limit,TC,LS,S).
2416 max_cardinality_ok_for_expansion2(cartesian_product(A,B),Limit,TC,LS,S) :- !,
2417 ILimit is Limit//2, ILimit>0, %use sqrt ?
2418 max_cardinality_ok_for_expansion1(A,ILimit,TC,LS,S),
2419 max_cardinality_ok_for_expansion1(B,ILimit,TC,LS,S).
2420 max_cardinality_ok_for_expansion2(value(S),Limit,_TC,_LS,_S) :- !,
2421 get_max_card_for_value(S,MaxCard),
2422 MaxCard =< Limit.
2423 max_cardinality_ok_for_expansion2(identifier(_ID),_Limit,TC,_LS,_S) :- !, number(TC).
2424 % TO DO: check if ID is fully defined; if so use card else accept as it will
2425 % probably be represented by a list and the forall constraints could be useful in finding ID's value
2426 % we have to store/compute ID anyway (could be infinite closure; hence check that TC is a number); a bit of a hack; is there a more principled way?
2427 max_cardinality_ok_for_expansion2(external_function_call(_,_),_,_,_,_) :- !,fail.
2428 max_cardinality_ok_for_expansion2(lazy_lookup_expr(_),_,_,_,_) :- !,fail.
2429 max_cardinality_ok_for_expansion2(record_field(_,_),_Limit,_TC,_LS,_S) :- !, fail.
2430 max_cardinality_ok_for_expansion2(E,Limit,TC,_LS,_S) :- functor(E,F,N),
2431 print(unknown_max_card(F/N,Limit,TC)),nl,fail.
2432
2433
2434 :- use_module(kernel_cardinality_attr,[clpfd_card_domain_for_var/3]).
2435
2436 get_max_card_for_value(S,MaxCard) :- var(S), !,
2437 clpfd_card_domain_for_var(S,_,Max), number(Max),
2438 MaxCard=Max.
2439 get_max_card_for_value([],R) :- !, R=0.
2440 get_max_card_for_value([_|T],R) :- !,get_max_card_for_value(T,TMax), R is TMax+1.
2441 get_max_card_for_value(S,Card) :- efficient_card_for_set(S,Card,C),!,
2442 call(C), number(Card).
2443
2444
2445 get_integer(X, b(Expr,integer,_),LS,S) :- get_integer2(Expr,X,LS,S).
2446 get_integer2(integer(X),X,_,_) :- number(X).
2447 get_integer2(identifier(Id),Val,LS,S) :- lookup_value(Id,LS,S,int(Val)), number(Val).
2448
2449 member_conjunct(Predicate,Conjunction,Rest) :-
2450 conjunction_to_list(Conjunction,List),
2451 ? select(Predicate,List,RestList),
2452 conjunct_predicates(RestList,Rest).
2453 % member_conjunct(Conj,Conj,b(truth,pred,[])). covered by case above
2454
2455 b_generate_set_for_all_domain(Set,LS,S,Pattern,ParameterValues,ForAllDomain,WF) :-
2456 b_compute_expression(Set,LS,S,EvSet,WF),
2457 expand_custom_set_to_list_wf(EvSet,ESet,_Done,b_generate_set_for_all_domain,WF),
2458 filter_and_convert_list_to_parameter_tuples(ESet,Pattern,ParameterValues,ForAllDomain).
2459
2460
2461 % check if it is a predicate of the form x:S or x:Sx & y:Sy ... which we can optimize
2462 % (i.e. compute SET before all values inside it are fully known)
2463 is_for_all_set_membership_predicate(LHS,Parameters,Set,Pattern,ParameterValues) :-
2464 % print('CHECK FORALL : '), translate:print_bexpr(LHS),nl,nl,
2465 get_texpr_ids(Parameters,ParIDs), % TO DO: call get_texpr_ids before
2466 same_length(ParIDs,ParameterValues),
2467 is_for_all_set_membership_predicate2(LHS,ParIDs,ParIDs,UnmatchedParIDs,Set,Pattern,ParameterValues,_UPV),
2468 UnmatchedParIDs=[].
2469
2470 is_for_all_set_membership_predicate2(LHS,All,ParIDs,UnmatchedParIDs,Set,Pattern,ParameterValues,UPV) :-
2471 is_member_test(LHS,Element,Set),
2472 !,
2473 identifiers_not_used_in_bexp(All,Set),
2474 convert_to_prolog_pattern_match(Element,ParIDs,UnmatchedParIDs,Pattern,ParameterValues,UPV).
2475 % TO DO: also allow failing pattern matches ?!; at least when splitting
2476 is_for_all_set_membership_predicate2(LHS,All,ParIDs,ParIDs2,Set,
2477 (Pat1,Pat2),ParameterValues,UPV) :-
2478 is_a_conjunct(LHS,LHS1,LHS2), % we could have something of the form x:Sx & y:Sy ...
2479 Set = b(cartesian_product(Set1,Set2),couple(T1,T2),[]),
2480 is_for_all_set_membership_predicate2(LHS1,All,ParIDs, ParIDs1,Set1,Pat1,ParameterValues,PV1),
2481 get_texpr_type(Set1,T1),
2482 !,
2483 is_for_all_set_membership_predicate2(LHS2,All,ParIDs1,ParIDs2,Set2,Pat2,PV1,UPV),
2484 get_texpr_type(Set2,T2).
2485
2486 % TO DO: maybe use a more general test to be reused in other places
2487 is_member_test(b(P,_,_),Element,Set) :- is_member_test_aux(P,Element,Set).
2488 is_member_test_aux(member(Element,Set),Element,Set).
2489 % also detect equalities: important for tests 28,29 after b_compiler can introduce equalities for singleton set memberships
2490 is_member_test_aux(equal(Element,SetVal),Element,Set) :- % TO DO : also other direction + other kinds of values ?
2491 SetVal = b(value(SV),T,I),
2492 Set = b(value([SV]),set(T),I).
2493
2494 identifiers_not_used_in_bexp(IDList,Expr) :-
2495 find_identifier_uses(Expr,[],Used),
2496 id_check(IDList,Used).
2497 id_check([],_).
2498 id_check([ID|T],Used) :-
2499 nonmember(ID,Used), !,
2500 id_check(T,Used).
2501
2502 % check if an expression can be converted to a Prolog linear unification/pattern match
2503 % give an list of free identifiers IDS
2504 convert_to_prolog_pattern_match(b(E,_,_),IDS,OutIDS,Pattern,VarsIn,VarsOut) :-
2505 convert_to_prolog_pattern_match2(E,IDS,OutIDS,Pattern,VarsIn,VarsOut).
2506
2507 convert_to_prolog_pattern_match2(identifier(ID),IDsIn,IDsOut,PatVariable,VarsIn,VarsOut) :-
2508 % check that the identifier is in the list of quantified variables and thus unbound
2509 !,
2510 ? (nth1(Nr,IDsIn,ID,IDsOut)
2511 -> nth1(Nr,VarsIn,PatVariable,VarsOut) % put fresh PatVariable in the Pattern
2512 ),!.
2513 convert_to_prolog_pattern_match2(couple(ID1,ID2),IDS,OutIDS,Pattern,VarsIn,VarsOut) :-
2514 Pattern = (Pat1,Pat2),
2515 convert_to_prolog_pattern_match(ID1,IDS,RemIDS,Pat1,VarsIn,VarsInt),
2516 convert_to_prolog_pattern_match(ID2,RemIDS,OutIDS,Pat2,VarsInt,VarsOut).
2517 convert_to_prolog_pattern_match2(value(V),IDsIn,IDsOut,Pattern,VarsIn,VarsOut) :-
2518 can_be_used_for_unification(V), % check if we can use Prolog unification for equality
2519 !, Pattern=V, IDsOut=IDsIn, VarsIn=VarsOut.
2520 % TO DO: records?
2521
2522 % a pattern match code to be used with above; ensure we do not instantiate values
2523 pattern_match(PatVar,Val,Res) :- var(PatVar),!,PatVar=Val, Res=pred_true. % we have a free pattern variable
2524 pattern_match((Pat1,Pat2),(V1,V2),Res) :- !,
2525 pattern_match(Pat1,V1,R1), conjoin_simple(R1,R2,Res),
2526 pattern_match(Pat2,V2,R2).
2527 pattern_match(GroundPatVal,Val,Res) :- % we have a value that can_be_used_for_unification
2528 when( ?=(GroundPatVal,Val), (GroundPatVal=Val -> Res=pred_true ; Res=pred_false)).
2529
2530 :- block conjoin_simple(-,?,?). % TO DO: also allow second arg to unblock
2531 conjoin_simple(pred_true,X,X).
2532 conjoin_simple(pred_false,_,pred_false).
2533
2534 % similar to get_template(V,T,[])
2535 % but more restricted; we only accept those values where equality corresponds to Prolog unification
2536 % get_template is different and can assume normalized values, e.g., for empty set
2537 can_be_used_for_unification(V) :- var(V),!,fail.
2538 can_be_used_for_unification(int(V)) :- nonvar(V).
2539 can_be_used_for_unification(string(S)) :- ground(S).
2540 can_be_used_for_unification(fd(S,T)) :- ground(S), ground(T).
2541 can_be_used_for_unification(pred_false).
2542 can_be_used_for_unification(pred_true).
2543
2544
2545
2546 %large_parameter_list_cardinality(Parameters,Limit) :-
2547 % parameter_list_cardinality(Parameters,ParCard), (ParCard=inf -> true; ParCard > Limit).
2548
2549 % take a list and a pattern and filter the values that do not match the Pattern
2550 % Unification with the Pattern also instantiates the ParameterValues
2551 % TODO: Instead of converting to a Prolog Unification we could use kernel_equality instead of pattern_match
2552 % but this is not obvious, as the pattern contains free variables and equality would never return true
2553 % we would need to apply kernel_equality only to the ground pattern parts
2554 :- block filter_and_convert_list_to_parameter_tuples(-,?,?,?).
2555 filter_and_convert_list_to_parameter_tuples([],_,_,[]).
2556 filter_and_convert_list_to_parameter_tuples([H|T],Pattern,ParameterValues,Res) :-
2557 copy_term((Pattern,ParameterValues),(CPat,CPV)),
2558 pattern_match(CPat,H,PredRes), % check if pattern matches new element H in set; careful not to instantiate H
2559 ? filter_and_convert_list_to_parameter_tuples_aux(PredRes,CPV,T,Pattern,ParameterValues,Res).
2560
2561 :- block filter_and_convert_list_to_parameter_tuples_aux(-,?,-,?,?,?).
2562 filter_and_convert_list_to_parameter_tuples_aux(PredRes,CPV,T,Pattern,ParameterValues,Res) :-
2563 var(PredRes),!, % we cannot decide yet whether the optional value is to be used or not
2564 Res = [optional_value(CPV,PredRes)|RT], % create constructor for map_optlist or similar
2565 filter_and_convert_list_to_parameter_tuples(T,Pattern,ParameterValues,RT).
2566 filter_and_convert_list_to_parameter_tuples_aux(PredRes,CPV,T,Pattern,ParameterValues,Res) :-
2567 (PredRes = pred_true % we have a match, universal quantifier applies to H
2568 -> Res = [CPV|RT]
2569 ; % element of set does not match pattern; universal quantifier does not apply
2570 % ProB used to only accept non-failing pattern matches;
2571 % now we also accept tuples with static parts where Prolog unification can fail
2572 Res=RT
2573 ),
2574 ? filter_and_convert_list_to_parameter_tuples(T,Pattern,ParameterValues,RT).
2575
2576 :- use_module(tools,[map_optlist/2,optlist_to_list/2]).
2577 :- use_module(library(lists),[maplist/3]).
2578 expand_forall1(OList,RHS,Parameters,WF) :-
2579 ground_bexpr(RHS), % because compiled this means we cannot do any constraint propagation on variables in RHS
2580 optlist_to_list(OList,List),
2581 ground_value(List), % ditto here: no variables on which we could do constraint propagation
2582 %% preferences:get_preference(double_evaluation_when_analysing,false), % causes test 1112 to fail TO DO:fix
2583 % otherwise we do not have a real redundancy wrt to not exists check
2584 debug_println(15,ground_forall_translating_into_not_exists(Parameters)),
2585 !,
2586 %kernel_waitflags:init_wait_flags(LocalWF,[expansion_context(forall,Parameters)]),
2587 init_quantifier_wait_flag(WF,forall,Parameters,ParResult,unknown,LocalWF),
2588 % Advantage over treatment below: NegRHS is interpreted only once
2589 % but we cannot provide any instantiations and there must not be any links with variables outside of the forall !!
2590 create_negation(RHS,NegRHS),
2591 not_with_enum_warning( (
2592 b_interpreter:test_forall_instance(NegRHS,Parameters,LocalWF,negative,ParResult), % can fail; if inconsistency detected in WF0
2593 kernel_waitflags:ground_det_wait_flag(LocalWF),
2594 member(ParResultInList,List), % check the body for every solution
2595 lists:maplist(kernel_objects:equal_object,ParResultInList,ParResult), % match parameters with the solutions of the domain
2596 kernel_waitflags:ground_wait_flags(LocalWF) % do not ground EF? ground_constraintprop_wait_flags ground_inner_wait_flags
2597 ), LocalWF, forall(Parameters), RHS
2598 ).
2599 expand_forall1(List,RHS,Parameters,WF) :-
2600 ? map_optlist(b_interpreter:test_forall_instance(RHS,Parameters,WF,positive),List).
2601
2602
2603 test_forall_instance(RHS,Parameters,WF,NegationContext,ParResult) :-
2604 LocalState=[],State=[],
2605 ? if(set_up_typed_localstate(Parameters,ParResult,_TypedVals,LocalState,NewLocalState,NegationContext),
2606 true,
2607 (nl,print(set_up_typed_localstate_failed(Parameters,ParResult,_,LocalState,NewLocalState)),nl,
2608 % it can happen that ParResult has constraints on it and that setting up the typing info detects the error
2609 % add_internal_error('Call failed: ', set_up_typed_localstate(Parameters,ParResult,_,LocalState,NewLocalState)),
2610 fail)),
2611 ? b_optimized_b_test_instance(RHS,NewLocalState,State,WF).
2612
2613 reification_relevant_for_op(implication(_,_)).
2614 reification_relevant_for_op(equivalence(_,_)).
2615 reification_relevant_for_op(disjunct(_,_)).
2616 % TODO: maybe check if a conjunct contains implication
2617 % relevant for example for: n=2000 & f:1..n-->BOOL & !i.(i:2..n => (f(i)=TRUE =>f(i-1)=FALSE)) & f(1)=TRUE
2618
2619 b_optimized_b_test_instance(RHS,NewLocalState,State,WF) :-
2620 get_texpr_expr(RHS,RE), reification_relevant_for_op(RE), % we will attempt reification
2621 attempt_reification,
2622 \+ always_well_defined(RHS), % this will prevent reification
2623 !,
2624 % try and compile in the hope that now the WD issue disappears:
2625 b_compiler:b_optimize(RHS,[],NewLocalState,State,NewRHS,WF),
2626 b_test_boolean_expression(NewRHS,NewLocalState,State,WF).
2627 b_optimized_b_test_instance(RHS,NewLocalState,State,WF) :-
2628 ? b_test_boolean_expression(RHS,NewLocalState,State,WF).
2629 % using b_test_inner_boolean_expression considerably slows down NQueens, Sudoku,...
2630 % WF=InnerWF. /* give the boolean expression a chance to do ground propagations first */
2631
2632
2633 % use this when the test boolean expression could be called with WF0 already set
2634 % give the inner expression a chance to do the deterministic stuff first
2635 b_test_inner_boolean_expression(Pred,LocalState,State,WF) :-
2636 kernel_waitflags:clone_wait_flags_from1(WF,GroundUponFinish,WF2),
2637 % set WF0 to variable to propagate deterministic infos first:
2638 ? b_test_boolean_expression(Pred,LocalState,State,WF2),
2639 ? kernel_waitflags:clone_wait_flags_from1_finish(WF,GroundUponFinish,WF2).
2640 % the same for testing negation of a predicate:
2641 b_not_test_inner_boolean_expression(Pred,LocalState,State,WF) :-
2642 kernel_waitflags:clone_wait_flags_from1(WF,GroundUponFinish,WF2),
2643 % set WF0 to variable to propagate deterministic infos first:
2644 ? b_not_test_boolean_expression(Pred,LocalState,State,WF2),
2645 kernel_waitflags:clone_wait_flags_from1_finish(WF,GroundUponFinish,WF2).
2646
2647 /* now the same as above; but without converting list of values into pairs */
2648 :- assert_pre(b_interpreter:b_expand_closure_forall_to_list(Closure,_Result,_WF),
2649 (nonvar(Closure), custom_explicit_sets:is_closure(Closure,_Parameters,_ParameterTypes,ClosureBody),
2650 nonvar(ClosureBody),
2651 bsyntaxtree:check_if_typed_predicate(ClosureBody))).
2652 :- assert_post(b_interpreter:b_expand_closure_forall_to_list(_Closure,Result,_WF),
2653 b_interpreter:value_type(Result)).
2654 b_expand_closure_forall_to_list(Closure,Result,WF) :- nonvar(Closure),
2655 Closure = closure(Parameters,ParameterTypes,ClosureBody),
2656 !,
2657 % print('Expand closure forall: '), translate:print_bexpr(ClosureBody),nl,
2658 % at the moment we may wait too long before expanding this closure
2659 % what if we have f(1) in the ClosureBody: in principle we only need to wait until f(1) known or even f sekeleton set up ? compilation now solves this issue ?
2660 (performance_monitoring_on,
2661 term_variables(ClosureBody,Vars),
2662 Vars \= []
2663 ->
2664 perfmessagecall(delaying_forall(Parameters,vars(Vars),out(ParValues)),translate:print_bexpr(ClosureBody),ClosureBody)
2665 ; true),
2666 ground_bexpr_check(ClosureBody,BodyGround),
2667 add_texpr_infos(ClosureBody,[quantifier_kind(forall)],ClosureBody1), % for call_stack
2668 delay_setof_list( ParValues,
2669 %% (print_bt_message(expanding_forall_closure(Parameters,ClosureBody,ParValues)), %%
2670 custom_explicit_sets:b_test_closure(Parameters,ParameterTypes,ClosureBody1,ParValues,all_solutions,WF)
2671 %% ,print_bt_message(expanded(Parameters,ParValues)) ) %%
2672 ,
2673 Result,
2674 BodyGround).
2675 b_expand_closure_forall_to_list(Closure,Result,WF) :-
2676 add_internal_error('Illegal Call: ', b_expand_closure_forall_to_list(Closure,Result,WF)),
2677 fail.
2678
2679
2680 :- assert_pre(b_interpreter:set_up_typed_localstate(V,S,_), (list_skeleton(V),list_skeleton(S))).
2681 :- assert_post(b_interpreter:set_up_typed_localstate(_,_,R),list_skeleton(R)).
2682
2683 set_up_typed_localstate(Identifiers,InState,OutState) :-
2684 ? set_up_typed_localstate(Identifiers,_FreshVars,_TypedVals,InState,OutState,positive).
2685
2686 :- use_module(b_enumerate,[construct_typedval_infos/4]).
2687 set_up_typed_localstate([],[],[],State,State,_).
2688 set_up_typed_localstate([Identifier|IdRest],[Val|ValRest],[typedval(Val,Type,Var,TINFO)|TRest],
2689 % TO DO: add info field to typedval: source_span, and lambda_result/do_not_enumerate infos
2690 InState,OutState,NegationContext) :-
2691 % The other way round (first add Identfier, then IdRest) would be more efficient,
2692 % but we do it this way to keep compatibility with a previous version.
2693 % In specfile:compute_operation_effect, the arguments of an operation are in the same order than in the store
2694 ? set_up_typed_localstate(IdRest,ValRest,TRest,InState,InterState,NegationContext),
2695 def_get_texpr_id(Identifier,Var), get_texpr_type(Identifier,Type),
2696 get_texpr_info(Identifier,Info),
2697 triggers_enum_warning(Var,Type,Info,NegationContext,TriggersEnumWarning),
2698 get_texpr_info(Identifier,Infos),construct_typedval_infos(Var,Infos,TriggersEnumWarning,TINFO),
2699 ? add_typed_var_to_localstate(Var,Val,Type,InterState,OutState).
2700
2701 % same version; but with list of atomic ids and list of types
2702 set_up_typed_localstate2([],[],_,[],[],State,State,_).
2703 set_up_typed_localstate2([Var|IdRest],[Type|TyRest],Infos,[Val|ValRest],[typedval(Val,Type,Var,TINFO)|TRest],
2704 InState,OutState,NegationContext) :-
2705 % The other way round (first add Identfier, then IdRest) would be more efficient,
2706 % but we do it this way to keep compatibility with a previous version.
2707 % In specfile:compute_operation_effect, the arguments of an operation are in the same order than in the store
2708 ? set_up_typed_localstate2(IdRest,TyRest,Infos,ValRest,TRest,InState,InterState,NegationContext),
2709 triggers_enum_warning(Var,Type,Infos,NegationContext,TriggersEnumWarning),
2710 construct_typedval_infos(Var,Infos,TriggersEnumWarning,TINFO),
2711 ? add_typed_var_to_localstate(Var,Val,Type,InterState,OutState).
2712
2713 % possible values for NegationContext: positive, negative, all_solutions
2714 triggers_enum_warning(Id,Type,Info,all_solutions,Res) :- !,
2715 Res = trigger_throw(b(identifier(Id),Type,Info)).
2716 %triggers_enum_warning(Id,_Type,Info,NegationContext,trigger_false(Id)) :- % no longer used
2717 % NegationContext=positive, % when negated then success will occur if all possibilities have been tried out
2718 % memberchk(introduced_by(exists),Info),
2719 % %%((preferences:get_preference(disprover_mode,true),type_contains_unfixed_deferred_set(Type))-> fail % otherwise %finding a solution may depend on the size of the deferred set; true),
2720 % %% The Disprover now checks whether unfixed_deferred sets were involved; keeping track of implicit enumerations of %deferred sets is just too difficult
2721 % !.
2722 triggers_enum_warning(Id,Type,Info,_,trigger_true(b(identifier(Id),Type,Info))).
2723
2724
2725 add_typed_var_to_localstate(Var,Val,Type,InState,OutState) :-
2726 add_var_to_localstate(Var,Val,InState,OutState),
2727 %%when(ground(Val), (print(' ++ '),print(Var),print(' ---> '), print(Val),nl)),
2728 ? kernel_objects:basic_type(Val,Type). %% ,print(ok(Val)),nl.
2729
2730 /*
2731 xxb_test_exists(Parameters,Condition,Infos,LocalState,State,WF) :-
2732 b_check_boolean_expression(b(exists(Parameters,Condition),pred,Infos),LocalState,State,WF,NR),
2733 get_exists_used_ids(Parameters,Condition,Infos,Used),lookup_values_if_vars(Used,LocalState,State,WaitVars),
2734 \+ ground(WaitVars),
2735 !,
2736 debug_println(9,unfolding_exists(Parameters)), print(unfolding(Parameters)),nl,
2737 %translate:print_bexpr(Condition),nl, print(State),nl, print(LocalState),nl,nl,
2738 NR=pred_true. %, print(set_res(pred_true)),nl.
2739 % if enabled it slows down: ./probcli examples/EventBPrologPackages/SET_Game/SET_GAM_Sym_NoSet20_mch.eventb -mc 10000000 -p SYMMETRY_MODE hash -p TIME_OUT 7000 -p CLPFD TRUE -df -goal "n=18" -p MAX_OPERATIONS 20 -strict -expcterr goal_found
2740 */
2741
2742 b_test_exists(Parameters,Condition,Infos,LocalState,State,WF) :-
2743 get_wait_flag0(WF,WF0),
2744 ? b_test_exists(WF0,Parameters,Condition,Infos,LocalState,State,WF).
2745
2746 :- block b_test_exists(-,?,?, ?,?,?,?).
2747 b_test_exists(_LWF,Parameters,Condition,Infos,LocalState,State,WF) :-
2748 if((attempt_reification, % what if there is a wd_condition attached to Condition?
2749 b_interpreter_check:b_check_exists_wf(Parameters,Condition,Infos,LocalState,State,WF,ReificationVariable)),
2750 % try and expand quantifiers of small cardinality; see also expand_forall_quantifier
2751 % tested in test 1452
2752 (debug_println(9,expanded_exists(Parameters)),
2753 ReificationVariable=pred_true),
2754 ? b_test_exists_wo_expansion(Parameters,Condition,Infos,LocalState,State,WF)).
2755
2756 %attempt_reification :- preferences:preference(use_clpfd_solver,true),!. % all tests seem to pass
2757 attempt_reification :- preferences:preference(use_smt_mode,true),!.
2758 attempt_reification :- preferences:preference(solver_strength,SS), SS>9.
2759 % TO DO: maybe take context into account: setup constants, becomes such, ... allow_skipping_over_components/reset_component_info(true)
2760
2761 :- use_module(kernel_tools,[bexpr_variables/2, value_variables/3]).
2762
2763 % we treat the existential quantifier without expansion into a disjuncition aka reification
2764 b_test_exists_wo_expansion(Parameters,Condition,Infos,LocalState,State,WF) :-
2765 %print(test_exists(Parameters,Infos)),nl,portray_waitflags(WF),nl,
2766 ? (preference(lift_existential_quantifiers,true) ; member(allow_to_lift_exists,Infos)),
2767 !, % we enumerate the exists normally; treat it just like an ordinary predicate
2768 % lifting may generate multiple solutions; but avoids delaying enumeration of quantified parameters
2769 % print('*Lifting existential quantifier: '), translate:print_bexpr(Condition),nl,
2770 ? set_up_typed_localstate(Parameters,ParaValues,TypedVals,LocalState,NewLocalState,positive),
2771 copy_wf_start(WF,b_test_exists_wo_expansion,CWF),
2772 opt_push_wait_flag_call_stack_quantifier_info(CWF,exists,Parameters,ParaValues,Infos,CWF2),
2773 ? b_test_boolean_expression(Condition,NewLocalState,State,CWF2),
2774 % often we do not need to enumerate TypedVals; they can be derived, but we could have #y.(y>x) and need to enum y
2775 b_tighter_enumerate_values_in_ctxt(TypedVals,Condition,CWF2),
2776 ? copy_wf_finish(WF,CWF2). % moving this before tighter_enum may mean that we have more precise ranges; but this can be counter-productive (e.g., for test 1162 unless we strengthen the useless enum analysis)
2777 b_test_exists_wo_expansion(Parameters,Condition,Infos,LocalState,State,WF) :-
2778 get_exists_used_ids(Parameters,Condition,Infos,Used),
2779 % IT IS IMPORTANT THAT THE USED INFO IS CORRECT ; otherwise the WaitVars will be incorrect
2780 % The used_ids info does not include the Parameters of the existential quantifier !
2781 ? set_up_typed_localstate(Parameters,ParaValues,TypedVals,LocalState,NewLocalState,positive),
2782 lookup_values_if_vars(Used,LocalState,State,WaitVarsState), % TO DO: we could use b_compiler instead
2783 % What if the Condition was compiled and now contains a previously used_variable inside a closure/value ?
2784 %term_variables((Condition,WaitVarsState),WaitVars), % this can be expensive when we have large data values (see rule_RVF219/rule_RVF219_compo.mch)
2785 bexpr_variables(Condition,CondVars),
2786 value_variables(WaitVarsState,CondVars,WaitVars),
2787 % now determine which WaitVars are really worth waiting for, e.g., do not wait for res in #x.(x:E & ... res=min(f(x)))
2788 % relevant tests: 1868, 1194, 383, 1642, 1708, 1003, 1080, 1081, 1943
2789 (remove_ids_defined_by_equality(WaitVars,LocalState,State,Infos,RealWaitVars) -> RemovedVars=true
2790 ; RealWaitVars = WaitVars, RemovedVars=false),
2791 opt_push_wait_flag_call_stack_quantifier_info(WF,exists,Parameters,ParaValues,Infos,WF2),
2792 create_inner_wait_flags(WF2,expansion_context(b_test_exists,Parameters),LocalWF), % we are creating inner waitflags here as the exist will wait anyway; LocalWF shares just WFE flag with WF
2793 ? b_test_boolean_expression(Condition,NewLocalState,State,LocalWF), /* check Condition */
2794 ? ground_det_wait_flag(LocalWF), % print('det no contradiction'),nl,flush_output,
2795 b_tighter_enumerate_values_in_ctxt(TypedVals,Condition,LocalWF), % will not yet enumerate
2796 (% we could treat allow_to_lift_exists also here by setting ESWF=1; but 1162 then fails
2797 get_preference(data_validation_mode,true),
2798 not_generated_exists_paras(Parameters) % generated exists, e.g., for relational composition can lead to virtual timeouts, cf Thales_All/rule_zcpa2.mch in test 2287
2799 -> get_wait_flag(50000,b_test_exists(Parameters),WF,ESWF) % 100000 sufficient for test 1945; 869 for rule_CHAMPS in private_examples/ClearSy/2023
2800 ; get_enumeration_starting_wait_flag(b_test_exists(Parameters),WF,ESWF)), %% TO DO: get flag when enumeration of infinite type starts; maybe if domain of exists is small we can start enumerating earlier ?? <-> relation with lifting exists in closure expansion heuristic
2801 when((nonvar(ESWF);ground(RealWaitVars)),b_enumerate_exists(ESWF,RemovedVars,WaitVars,Parameters,LocalWF,WF)).
2802
2803 not_generated_exists_paras([b(_,_,Infos)|_]) :- nonmember(generated_exists_parameter,Infos).
2804
2805 :- use_module(tools,[remove_variables/3]).
2806 :- use_module(kernel_tools,[value_variables/2]).
2807 % if we have #x.( P & y = E(x)) we do not have to wait for y to be known
2808 remove_ids_defined_by_equality(WaitVars,LocalState,State,Infos,RealWaitVars) :- WaitVars \== [],
2809 memberchk(used_ids_defined_by_equality(Ideq),Infos),
2810 Ideq = [ID1|_], % currently we only look at one used_id defined by equality,
2811 % we could have #x.(P & y=E(z) & z=E(y)): TODO: improve computation in ast_cleanup
2812 (memberchk(bind(ID1,VAL),LocalState) -> true ; memberchk(bind(ID1,VAL),State)),
2813 value_variables(VAL,VARS),
2814 remove_variables(WaitVars,VARS,RealWaitVars),
2815 debug_println(9,removed_ids_def_by_equality(WaitVars,ID1,RealWaitVars)).
2816
2817
2818 b_enumerate_exists(ESWF,RemovedVars,WaitVars,Parameters,LocalWF,WF) :-
2819 %print(enum_exists(ESWF,RemovedVars,WaitVars,Parameters,LocalWF,WF)),nl,
2820 ((RemovedVars=false,var(ESWF) ; % WaitVars guaranteed to be ground
2821 ground(WaitVars)) % TODO: replace this by an optimised version of ground check
2822 -> get_idle_flag(Parameters,WF,LWF),
2823 /* allow all other co-routines waiting on WaitVars to complete */
2824 /* Note however: if WF grounding as triggered two non-deterministic co-routines this
2825 will allow the other non-determinism to run first, duplicating the number of calls !
2826 This has been fixed by storing seperate waitflag variables for same prio in kernel_waitflags
2827 TODO: However, for enumeration of FD variables this might still happen and lead to duplication of
2828 calls to b_enumerate_exists_aux_ground
2829 */
2830 %print(get_idle(Parameters,WaitVars)),nl, %kernel_waitflags:portray_waitflags(WF),nl,nl,
2831 b_enumerate_exists_aux_ground(LWF,WaitVars,Parameters,LocalWF,WF)
2832 ; debug_println(9,semi_lifting_exists(ESWF,Parameters)),
2833 % add_message_wf(exists,'Semi-lifting exists:',Parameters,Parameters,WF),portray_waitflags(LocalWF),nl,
2834 kernel_waitflags:copy_waitflag_store(LocalWF,WF) % outer WF will now drive enumeration
2835 % Note: in case a LET has been moved inside and replaced this may lead to duplication
2836 ).
2837
2838 :- if(environ(prob_safe_mode,true)).
2839 get_idle_flag(Parameters,WF,LWF) :- kernel_waitflags:get_idle_wait_flag(b_enumerate_exists(Parameters),WF,LWF),
2840 (var(LWF) -> true ; add_internal_error('Illegal idle waitflag for exists:',get_idle_flag(Parameters,WF,LWF))).
2841 :- else.
2842 get_idle_flag(Parameters,WF,LWF) :- kernel_waitflags:get_idle_wait_flag(b_enumerate_exists(Parameters),WF,LWF).
2843 :- endif.
2844
2845 :- block b_enumerate_exists_aux_ground(-,?,?,?,?).
2846 b_enumerate_exists_aux_ground(_,_WaitVars,Parameters,LocalWF,_WF) :-
2847 /* Note: this does a local cut: so it is important
2848 that all conditions are fully evaluated before performing the cut ; otherwise
2849 solutions will be lost */
2850 % print_bt_message('ENUMERATE EXISTS'(_Parameters)),nl, % portray_waitflags(_WF),
2851 if(ground_wait_flags_for_exists(Parameters,LocalWF),true,
2852 (perfmessage(exists,late_bound_exists_failed(Parameters),Parameters),fail)).
2853
2854
2855 ground_wait_flags_for_exists(Parameters,LocalWF) :-
2856 \+ enumeration_warning_occured_in_error_scope,
2857 get_current_error_scope(Level),
2858 ? \+ error_manager:throw_error(Level,_,_),
2859 !, % current scope is already clean, no need to enter a fresh one
2860 ground_wait_flags_for_exists2(Parameters,LocalWF,Level).
2861 ground_wait_flags_for_exists(Parameters,LocalWF) :-
2862 enter_new_clean_error_scope(Level),
2863 % Note: see {x|x:1..10 & #y.(y>x & y*y >10)} in test 2210:
2864 % we do not want to throw enum warnings even if the outer scope does in case a solution is found
2865 % NOTE: if this engenders an enumeration warning: it may have been better to enumerate the outer WF first ?! : but as WaitVars are ground, so only failure of outer WF could help us here in preventing enumeration warning
2866 call_cleanup(ground_wait_flags_for_exists2(Parameters,LocalWF,Level),
2867 exit_error_scope(Level,_,ground_wait_flags_for_exists)).
2868
2869 ground_wait_flags_for_exists2(_Parameters,LocalWF,Level) :-
2870 ? (ground_constraintprop_wait_flags(LocalWF)
2871 -> % local cut: one solution is sufficient.
2872 clear_enumeration_warning_in_error_scope(Level)
2873 % ; %print(fail),nl, % do not clear enumeration warnings fail
2874 ).
2875
2876
2877 :- use_module(b_ast_cleanup,[check_used_ids_info/4]).
2878 get_exists_used_ids(Parameters,Condition,Infos,Used) :-
2879 preference(prob_safe_mode,true),!,
2880 ? (select(used_ids(Used),Infos,Rest)
2881 -> check_used_ids_info(Parameters,Condition,Used,exists), %% comment in to check used_ids field
2882 (member(used_ids(_),Rest)
2883 -> add_internal_error('Multiple used_ids info fields:',Parameters:Infos) ; true)
2884 ;
2885 add_internal_error(
2886 'Expected information of used identifiers in exists information',Parameters:Infos),
2887 bsyntaxtree:find_identifier_uses(Condition, [], Used)
2888 ).
2889 get_exists_used_ids(Parameters,Condition,Infos,Used) :-
2890 ? member(used_ids(Used),Infos) -> true
2891 ;
2892 add_internal_error(
2893 'Expected information of used identifiers in exists information',Parameters:Infos),
2894 bsyntaxtree:find_identifier_uses(Condition, [], Used).
2895 % what if we call test_exists for a negated universal quantifier ??
2896
2897
2898
2899
2900 :- use_module(kernel_tools,[ground_state/1]).
2901 /* the following causes performance problems with examples/B/Mathematical/GraphIso/CheckGraphIsomorphism
2902 and with lausanne.mch in SMT mode */
2903 b_not_test_exists(Parameters,Condition,Infos,LocalState,State,_,WF) :-
2904 preferences:preference(use_smt_mode,true),
2905 is_a_conjunct(Condition,LHS,RHS),
2906 (\+ ground_state(LocalState) ; \+ ground_state(State)),
2907 % TO DO: check if any of the variables in Condition are not ground
2908 % TO DO: check if used_ids exist in Infos ? memberchk(used_ids(_),Infos),
2909 !,
2910 %print(translating_not_exists_into_forall),nl,print(' '),print_bexpr(LHS),nl, print('=> '),print_bexpr(RHS),nl,
2911 (is_for_all_set_membership_predicate(RHS,Parameters,_Set,_Pattern,_ParameterValues),
2912 \+ is_for_all_set_membership_predicate(LHS,Parameters,_,_,_)
2913 -> LLHS=RHS, RRHS=LHS % swap LHS and RHS; TO DO: search for membership predicate inside LHS,RHS !!
2914 ; LLHS=LHS, RRHS=RHS
2915 ),
2916 safe_create_texpr(negation(RRHS),pred,NegRHS),
2917 b_for_all(Parameters,Infos,LLHS,NegRHS,LocalState,State,WF).
2918 b_not_test_exists(Parameters,Condition,Infos,[],[],no_compile,WF) :- !,
2919 % already compiled in is_empty_closure_wf
2920 ground_bexpr_check(Condition,Ground),
2921 b_not_test_exists_aux(Ground,Parameters,Condition, Infos, WF).
2922 b_not_test_exists(Parameters,Condition,Infos,LocalState,State,_,WF) :-
2923 % compile to remove dependency on unused parts of State+LocalState; will make it delay less below
2924 def_get_texpr_ids(Parameters,ParaIDs),
2925 %% print(b_not_test_exists(ParaIDs)),nl, print(state(LocalState,State)),nl, %%
2926 ? b_compiler:b_compile(Condition,ParaIDs,LocalState,State,CompiledCond,WF),
2927 (is_truth(CompiledCond) -> fail
2928 ; is_falsity(CompiledCond) -> true
2929 % TO DO: we could detect equalities that will always succeed (but be careful for WD issues)
2930 ; ground_bexpr_check(CompiledCond,Ground),
2931 b_not_test_exists_aux(Ground,Parameters,CompiledCond, Infos, WF)
2932 ).
2933
2934 :- block b_not_test_exists_aux(-,?,?,?,?).
2935 b_not_test_exists_aux(_,Parameters,CompiledCond,Infos,WF) :-
2936 % getting an idle waitflag considerably slows down test 1739; see also ClearSy/2019_Aug/call_residue/rule_erreur.mch
2937 % slow down no longer the case with the new waitflag implementation
2938 kernel_waitflags:get_idle_wait_flag(b_not_test_exists_aux(Parameters),WF,LWF),
2939 % allow pending co-routines to complete
2940 b_not_test_exists_aux2(LWF,Parameters,CompiledCond,Infos,WF).
2941 :- block b_not_test_exists_aux2(-,?,?,?,?).
2942 b_not_test_exists_aux2(_,Parameters,CompiledCond,Infos,WF) :-
2943 % no need to create inner waitflag: we enumerate fully below: create_inner_wait_flags(WF,b_not_test_exists(Parameters),LocalWF),
2944 %init_wait_flags(LocalWF,[expansion_context(b_not_not_test_exists,Parameters)]),
2945 init_quantifier_wait_flag(WF,not(exists),Parameters,ParaResult,Infos,LocalWF),
2946 not_with_enum_warning(
2947 b_interpreter:b_not_not_test_exists_aux(Parameters,ParaResult,CompiledCond,LocalWF),
2948 LocalWF, CompiledCond, % was not_exists(Parameters), the not_exists quantifier call is on call_stack now
2949 CompiledCond),
2950 copy_wfe_from_inner_if_necessary(LocalWF,WF). % for the case that the negated call has found abort errors and WFE was not grounded
2951 b_not_not_test_exists_aux(Parameters,ParaResult,CompiledCond,LocalWF) :-
2952 ? b_interpreter:set_up_typed_localstate(Parameters,ParaResult,TypedVals,[],NewLocalState,negated),
2953 % delay generation of WD error messages until outer WFE flag set
2954 ? b_interpreter:b_test_boolean_expression(CompiledCond,NewLocalState,[],LocalWF), % check Condition
2955 b_tighter_enumerate_values_in_ctxt(TypedVals,CompiledCond,LocalWF),
2956 ? ground_inner_wait_flags(LocalWF). % does not always ground WFE if abort is pending in which case not_with_enum_warning also does not fail and keeps the co-routines
2957 % pending co-routines will be discarded by negation !
2958
2959
2960 /* --------------------------------- */
2961
2962 value_type(_X). % only used in post_conditions (assert_post)
2963 /*
2964 value_type(X) :- nonvar(X),
2965 (X = value(_) ; X = global_set(_) ;
2966 X = global_constant(_) ; X = term(_)).*/
2967
2968
2969 % look up identifiers in store, if the identifier
2970 % is not in the store, assume it's a constant and ignore it
2971 % used for determining wait variables for existential quantifier
2972 % TO DO: better deal with CSE @identifiers ?
2973 lookup_values_if_vars([],_,_,[]).
2974 lookup_values_if_vars([Id|IRest],LocalStore,Store,Values) :-
2975 ( lookup_value(Id,LocalStore,Store,Val)
2976 -> (force_evaluation_of_lazy_value(Id,Val,RealVal)
2977 -> Values = [RealVal|VRest]
2978 ; Values = [Val|VRest])
2979 ; Values = VRest),
2980 lookup_values_if_vars(IRest,LocalStore,Store,VRest).
2981
2982 force_evaluation_of_lazy_value(Id,Value,RealVal) :- nonvar(Value), Value=(Trigger,RealVal),
2983 var(Trigger),
2984 get_preference(use_common_subexpression_elimination,true),
2985 is_lazy_let_identifier(Id),
2986 !,
2987 Trigger=pred_true. % force evaluation, as the exists will otherwise delay/flounder
2988 % Warning: this means that outer lazy_let_expressions inside an exists should be well-defined (WD)
2989
2990
2991 /* will not generate error messages; used for CSP||B when we don't know if something is a B variable or not */
2992 /* TO DO: add peel_prefix for global_sets and constants ?? */
2993 try_lookup_value_in_store_and_global_sets(Id,State,Val) :-
2994 (lookup_value(Id,State,RVal) -> RVal=Val
2995 ; b_global_sets:lookup_global_constant(Id,VGC) -> Val = VGC
2996 ; b_global_set_or_free_type(Id,_AnyType,Value) -> Val=Value /* global set evaluates to itself */
2997 ).
2998
2999
3000 lookup_value_in_store_and_global_sets_wf(Id,Type,LocalState,State,Val,Span,WF) :-
3001 (lookup_value_with_span_wf(Id,LocalState,State,RVal,Span,WF)
3002 -> RVal=Val
3003 ; lookup_value_in_global_sets_wf(Id,Type,Val,LocalState,State,Span,WF)
3004 ).
3005
3006 lookup_value_in_global_sets_wf(Id,Type,Val,LocalState,State,Span,WF) :-
3007 (b_global_sets:lookup_global_constant(Id,VGC)
3008 -> Val=VGC
3009 ? ; (b_global_set_or_free_type(Id,Type,Value)
3010 -> Val = Value /* global set evaluates to itself */
3011 ; ((member(bind(Id,_),LocalState) ; member(bind(Id,_),State))
3012 -> Msg1 = 'Cannot determine value for identifier '
3013 ; Msg1 = 'Cannot find identifier '
3014 ),
3015 append(LocalState,State,LSS),
3016 translate:translate_bstate_limited(LSS,StateInfo),
3017 ajoin([Msg1,Id,':'],Msg),
3018 add_error_wf(identifier_not_found,Msg,StateInfo,Span,WF),
3019 fail % Val = term(Id) /* Val=fail */
3020 )
3021 ).
3022
3023 :- use_module(probsrc(kernel_freetypes),[registered_freetype/2, registered_freetype_case_value/3]).
3024 ?b_global_set_or_free_type(Id,_,global_set(Id)) :- b_global_set(Id).
3025 b_global_set_or_free_type(Id,_,freetype(Id)) :- registered_freetype(Id,_).
3026 b_global_set_or_free_type(Id,Type,Value) :-
3027 registered_freetype_case_value(Id,Type,Value). % to instantiate the type parameters we also need the TypeId
3028 % TODO: we could also register Event-B destructors and look them up here
3029
3030 /* -----------------------------*/
3031 /* b_compute_expressions */
3032 /* -----------------------------*/
3033
3034 b_compute_expressions([], _, _, [],_WF).
3035 b_compute_expressions([EXPRsHd|EXPRsTl],LocalState,InState,[ValHd|ValTl],WF) :-
3036 ? b_compute_expression(EXPRsHd,LocalState,InState,ValHd,WF),
3037 ? b_compute_expressions(EXPRsTl,LocalState,InState,ValTl,WF).
3038
3039 % a variation of above that delays computing the expressions until Waitflag 1/2 is set
3040 b_compute_assign_expressions_when(EXPRsTl,LocalState,InState,ValTl,WF,OR) :-
3041 get_assign_expr_priority_wf(OR,WF,LWF),
3042 ? b_compute_expressions_when2(EXPRsTl,LocalState,InState,ValTl,WF,LWF).
3043 b_compute_expressions_when2([], _, _, [],_WF,_).
3044 b_compute_expressions_when2([EXPRsHd|EXPRsTl],LocalState,InState,[ValHd|ValTl],WF,LWF) :-
3045 ? b_compute_expression_when2(EXPRsHd,LocalState,InState,ValHd,WF,LWF),
3046 b_compute_expressions_when2(EXPRsTl,LocalState,InState,ValTl,WF,LWF).
3047
3048 % TO DO: add step number in OR
3049 get_assign_expr_priority_wf(output_required,_WF,LWF) :- !,
3050 % the Output of the statement is required; do not delay computing it
3051 LWF=0. % this would delay computation until WF0 is set: get_wait_flag0(WF,LWF); cf. initialisation for test 2104
3052 get_assign_expr_priority_wf(_,WF,LWF) :-
3053 % the Output is not directly required; compute it later (when we are sure that the statement actually succeeds)
3054 (preferences:preference(use_smt_mode,true)
3055 -> Prio = 2.0 % SMT Mode: we are probably doing CBC checking, we may have set up constraints on ValTl
3056 ; Prio=4000), % unless the expression is inside an sequential composition: nothing can depend on ValTl; TO DO: check if we are inside a sequential composition; if not use inf priority; otherwise use 2.0 or 4
3057 get_wait_flag(Prio,get_assign_expr_priority_wf,WF,LWF).
3058
3059 :- block b_compute_expression_when2(?,?,?,?,?,-).
3060 b_compute_expression_when2(eval_must_not_fail(ErrMsg,EXPRsHd),LocalState,InState,Res,WF,_) :- !,
3061 % catch failure; in case the interpreter fails to catch wd-error itself (e.g., try_find_abort is false)
3062 if(b_compute_expression(EXPRsHd,LocalState,InState,ValHd,WF),equal_object_wf(ValHd,Res,WF),
3063 (translate:translate_bexpression_with_limit(EXPRsHd,TS),
3064 add_wd_error_span(ErrMsg,TS,span_predicate(EXPRsHd,LocalState,InState),WF))).
3065 b_compute_expression_when2(EXPRsHd,LocalState,InState,ValHd,WF,_) :-
3066 copy_wf_start(WF,b_compute_expression_when2,CWF), % not sure this is useful for expressions:
3067 ? b_compute_expression(EXPRsHd,LocalState,InState,ValHd,CWF),
3068 ? copy_wf_finish(WF,CWF).
3069
3070
3071 /* -----------------------------*/
3072 /* b_execute_statement */
3073 /* -----------------------------*/
3074 /* b_execute_statement(XMLStatements:input, StateofLocalVariables:input,
3075 StateOfGlobalVariables:input,
3076 ListOfUpdateBindingsForGlobalVariablesAndResultVariables:output) */
3077
3078 :- assert_pre(b_interpreter:b_execute_statement(Stmt,LS,IS,_OS,_WF,_Path,_OR),
3079 (bsyntaxtree:check_if_typed_substitution(Stmt),type_check(LS,store),type_check(IS,store) )).
3080 :- assert_post(b_interpreter:b_execute_statement(_Stmt,_LS,_IS,OS,_WF,_Path,_OR),
3081 (type_check(OS,store))).
3082
3083 b_execute_inner_statement(Body,LocalState,InState,OutState,WF,Path,output_required) :-
3084 get_texpr_expr(Body,BE),
3085 BE \= while(_COND,_STMT,_INV,_VARIANT), % also other non-det substitutions ??
3086 BE \= select(_),
3087 BE \= select(_,_),
3088 BE \= if(_), % case(_,_,_) statements are now translated to if-then-else in ast_cleanup
3089 !,
3090 get_wait_flag0(WF,WF0),
3091 block_execute_statement(WF0,Body,LocalState,InState,OutState,WF,Path).
3092 b_execute_inner_statement(Body,LocalState,InState,OutState,WF,Path,OR) :-
3093 get_wait_flag(2,inner_stmt,WF,LWF), % was 2.0
3094 clone_wait_flags_from1(WF,GroundUponFinish,InnerWF), % copy everything but WF0
3095 b_execute_inner_statement(Body,LocalState,InState,OutState,GroundUponFinish,InnerWF,Path,LWF,OR).
3096
3097 :- block block_execute_statement(-, ?,?,?, ?,?,?).
3098 block_execute_statement(_,Body,LocalState,InState,OutState,WF,Path) :-
3099 ? b_execute_statement(Body,LocalState,InState,OutState,WF,Path,output_required).
3100
3101 :- block b_execute_inner_statement(?,?,?,?,?,?,?,-,?).
3102 b_execute_inner_statement(Body,LocalState,InState,OutState,GUF,InnerWF,Path,_,OR) :-
3103 ? b_execute_statement(Body,LocalState,InState,OutState,InnerWF,Path,OR),
3104 (GUF=ground_upon_finish -> ground_wait_flags(InnerWF) ; ground_wait_flag0(InnerWF)).
3105
3106 :- use_module(source_profiler,[opt_add_source_location_hits/2]).
3107
3108 b_execute_statement(Stmt, LS, S, OS, WF,Path) :-
3109 ? b_execute_statement(Stmt, LS, S, OS, WF,Path,output_not_required).
3110 b_execute_statement(b(Stmt,_,Infos), LS, S, OS, WF,Path,OR) :- !,
3111 ? b_execute_statement2(Stmt, Infos, LS, S, OS, WF,Path,OR).
3112 b_execute_statement(Stmt, LS, S, OS, WF,Path,OR) :-
3113 add_internal_error('Statement not properly wrapped: ',b_execute_statement(Stmt, LS, S, OS, WF,Path,OR)),
3114 b_execute_statement2(Stmt, [], LS, S, OS, WF,Path,OR).
3115
3116 % blocks should be removed by type-checker
3117 b_execute_statement2(block(Stmt),_,LS,IS,OS,WF,Path,OR) :- !,
3118 b_execute_statement(Stmt,LS,IS,OS,WF,Path,OR). %% NOT COVERED
3119 b_execute_statement2(assign(LHS,Exprs),Info,LocalState,InState,OutState,WF,assign,OR) :- !,
3120 /* Var1, ..., VarN := Expr1, ..., ExprN */
3121 /* also: Var1, fun1(arg), ... := Expr1, Expr2, ... */
3122 opt_add_source_location_hits(Info,1),
3123 ? b_compute_assign_expressions_when(Exprs,LocalState,InState,VALs,WF,OR),% VALs - a list of computed values
3124 ? b_assign_values_or_functions(LHS,VALs,LocalState,InState,OutState,WF,OR).
3125 b_execute_statement2(assign_single_id(IDE,Expr),Info,LocalState,InState,OutState,WF,assign,_OR) :-
3126 get_texpr_id(IDE,ID),!,
3127 opt_add_source_location_hits(Info,1),
3128 ? b_compute_expression(Expr,LocalState,InState,Value,WF), % b_compute_assign_expressions_when
3129 %b_compute_assign_expressions_when([Expr],LocalState,InState,[Value],WF),
3130 OutState=[bind(ID,Value)].
3131 b_execute_statement2(choice(ChoiceList),_,LocalState,InState,OutState,WF,Path,OR) :- !,
3132 /* CHOICE LHS OR RHS OR ... END */
3133 get_wait_flag(2,choice,WF,WFC), % % was 2.0, maybe use length of ChoiceList as Priority ??
3134 b_execute_choice(ChoiceList,LocalState,InState,OutState,WF,Path,WFC,OR).
3135 b_execute_statement2(becomes_element_of(LHS,RHS), /* LHS :: RHS */
3136 Info,LocalState,InState,OutState,WF,becomes_element_of,_OR) :- !,
3137 % LHS must be of the form Var1,..,Vark where all variables are disjoint
3138 opt_add_source_location_hits(Info,1),
3139 b_compute_expression(RHS,LocalState,InState,ValueSet,WF),
3140 check_element_of_wf(SingleValue,ValueSet,WF),
3141 ground_det_wait_flag(WF), %% TODO: remove this
3142 convert_pairs_into_list(LHS,SingleValue,ValList),
3143 set_up_typed_localstate(LHS,ValList,TypedVals,[],OutState,positive),
3144 b_tighter_enumerate_all_values(TypedVals,WF).
3145 b_execute_statement2(becomes_such(Vars,Condition), /* Vars : Condition */
3146 Info,LocalState,InState,OutState,WF,becomes_such,_OR) :- !,
3147 opt_add_source_location_hits(Info,1),
3148 ? b_execute_becomes_such(Vars,Condition,LocalState,InState,OutState,_,WF).
3149 b_execute_statement2(sequence(Seq), /* LHS ; RHS */
3150 _,LocalState,InState,OutUpdates,WF,Path,OR) :- !, %pe_print(sequence(Seq,InState)),
3151 ? b_execute_sequence(Seq,LocalState,InState,OutUpdates,WF,Path,OR).
3152 b_execute_statement2(precondition(PreCond,Body),_,LocalState,InState,OutState,WF,Path,OR) :- !,
3153 %print('*** Non-outermost PRE construct'),nl,
3154 Path=pre(PreRes,IPath),
3155 b_try_check_boolean_expression(PreCond,LocalState,InState,WF,PreRes),
3156 %used to be: ground_det_wait_flag(WF),
3157 check_precondition_result(PreRes,PreCond,LocalState,InState,WF),
3158 ? (PreRes == pred_true -> b_execute_statement(Body,LocalState,InState,OutState,WF,IPath,OR)
3159 ; PreRes == pred_false -> IPath = not_executed
3160 ; b_execute_inner_statement(Body,LocalState,InState,OutState,WF,IPath,OR) % with extra waitflag
3161 ).
3162 b_execute_statement2(assertion(PreCond,Body),_,LocalState,InState,OutState,WF,Path,OR) :- !,
3163 ? b_execute_assertion(PreCond,Body,LocalState,InState,OutState,WF,Path,OR).
3164 b_execute_statement2(select(Whens),_, LocalState, InState, OutState,WF,select(Nr,Path),OR) :- !,
3165 get_texpr_expr(TExpr,select_when(PreCond, Body)), % info field not used for select_when
3166 ? optimized_nth1(Nr, Whens, TExpr), % THIS IS A CHOICE POINT if length(Whens)>1 ! <-------- TO DO guard
3167 ? b_test_boolean_expression(PreCond,LocalState,InState,WF),
3168 %used to call: ground_det_wait_flag(WF), now execute inner statement delays
3169 b_execute_inner_statement(Body,LocalState,InState,OutState,WF,Path,OR).
3170 b_execute_statement2(select(Whens,Else), Infos, LocalState, InState, OutState,WF,Path,OR) :- !,
3171 (
3172 ? b_execute_statement2(select(Whens), Infos, LocalState, InState, OutState,WF,Path,OR)
3173 ; % THIS IS A CHOICE POINT ! <-------- TO DO guard
3174 findall(PC,
3175 (member(SW,Whens),get_texpr_expr(SW,select_when(PC,_))), AllPreconds),
3176 b_not_test_list_of_boolean_expression(AllPreconds,LocalState,InState,WF),
3177 Path = select(else,IPath),
3178 b_execute_inner_statement(Else,LocalState,InState,OutState,WF,IPath,OR)
3179 ).
3180 b_execute_statement2(var(Parameters,Body), /* VAR _ IN _ substitution */
3181 _,LocalState,InState,NewOutState,WF,var(Path),OR) :- !,
3182 /* introduces a new variable that can be assigned to */
3183 split_names_and_types(Parameters,Names,_),
3184 delete_variables_from_state(Names,InState,InState1), % in case any local parameter name is also a constant/variable: remove it % but if we do an operation_call: we leave context and it becomes visible again !!
3185 % otherwise we may think there are two updates, e.g., in WHILE loop; see Rule_DB_SIGAREA_0030 from test 1303
3186 set_up_undefined_localstate(Parameters,InState1,NewInState),
3187 delete_variables_from_state(Names,LocalState,NewLocalState),
3188 %check_valid_store(InState,var_in_state), check_valid_store(LocalState,var_local_state),
3189 ? b_execute_statement(Body,NewLocalState,NewInState,OutState,WF,Path,OR),
3190 % check_valid_store(OutState,var_out_state),
3191 filter_results(Parameters,OutState,NewOutState,WF)
3192 .
3193 /* it can be ok not to assign to a local variable */
3194
3195 %TODO(DP, 5.8.2008):
3196 b_execute_statement2(let(Parameters,Defs,Body), /* LET _ BE _ IN _ */
3197 _,LocalState,InState,OutState,WF,let(Path),OR) :- !,
3198 ? set_up_typed_localstate(Parameters,LocalState,NewLocalState),
3199 b_execute_let_definitions(Defs,NewLocalState,InState,WF),
3200 ? b_execute_statement(Body,NewLocalState,InState,OutState,WF,Path,OR).
3201 b_execute_statement2(lazy_let_subst(Id,IdExpr,Body),_,LocalState,InState,OutState,WF,lazy_let(Path),OR) :-
3202 !,
3203 add_lazy_let_id_and_expression(Id,IdExpr,LocalState,InState,NewLocalState,WF),
3204 b_execute_statement(Body,NewLocalState,InState,OutState,WF,Path,OR).
3205 b_execute_statement2(any(Parameters,PreCond,Body), /* ANY _ WHERE */
3206 Info,LocalState,InState,OutState,WF0,any(Bindings,Path),OR) :- !, %statistics(runtime,_),
3207 %print('ANY: '), print_bexpr(PreCond),nl, %%
3208 ? set_up_typed_localstate(Parameters,FreshVars,TypedVals,LocalState,NewLocalState,positive),
3209 create_any_bindings(Parameters,FreshVars,Bindings),
3210 push_wait_flag_call_stack_info(WF0,quantifier_call('ANY',Parameters,FreshVars,Info),WF),
3211 ? b_test_inner_boolean_expression(PreCond,NewLocalState,InState,WF), /* check WHERE */
3212 %%observe_state(TypedVals,WF,0), b_tracetest_boolean_expression(PreCond,NewLocalState,InState,WF,one), %% comment in for debugging
3213 b_tighter_enumerate_all_values(TypedVals,WF), % moved enumeration after test; in case WF already instantiated
3214 %TODO: check if we can use b_tighter_enumerate_values_in_ctxt
3215 ? b_execute_statement(Body,NewLocalState,InState,OutState,WF,Path,OR). /* should we use b_execute_inner_statement/LWF here ?? */
3216 b_execute_statement2(skip, /* SKIP */
3217 Info,_LocalState,_InState,OutState,_WF,skip,_OR) :- !,
3218 opt_add_source_location_hits(Info,1),
3219 OutState = [].
3220 b_execute_statement2(parallel(Statements), /* LHS || RHS */ %@@@
3221 _,LocalState,InState,OutState,WF,parallel(Paths),OR) :- !,
3222 ? b_execute_statements_in_parallel(Statements,LocalState,InState,OutState,WF,Paths,OR).
3223 b_execute_statement2(init_statement(Stmt),_,LocalState,InState,OutState,WF,Path,OR) :- !,
3224 /* Like block: but
3225 writes error messages if statement fails */ %@@@
3226 (preferences:get_preference(provide_trace_information,true)
3227 -> nl,print(' =INIT=> '),translate:print_subst(Stmt),nl, flush_output(user_output),
3228 statistics(walltime,[Tot1,_])
3229 ; true),
3230 ? if(b_execute_initialisation_statement(Stmt,LocalState,InState,OutState,WF,Path,OR),
3231 (
3232 (preferences:get_preference(provide_trace_information,true)
3233 -> statistics(walltime,[Tot2,_]), Tot is Tot2-Tot1,
3234 format(' [=OK= ~w ms]~n',[Tot]), flush_output(user_output)
3235 ; true)
3236 ),
3237 (translate:translate_substitution(Stmt,TStmt),
3238 (bmachine:b_machine_temp_predicate(_)
3239 -> add_message_wf(initialisation_fails,'Initialisation statement cannot be executed with extra predicate: ',TStmt,Stmt,WF)
3240 ; add_error_wf(initialisation_fails,'Initialisation statement fails: ',TStmt,Stmt,WF)
3241 ), fail
3242 )
3243 ).
3244 b_execute_statement2(if(IfList),_,LocalState,InState,OutState,WF,if,OR) :- !,
3245 %LWF=1,
3246 LWF='$GENERATE_ON_DEMAND', %
3247 ? b_execute_else_list(IfList,LocalState,InState,OutState,WF,LWF,OR).
3248 b_execute_statement2(operation_call(Operation,Results,Parameters),Info,LocalState,InState,OutState,WF,
3249 operation_call(OperationName,ParamValues,ResultValues,InnerPath),OR) :- !,
3250 def_get_texpr_id(Operation,op(OperationName)),
3251 ? b_execute_operation_with_parameters(OperationName,LocalState,InState,Results,
3252 Parameters,OpOutState,ParamValues,ResultValues,InnerPath,Info,WF,OR),
3253 split_names_and_types(Results,ResultingIDs,_),
3254 store_values(ResultingIDs, ResultValues, ResultsOutState),
3255 combine_updates(ResultsOutState,OpOutState,OutState).
3256
3257 b_execute_statement2(while(COND,STMT,INV,VARIANT),
3258 Info,LocalState,InState,OutState,WF0,while,_OR) :- !,
3259 %hit_profiler:add_profile_hit(while(COND,WF),2),
3260 % we may go around the loop many times: avoid carrying around unused variables
3261 get_while_reads_write_info_and_filter_state(Info,LocalState,InState,LS,IS,ModVars),
3262 push_wait_flag_call_stack_info(WF0,b_operator_call('WHILE',[],Info),WF), % TODO: provide subst. call stack entry
3263 %print_message(execute_while(LocalState,InState)),
3264 b_compiler:b_optimize(INV,ModVars,LS,IS,CINV,WF),
3265 b_compiler:b_optimize(COND,ModVars,LS,IS,CCOND,WF),
3266 b_compiler:b_optimize(VARIANT,ModVars,LS,IS,CVARIANT,WF),
3267 %,b_compiler:b_compile(STMT,ModVars,LS,IS,CSTMT,WF)
3268 % TO DO: maybe exclude in one go; use ordered approach ?
3269 %exclude(unused_variable(ModVars),LS,LS2), % only keep modified vars; all other compiled
3270 %exclude(unused_variable(ModVars),IS,IS2), % only keep modified vars; all other compiled
3271 b_compute_expression(CVARIANT,LS,IS,VarVal,WF),
3272 b_execute_while(CCOND,STMT,CINV,CVARIANT,ModVars,VarVal,LS,IS,OutState,WF).
3273 b_execute_statement2(external_subst_call(FunName,Args),Info,LocalState,State,OutState,WF,external(FunName),_OR) :-
3274 !, b_compute_expressions(Args, LocalState,State, EvaluatedArgs, WF),
3275 push_wait_flag_call_stack_info(WF,external_call(FunName,EvaluatedArgs,Info),WF2),
3276 call_external_substitution(FunName,EvaluatedArgs,State,OutState,Info,WF2).
3277 b_execute_statement2(E,I,LS,S,O,WF,Path,OR) :-
3278 add_internal_error('Uncovered statement: ',b_execute_statement2(E,I,LS,S,O,WF,Path,OR)),
3279 print_functor(E),nl,fail.
3280
3281 % -------------------
3282
3283 b_execute_becomes_such(Vars,Condition,LocalState,InState,OutState,Values,WF) :- !,
3284 % create the LHS variables in the local state
3285 ? set_up_typed_localstate(Vars,Values,TypedVals,LocalState,TempLocalState1,positive),
3286 get_texpr_ids(Vars,Ids),
3287 % store those values also the outgoing state
3288 store_values(Ids,Values,OutState),
3289 % there might be some variables of the form x$0 to access the
3290 % values before the substitution. We put them into the local state
3291 insert_before_substitution_variables(Vars,LocalState,InState,TempLocalState1,TempLocalState),
3292 ? b_test_inner_boolean_expression(Condition,TempLocalState,InState,WF),
3293 b_tighter_enumerate_values_in_ctxt(TypedVals,Condition,WF). % moved enumeration after test, to avoid overhead in case Condition is deterministic (see e.g. WhileAssignTupleChoose_v2)
3294
3295
3296 b_execute_sequence([],_LocalState,_InState,[],_WF,[],_OR).
3297 b_execute_sequence([First|Rest],LocalState,InState,OutUpdates,WF,Path,OR) :-
3298 (Rest == []
3299 ? -> b_execute_statement(First,LocalState,InState,OutUpdates,WF,Path,OR)
3300 ; Path = sequence(Path1,RestPath),
3301 ? b_execute_statement(First,LocalState,InState,LHSUpdates,WF,Path1,output_required),
3302 ? ground_det_wait_flag(WF), % maybe better to delay next execute_statement ? TODO
3303 store_intermediate_updates_wf(InState,LHSUpdates,IntermediateState,First,WF),
3304 % TO DO: statically determine what the Rest can modify and copy over LHSUpdates not modified by Rest into OutUpdates
3305 ? b_execute_statement_list_when_state_set(Rest,LocalState,IntermediateState,
3306 LHSUpdates,OutUpdates,WF,RestPath,OR)
3307 ).
3308
3309
3310 :- block check_precondition_result(-,?,?,?,?).
3311 check_precondition_result(pred_true,_,_,_,_).
3312 check_precondition_result(pred_false,PreCond,LS,S,WF) :-
3313 translate_bexpression(PreCond,PreString),
3314 add_abort_error_span(precondition_error,'Precondition violated: ',PreString,span_predicate(PreCond,LS,S),WF).
3315
3316 create_any_bindings([],[],[]).
3317 create_any_bindings([Param|Prest],[Value|Vrest],[bind(Id,Value)|Brest]) :-
3318 get_texpr_id(Param,Id),
3319 create_any_bindings(Prest,Vrest,Brest).
3320
3321 % insert the values of variables before the substitution under an
3322 % alternative name. The alternative name is given as an optional extra
3323 % information in the variable (see type-checking of becomes_such for
3324 % details). Usually (i.e. always) the alternative name is x$0 for the variable x.
3325 insert_before_substitution_variables([],_LocalState,_InState,State,State).
3326 insert_before_substitution_variables([Var|VRest],LocalState,InState,StateA,ResultStateB) :-
3327 get_texpr_info(Var,Infos),
3328 ? ( member(before_substitution(_,Alternative),Infos) ->
3329 def_get_texpr_id(Var,Id),
3330 lookup_value_for_existing_id(Id,LocalState,InState,Value),
3331 store_value(Alternative,Value,StateA,StateC)
3332 ;
3333 StateA = StateC),
3334 insert_before_substitution_variables(VRest,LocalState,InState,StateC,ResultStateB).
3335
3336
3337
3338 % treat the bool(.) operator
3339 b_convert_bool(Pred,LocalState,State,WF,PredRes) :-
3340 get_wait_flag0(WF,WF0), % first give a chance for PredRes to be instantiated
3341 ? b_convert_bool_wf0(Pred,LocalState,State,WF,PredRes,WF0).
3342
3343 :- block b_convert_bool_wf0(?,?,?,?,-,-).
3344 b_convert_bool_wf0(Pred,LocalState,State,WF,PredRes,_) :- PredRes==pred_true,!,
3345 %% print('bool(.)=TRUE '), translate:print_bexpr(Pred),nl, %%
3346 b_test_inner_boolean_expression(Pred,LocalState,State,WF).
3347 b_convert_bool_wf0(Pred,LocalState,State,WF,PredRes,_) :- PredRes==pred_false,!,
3348 %% print('bool(.)=FALSE '), translate:print_bexpr(Pred),nl, %%
3349 b_not_test_inner_boolean_expression(Pred,LocalState,State,WF).
3350 b_convert_bool_wf0(Pred,LocalState,State,WF,PredRes,_) :-
3351 %% print('bool(.) check : '), translate:print_bexpr(Pred),nl, % obsv(LocalState),
3352 ? b_try_check_boolean_expression_wf(Pred,LocalState,State,WF,PredRes ).
3353 %% print('finished bool(.) check : '), translate:print_bexpr(Pred),nl,translate:print_bstate(LocalState),nl.
3354
3355 % Additional time limit +TO in ms, e.g., used for CDCL(T). +TORes is time_out if a timeout occurred.
3356 b_convert_bool_timeout(Pred,LocalState,State,WF,PredRes,TO,TORes) :-
3357 get_wait_flag0(WF,WF0),
3358 b_convert_bool_wf0_timeout(Pred,LocalState,State,WF,PredRes,WF0,TO,TORes).
3359
3360 :- block b_convert_bool_wf0_timeout(?,?,?,?,-,-,?,?).
3361 b_convert_bool_wf0_timeout(Pred,LocalState,State,WF,PredRes,_,TO,TORes) :-
3362 PredRes == pred_true,
3363 !,
3364 safe_time_out(b_test_inner_boolean_expression(Pred,LocalState,State,WF),
3365 TO,
3366 TORes).
3367 b_convert_bool_wf0_timeout(Pred,LocalState,State,WF,PredRes,_,TO,TORes) :-
3368 PredRes == pred_false,
3369 !,
3370 safe_time_out(b_not_test_inner_boolean_expression(Pred,LocalState,State,WF),
3371 TO,
3372 TORes).
3373 b_convert_bool_wf0_timeout(Pred,LocalState,State,WF,PredRes,_,TO,TORes) :-
3374 safe_time_out(b_try_check_boolean_expression_wf(Pred,LocalState,State,WF,PredRes ),
3375 TO,
3376 TORes).
3377
3378 %%obsv([]).
3379 %%obsv([bind(Var,Val) | T] ) :- when(ground(Val), format("~w = ~w~n",[Var,Val])), obsv(T).
3380
3381 % check boolean expression without enumeration predicate result (unless WFE is set)
3382 b_try_check_boolean_expression_no_enum_wf(Pred,LocalState,State,WF,PredRes) :-
3383 ? b_try_check_boolean_expression_lwf(Pred,LocalState,State,WF,'$NO_ENUMERATION',PredRes,_).
3384
3385 b_try_check_boolean_expression_wf(Pred,LocalState,State,WF,PredRes) :-
3386 ? b_try_check_boolean_expression_lwf(Pred,LocalState,State,WF,'$ENUMERATION',PredRes,'$GENERATE_ON_DEMAND' ).
3387 % try to do check_boolean expression; if not possible create choice point if LWF is grounded
3388 b_try_check_boolean_expression_lwf(Pred,LocalState,InState,WF,DoEnumeration,PredRes,LWF) :-
3389 ? b_compiler:b_optimize(Pred,[],LocalState,InState,CPRED,WF), % this increases chance that check can be applied+avoids multiple computations in two branches
3390 % still: some computations may not be pre-computed, e.g., union of closures, ..., see Rule_DB_PSR_0003_C
3391 ? b_try_check_boolean_expression_lwf_c(CPRED,LocalState,InState,WF,DoEnumeration,PredRes,LWF).
3392
3393 b_try_check_boolean_expression_lwf_c(b(truth,_,_),_LocalState,_InState,_WF,_,PredRes,_LWF) :- !,
3394 % typical case in e.g. IF-THEN-ELSE
3395 PredRes= pred_true.
3396 b_try_check_boolean_expression_lwf_c(Pred,LocalState,InState,WF,DoEnumeration,PredRes,LWF) :-
3397 copy_wf_start(WF,try_check,CWF),
3398 ? if(b_check_boolean_expression_with_enum(Pred,LocalState,InState,CWF,DoEnumeration,Res),
3399 % Note: we do not use a cut here ! usually b_check will not enumerate; but on rare occasions it can (apply function in inverse,...)
3400 (PredRes=Res,
3401 ? copy_wf_finish(WF,CWF)
3402 ),
3403 b_try_check_failed(Pred,LocalState,InState,WF,DoEnumeration,PredRes,LWF)
3404 ).
3405 b_try_check_failed(Pred,LocalState,InState,WF,DoEnumeration,PredRes,LWF) :-
3406 % print(choice_point(LWF)),nl, translate:print_bexpr(Pred),nl,
3407 perfmessagecall(choice_point,reification_of_check_predicate_failed,translate:print_bexpr(Pred),Pred),
3408 (LWF=='$GENERATE_ON_DEMAND' -> get_binary_choice_wait_flag('$GENERATE_ON_DEMAND',WF,WF1)
3409 ; var(LWF),DoEnumeration=='$NO_ENUMERATION' -> get_enumeration_finished_wait_flag(WF,WF1) % nothing will enum LWF
3410 ; WF1=LWF),
3411 b_try_check_boolean_expression_lwf_block(Pred,LocalState,InState,WF,PredRes,WF1).
3412
3413 % a version of b_check_boolean_expression which will enumerate its result as last resort
3414 % should we only do this in SMT mode : preferences:preference(use_smt_mode,true) ?
3415 b_check_boolean_expression_with_enum(Pred,LocalState,State,WF,DoEnumeration,Res) :-
3416 ? b_check_boolean_expression(Pred,LocalState,State,WF,Res),
3417 (nonvar(Res) -> true
3418 ; DoEnumeration=='$NO_ENUMERATION' -> get_enumeration_finished_wait_flag(WF,EWF), enum_pred_result(Res,EWF,WF)
3419 ; get_wait_flag0(WF,LWF0),
3420 enum_pred_result0(Res,LWF0,WF)).
3421
3422 % first set up with wait_flag0: easy to get, avoid putting unnecessary waitflags into store
3423 % relevant for DataValidationTest.mch with n>20000
3424 :- block enum_pred_result0(-,-,?).
3425 enum_pred_result0(Res,_,WF) :- var(Res),!,
3426 get_last_wait_flag(b_check_boolean_expression_with_enum,WF,LWF),
3427 enum_pred_result(Res,LWF,WF). % before doing infinite enumerations: better do case-distinction here
3428 enum_pred_result0(_,_,_).
3429
3430 :- block enum_pred_result(-,-,?).
3431 enum_pred_result(pred_true,_,_).
3432 enum_pred_result(pred_false,_,_).
3433
3434 :- block b_try_check_boolean_expression_lwf_block(?,?,?, ?,-,-).
3435 b_try_check_boolean_expression_lwf_block(Pred,LocalState,InState,WF,PREDRES,_) :-
3436 PREDRES \== pred_false,
3437 % print(' TRUE +++++> '), translate:print_bexpr(Pred),nl,
3438 ? b_test_inner_boolean_expression(Pred,LocalState,InState,WF),
3439 PREDRES = pred_true. % set it only after we have actually checked the predicate; e.g., for IF we may execute rest of while loop etc... before actually having set up the constraint Pred; See Hansen23_WhilePerformance
3440 b_try_check_boolean_expression_lwf_block(Pred,LocalState,InState,WF,PREDRES,_) :-
3441 PREDRES \== pred_true,
3442 % print(' FALSE +++++> '), translate:print_bexpr(Pred),nl,
3443 ? b_not_test_inner_boolean_expression(Pred,LocalState,InState,WF),
3444 PREDRES = pred_false.
3445
3446 % try to do check_boolean expression; if not possible create choice point *directly*
3447 b_try_check_boolean_expression(Pred,LocalState,InState,WF,PredRes) :-
3448 b_compiler:b_optimize(Pred,[],LocalState,InState,CPRED,WF), % this increases chance that check can be applied+avoids multiple computations in two branches
3449 b_try_check_boolean_expression_c(CPRED,LocalState,InState,WF,PredRes).
3450 b_try_check_boolean_expression_c(Pred,LocalState,InState,WF,PredRes) :-
3451 copy_wf_start(WF,try_check_c,CWF),
3452 if(b_check_boolean_expression(Pred,LocalState,InState,CWF,Res),
3453 (PredRes=Res,copy_wf_finish(WF,CWF)),
3454 ? b_try_check_boolean_expression_c2(Pred,LocalState,InState,WF,PredRes)
3455 ).
3456 b_try_check_boolean_expression_c2(Pred,LocalState,InState,WF,pred_true) :-
3457 %hit_profiler:add_profile_hit(b_try_check_failed(Pred),3),
3458 b_test_inner_boolean_expression(Pred,LocalState,InState,WF).
3459 b_try_check_boolean_expression_c2(Pred,LocalState,InState,WF,pred_false) :-
3460 b_not_test_inner_boolean_expression(Pred,LocalState,InState,WF).
3461
3462
3463 % WHILE SUBSTITUTION TREATMENT:
3464
3465 :- if(environ(prob_noopt_mode,true)).
3466 get_while_reads_write_info_and_filter_state(Info,LocalState,InState,LS,IS,ModVars) :-
3467 member(modifies(ModVars),Info),!,
3468 LS=LocalState, IS=InState. % do not filter state
3469 :- endif.
3470 get_while_reads_write_info_and_filter_state(Info,LocalState,InState,LS,IS,ModVars) :-
3471 ? member(reads(ReadVars),Info),
3472 ? member(modifies(ModVars),Info),!,
3473 % we may go around the loop many times: avoid carrying around unused variables
3474 ord_union(ReadVars,ModVars,ReadOrModVars),
3475 filter_states(ReadOrModVars,LocalState,InState,LS,IS).
3476 get_while_reads_write_info_and_filter_state(Info,LocalState,InState,LS,IS,ModVars) :-
3477 add_internal_error('No reads & modifies info for while loop: ',get_while_reads_write_info_and_filter_state(Info,LocalState,InState,LS,IS,ModVars)),
3478 ModVars=_, % all variables assumed to be modified
3479 LS=LocalState, IS=InState.
3480
3481 unused_variable(List,bind(Var,_)) :-
3482 % b_is_variable(Var), % TO DO: also include constants in reads Info ?
3483 ord_nonmember(Var,List).
3484 unused_localvariable(List,bind(Var,Val)) :- ord_nonmember(Var,List),
3485 (nonvar(Val),Val=(_,_) -> atom_codes(Var,Codes), Codes \= [64|_] % not a lazy_let ID starting with @
3486 % TO DO: either ensure lazy-let ids are also included in reads/writes ! or mark Val not as pair but using a special functor in add_lazy_let_id_to_local_state ?
3487 ; true).
3488
3489 filter_states(ReadOrModVars,LocalState,InState,LS,IS) :-
3490 exclude(unused_localvariable(ReadOrModVars),LocalState,LS),
3491 exclude(unused_variable(ReadOrModVars),InState,IS).
3492 % TO DO: investigate whether we should use ord_intersect; ReadVars is already sorted
3493
3494 :- block lazy_exclude(-,?,?).
3495 lazy_exclude([],_,[]).
3496 lazy_exclude([bind(Var,Val)|T],ModVars,Res) :- lazy_exclude_aux(Var,Val,T,ModVars,Res).
3497 :- block lazy_exclude_aux(-,?,?,?,?).
3498 lazy_exclude_aux(Var,Val,T,ModVars,Res) :-
3499 ? (member(Var,ModVars) -> Res = [bind(Var,Val)|RT]
3500 ; Res = RT),
3501 lazy_exclude(T,ModVars,RT).
3502
3503
3504 :- use_module(kernel_tools,[ground_state_check/2]).
3505 % outermost while code:; at next iteration b_execute_while1 will be called.
3506 :- block b_execute_while(?,?,?,?,?,-, ?,?,?, ?). % we block on Variant Value int(VarVal)
3507 b_execute_while(COND,STMT,INV,VARIANT,ModVars,int(VarVal),LocalState,InState,OutState,WF) :-
3508 %kernel_waitflags:get_idle_wait_flag(b_execute_while,WF,LWF),
3509 (number(VarVal),VarVal =< 50
3510 -> LWF=VarVal % we will wait anyway on GrInState below; no danger for WD issues in in b_optimize
3511 ; no_pending_waitflags(WF) -> get_wait_flag0(WF,LWF) %important for e.g. PerformanceTests/While/LiftExec_LIM.mch
3512 ; kernel_waitflags:get_last_wait_flag(b_execute_while1,WF,LWF) % to do: maybe get largest waitflag to avoid as much as possible that new choice points get enumerated before while triggers?
3513 % see also tests 979, 981
3514 ),
3515 % before entering while loop, we wait for co-routines to complete that may have activated b_execute_while
3516 b_execute_while_idle(COND,STMT,INV,VARIANT,ModVars,int(VarVal),LocalState,InState,OutState,WF,LWF).
3517
3518 :- block b_execute_while_idle(?,?,?,?,?,?, ?,?,?, ?,-). % we block on enumeration starting wait_flag
3519 b_execute_while_idle(COND,STMT,INV,VARIANT,ModVars,int(VarVal),LocalState,InState,OutState,WF,_) :-
3520 %ground_constraintprop_wait_flags(WF),
3521 (number(VarVal), VarVal>50, preference(compile_while_body,true)
3522 % if VarVal > 50 -> worthwhile to compile STMT
3523 % TO DO: also take size of body into account, and what if only a small part of the body is reachable in each iteration
3524 ? -> b_compiler:b_optimize(STMT,ModVars,LocalState,InState,CSTMT,WF),
3525 % print(compiled_while(ModVars)),nl, translate:print_subst(CSTMT),nl,
3526 OutState=WhileOutState,
3527 exclude(unused_variable(ModVars),LocalState,LS), % only keep modified vars; all other compiled
3528 exclude(unused_variable(ModVars),InState,IS) % only keep modified vars; all other compiled
3529 ; CSTMT=STMT, LS=LocalState, IS=InState,
3530 lazy_exclude(WhileOutState,ModVars,OutState) % only copy over those variables (potentially) modified by While loop
3531 % Note: it is important that we only have one copy of each modified variable in OutState
3532 ),
3533 ground_state_check(InState,GrInState),
3534 ? b_execute_while_loop_block(GrInState,COND,CSTMT,INV,VARIANT,none,VarVal,LS,IS,WhileOutState,WF).
3535
3536 :- block b_execute_while_loop_block(-,?,?,?,?,?,?,?,?,?,?).
3537 b_execute_while_loop_block(_,COND,CSTMT,INV,VARIANT,none,VarVal,LS,IS,WhileOutState,WF) :-
3538 ? b_execute_while_loop(COND,CSTMT,INV,VARIANT,none,VarVal,LS,IS,WhileOutState,WF).
3539
3540 :- block b_execute_while1(?,?,?,?,?,-,?,?,?,?).
3541 b_execute_while1(COND,STMT,INV,VARIANT,PrevVariantValue,int(VarVal),LocalState,InState,OutState,WF) :-
3542 % get_last_wait_flag(while(VarVal),WF,LWF),
3543 deref_wf(WF,FreshWF),
3544 %ground_constraintprop_wait_flags(FreshWF), % this is not a good idea, co-routine may be triggered while grounding WF; this subsidiary call will prevent grounding from completing and may trigger later waitflags before earlier ones are finished
3545 % this can lead to enumeration warnings; the same applies to other calls to ground_constraintprop_wait_flags below
3546 b_execute_while_loop(COND,STMT,INV,VARIANT,PrevVariantValue,VarVal,LocalState,InState,OutState,FreshWF).
3547
3548 % block on PrevVarVal and VarVal not yet needed here; but we need it for b_execute_while_body below
3549 :- block b_execute_while_loop(?,?,?,?,-,?,?,?,?,?), b_execute_while_loop(?,?,?,?,?,-,?,?,?,?).
3550 b_execute_while_loop(COND,STMT,INV,VARIANT,PrevVarVal,VarVal,LocalState,InState,OutState,WF) :-
3551 ? b_try_check_boolean_expression_c(INV,LocalState,InState,WF,INVRes),
3552 %ground_constraintprop_wait_flags(WF), % seems to slow down interpretation
3553 ? b_check_execute_while_loop1(INVRes,COND,STMT,INV,VARIANT,PrevVarVal,VarVal,LocalState,InState,OutState,WF).
3554
3555 :- block b_check_execute_while_loop1(-,?,?,?,?,?,?,?,?,?,?).
3556 b_check_execute_while_loop1(pred_false,_COND,_STMT,INV,_VAR,_PrevVarVal,VarVal,LocalState,InState,_OutState,WF) :-
3557 add_abort_error_span(while_invariant_violation,
3558 'While INVARIANT VIOLATED, current VARIANT value: ',VarVal,span_predicate(INV,LocalState,InState),WF).
3559 b_check_execute_while_loop1(pred_true,COND,STMT,INV,VARIANT,PrevVarVal,VarVal,LocalState,InState,OutState,WF) :-
3560 b_try_check_boolean_expression_c(COND,LocalState,InState,WF,CondRes),
3561 %ground_constraintprop_wait_flags(WF), % seems to slow down interpretation
3562 ? b_check_execute_while_loop2(CondRes,COND,STMT,INV,VARIANT,PrevVarVal,VarVal,LocalState,InState,OutState,WF).
3563
3564 :- block b_check_execute_while_loop2(-,?,?,?,?,?,?,?,?,?,?).
3565 b_check_execute_while_loop2(pred_false,_COND,_STMT,_INV,_VARIANT,_PrevVarVal,_VarVal,_LS,InState,OutState,_WF) :-
3566 OutState=InState. % we copy over the while InState: the updates will be computed at the end of the while loop
3567 b_check_execute_while_loop2(pred_true,COND,STMT,INV,VARIANT,PrevVarVal,VarVal,LocalState,InState,OutState,WF) :-
3568
3569 %hit_profiler:add_profile_hit(b_execute_while_body(STMT,VarVal,PrevVarVal,LocalState),2),
3570 % TO DO: maybe only compute VARIANT now and not above ??
3571 % b_compute_expression(VARIANT,LocalState,InState,VarVal,WF),
3572 % ground_constraintprop_wait_flags(WF), %% moved here because VARIANT computed later
3573 ? b_execute_while_body(COND,STMT,INV,VARIANT,PrevVarVal,VarVal,LocalState,InState,OutState,WF).
3574
3575 %:- block b_execute_while_body(?,?,?,?,-,?,?,?,?,?), b_execute_while_body(?,?,?,?,?,-,?,?,?,?).
3576 % we must ensure VarVal and PrevVaraintValue known
3577 % the block declaration above for b_execute_while_loop already ensures this
3578 b_execute_while_body(_COND,_STMT,_INVARIANT,VAR,_PV,VarVal,LocalState,InState,_OutState,WF) :-
3579 VarVal<0, !, % more efficient than is_not_natural(int(VarVal)),
3580 %ground_constraintprop_wait_flags(WF),
3581 % add_abort_error_span will fail; hence no need to set _OutState
3582 add_abort_error_span(while_variant_error,'While VARIANT not NATURAL:',VarVal,span_predicate(VAR,LocalState,InState),WF).
3583 b_execute_while_body(_COND,_STMT,_INVARIANT,VAR,PrevVariantValue,VarVal,LocalState,InState,_OutState,WF) :-
3584 % check no longer required VarVal>=0,%is_natural(int(VarVal),WF),
3585 PrevVariantValue \= none,
3586 PrevVariantValue =< VarVal, !, %less_than_equal(int(PrevVariantValue),int(VarVal)),
3587 %ground_constraintprop_wait_flags(WF),
3588 % add_abort_error_span will fail; hence no need to set _OutState
3589 ajoin(['VARIANT = ',VarVal,', previous value = ',PrevVariantValue],Details),
3590 add_abort_error_span(while_variant_error,'While VARIANT not decreasing:',
3591 Details,span_predicate(VAR,LocalState,InState),WF).
3592 b_execute_while_body(COND,STMT,INV,VARIANT,_PrevVariantValue,VarVal,LocalState,InState,OutState,WF) :-
3593 % check no longer required due to cuts above %VarVal>=0, %is_natural(int(VarVal),WF),
3594 %(PrevVariantValue==none -> true ; less_than(int(VarVal),int(PrevVariantValue))),
3595 %ground_constraintprop_wait_flags(WF), % seems to slow down interpretation
3596 copy_wf_start(WF,while_body,CWF),
3597 ? b_execute_statement(STMT,LocalState,InState,LHSUpdates,CWF,_Path1,output_required),
3598 copy_wf_finish(WF,CWF),
3599 ground_det_wait_flag(WF), % TODO: remove this
3600 store_intermediate_updates_wf(InState,LHSUpdates,IntermediateState,STMT,WF),
3601 check_state_skeleton_bound(LHSUpdates,Bound), % otherwise variable lookups will cause problems; ensures IntermediateState skeleton bound
3602 b_execute_while_when_state_set(COND,STMT,INV,VARIANT,VarVal,LocalState,IntermediateState,OutState,WF,Bound).
3603
3604 :- block b_execute_while_when_state_set(?,?,?,?,?,?,?,?,?,-).
3605 b_execute_while_when_state_set(COND,STMT,INV,VARIANT,PrevVariantValue,LocalState,State,Res,WF,_) :-
3606 copy_wf_start(WF,while2,CWF),
3607 b_compute_expression(VARIANT,LocalState,State,VarVal,CWF),
3608 copy_wf_finish(WF,CWF),
3609 b_execute_while1(COND,STMT,INV,VARIANT,PrevVariantValue,VarVal,LocalState,State,Res,WF).
3610
3611 % ------------- IF-THEN-ELSE
3612
3613 :- block b_execute_else_list2(-,?,?,?, ?,?,?,-,?). % should we also unblock if LWF set ? needed for seq. composition to set up state ??
3614 b_execute_else_list2(PredRes,Body,Rest,LocalState,InState,OutState,InnerWF,LWF,OR) :-
3615 %(var(PredRes) -> print('IF-THEN-ELSE ENUMERATION: '), translate:print_subst(Body),nl ; true),
3616 ? b_execute_else_list3(PredRes,Body,Rest,LocalState,InState,OutState,InnerWF,LWF,OR).
3617
3618 b_execute_else_list3(pred_true,Body,_,LocalState,InState,OutState,WF,_,OR) :-
3619 ? b_execute_statement(Body,LocalState,InState,OutState,WF,_Path,OR).
3620 b_execute_else_list3(pred_false,_Body,Rest,LocalState,InState,OutState,WF,LWF,OR) :-
3621 ? b_execute_else_list(Rest,LocalState,InState,OutState,WF,LWF,OR).
3622
3623 b_execute_else_list([],_,_State,[],_WF,_LWF,_OR). /* skip */
3624 b_execute_else_list([TExpr|Rest],LocalState,InState,OutState,WF,LWF,OR) :-
3625 get_texpr_expr(TExpr,if_elsif(Test,Body)), % Info field not used
3626 % get_enumeration_finished_wait_flag(WF,LWF),
3627 InnerWF=WF, %clone_wait_flags_from1(WF,InnerWF),
3628 ? b_try_check_boolean_expression_lwf(Test,LocalState,InState,InnerWF,'$ENUMERATION',PredRes,LWF),
3629 %ground_wait_flag0(InnerWF),
3630 (nonvar(PredRes) -> b_execute_else_list3(PredRes,Body,Rest,LocalState,InState,OutState,InnerWF,LWF,OR)
3631 ; (LWF == '$GENERATE_ON_DEMAND' ->
3632 get_wait_flag0(WF,LWF1),
3633 get_wait_flag_if_necessary(PredRes,LWF1,OR,WF,LWF2)
3634 ; LWF2=LWF),
3635 ? b_execute_else_list2(PredRes,Body,Rest,LocalState,InState,OutState,InnerWF,LWF2,OR)
3636 ).
3637
3638 % avoid calling get_wait_flag if possible (expensive)
3639 :- block get_wait_flag_if_necessary(-,-,?,?,?).
3640 get_wait_flag_if_necessary(PredRes,_,OR,WF,LWF2) :- var(PredRes), !, % we need waitflag
3641 (preferences:preference(use_smt_mode,true) -> Prio = 2 % was 2.0
3642 ; OR == output_required -> Prio = 2000
3643 ; Prio = 200000 %last_finite_priority(Prio)
3644 ), % TO DO: check if there is a guard inside; if not we can wait much longer; unless we are in CBC mode
3645 get_wait_flag(Prio,if_else,WF,LWF2).
3646 get_wait_flag_if_necessary(_,_,_,_,_).
3647
3648 :- block b_execute_choice(?,?,?,?,?,?,-,?).
3649 b_execute_choice(ChoiceList,LocalState,InState,OutState,WF,choice(Nr,Path),_WFC,OR) :-
3650 ? nth1(Nr,ChoiceList,Choice),
3651 b_execute_statement(Choice,LocalState,InState,OutState,WF,Path,OR).
3652
3653 % execute ASSERT PreCond THEN Body
3654 b_execute_assertion(_PreCond,Body,LocalState,InState,OutState,WF,Path,OR) :-
3655 preference(do_assert_checking,false), % ASSERT checking disabled
3656 !,
3657 b_execute_statement(Body,LocalState,InState,OutState,WF,Path,OR).
3658 b_execute_assertion(PreCond,Body,LocalState,InState,OutState,WF,Path,OR) :-
3659 ? b_try_check_boolean_expression_lwf(PreCond,LocalState,InState,WF,'$ENUMERATION',PredRes,WFC),
3660 % enumeration of PredRes before WFE set make sense, Body can instantiate values
3661 (var(PredRes) -> get_last_wait_flag(assertion,WF,WFC) ; true),
3662 b_execute_assertion_block(PredRes,PreCond,Body,LocalState,InState,OutState,WF,Path,OR).
3663
3664 :- block b_execute_assertion_block(-, ?,?,?,?, ?,?,?,?).
3665 b_execute_assertion_block(pred_true,_PreCond,Body,LocalState,InState,OutState,WF,Path,OR) :-
3666 Path = assertion(IPath),
3667 b_execute_statement(Body,LocalState,InState,OutState,WF,IPath,OR).
3668 b_execute_assertion_block(pred_false,PreCond,_Body,LocalState,InState,_OutState,WF,Path,_OR) :-
3669 Path = assertion_violated,
3670 translate_bexpression(PreCond,PreString),
3671 add_abort_error_span(assert_error,'ASSERT violated: ',PreString,span_predicate(PreCond,LocalState,InState),WF).
3672
3673 :- block check_state_skeleton_bound(-,?).
3674 check_state_skeleton_bound([],true).
3675 check_state_skeleton_bound([bind(Var,_)|T],Res) :-
3676 check_state_skeleton_bound_aux(Var,T,Res).
3677
3678 :- block check_state_skeleton_bound_aux(-,?,?).
3679 check_state_skeleton_bound_aux(Var,T,Res) :-
3680 (atomic(Var) -> true ; print('*** variable name not atomic: '), print(Var),nl),
3681 check_state_skeleton_bound(T,Res).
3682
3683
3684 b_execute_statement_list_when_state_set(StmtList,LS,State,USoFar,Res,WF,Path,OR) :-
3685 check_state_skeleton_bound(State,Bound), % otherwise variable lookups will cause problems
3686 ? b_execute_statement_when_state_set2(StmtList,LS,State,USoFar,Res,WF,Path,Bound,OR).
3687 :- block b_execute_statement_when_state_set2(?,?,?,?,?,?,?,-,?).
3688 b_execute_statement_when_state_set2(StmtList,LS,State,UpdatesSofar,Res,WF,Path,_,OR) :-
3689 copy_wf_start(WF,while2,CWF),
3690 ? b_execute_sequence(StmtList,LS,State,StmtUpdates,CWF,Path,OR),
3691 ? copy_wf_finish(WF,CWF),
3692 ? merge_updates(UpdatesSofar,StmtUpdates,Res).
3693
3694
3695 store_values([], [], []).
3696 store_values([IDsHd|IDsTl], [VALsHd|VALsTl], [bind(IDsHd,VALsHd)|OutStateTl]) :-
3697 store_values(IDsTl, VALsTl, OutStateTl).
3698
3699
3700
3701
3702 /* the B syntax does allow multiple definitions in a LET: */
3703
3704 b_execute_let_definitions(Pred,LocalState,State,WF) :-
3705 is_a_conjunct(Pred,LHS,RHS),!,
3706 b_execute_let_definitions(LHS,LocalState,State,WF),
3707 b_execute_let_definitions(RHS,LocalState,State,WF).
3708 b_execute_let_definitions(b(equal(LHS,RHS),_,_),LocalState,State,WF) :- !,
3709 b_compute_expression(LHS,LocalState,State,LHSVal,WF),
3710 b_compute_expression(RHS,LocalState,State,RHSVal,WF),
3711 % TO DO: ideally we should check if LHS is a declared identifier and is only defined once
3712 kernel_objects:equal_object_optimized(LHSVal,RHSVal,b_execute_let_definitions).
3713 b_execute_let_definitions(b(lazy_let_pred(Id,AssignmentExpr,Body),_,_),LocalState,State,WF) :- !,
3714 add_lazy_let_id_and_expression(Id,AssignmentExpr,LocalState,State,NewLocalState,WF),
3715 b_execute_let_definitions(Body,NewLocalState,State,WF).
3716 b_execute_let_definitions(P,_L,_S,WF) :-
3717 add_internal_error_wf(b_interpreter,'Let contains a predicate which is not an equality: ',P,P,WF),fail.
3718
3719
3720 /* -----------------------------------------*/
3721 /* b_assign_function */
3722 /* -----------------------------------------*/
3723
3724 b_assign_values_or_functions([],[],_LS,_S,[],_WF,_OR).
3725 b_assign_values_or_functions([TExpr|ERest],[Value|VRest],LS,S,[bind(Id,New)|NRest],WF,OR) :-
3726 get_texpr_expr(TExpr,Expr),
3727 ? b_assign_value_or_function(Expr,Value,LS,S,Id,New,WF,OR),
3728 b_assign_values_or_functions(ERest,VRest,LS,S,NRest,WF,OR).
3729
3730 :- use_module(kernel_tools,[ground_value_check/2]).
3731 :- use_module(kernel_records,[overwrite_record_wf/5]).
3732 b_assign_value_or_function(identifier(Id),Value,_LS,_S,LHS_Id,FullValue,WF,_OR) :- !,
3733 LHS_Id=Id,
3734 ? equal_object_wf(FullValue,Value,b_assign_value_or_function(Id),WF).
3735 b_assign_value_or_function(function(Fun,Arg),Value,LocalState,InState,Id,FullValue,WF,OR) :- !,
3736 %b_compute_expression(Arg,LocalState,InState,ArgVal,WF),
3737 %expand_global_sets_but_not_closures(ArgVal,EArgVal),
3738 FunMNF = eval_must_not_fail('Assignment left-hand-side (or part thereof) could not be evaluated: ',Fun), % could be f(..)(..)
3739 b_compute_assign_expressions_when([Arg,FunMNF],LocalState,InState,[ArgVal,FunVal],WF,OR), % or should we pass the OR info around ?
3740 /* we do not examine local state: these vars cannot be modified by operations !? */
3741 (OR=output_required -> override(FunVal,ArgVal,Value,NewFun,WF)
3742 ; ground_value_check((FunVal,ArgVal,Value),GRV),
3743 % wait until all arguments known so that we can effiently compute override
3744 blocking_override(GRV,FunVal,ArgVal,Value,NewFun,WF)),
3745 get_texpr_expr(Fun,Lhs),
3746 b_assign_value_or_function(Lhs,NewFun,LocalState,InState,Id,FullValue,WF,OR).
3747 b_assign_value_or_function(record_field(RecordExpr,FieldName),Value,LocalState,InState,LHS_Id,FullValue,WF,OR) :-
3748 !,
3749 % we allow nested record assignments: x'Field1'Field2 := Value
3750 b_compute_expression(RecordExpr,LocalState,InState,OldRecVal,WF),
3751 overwrite_record_wf(OldRecVal,FieldName,Value,NewRecVal,WF),
3752 get_texpr_expr(RecordExpr,Lhs),
3753 b_assign_value_or_function(Lhs,NewRecVal,LocalState,InState,LHS_Id,FullValue,WF,OR).
3754 b_assign_value_or_function(LHS,_Value,_LS,_InState,_Id,_FullValue,WF,_OR) :-
3755 add_internal_error_wf(b_interpreter,'Illegal LHS for assignment (must be ID(.) or ID\'Field or ID): ',LHS,LHS,WF),
3756 fail.
3757
3758 :- block blocking_override(-,?,?,?,?,?).
3759 blocking_override(_,FunVal,ArgVal,Value,NewFun,WF) :- override(FunVal,ArgVal,Value,NewFun,WF).
3760
3761
3762 /* -----------------------------------------*/
3763 /* b_execute_statements_in_parallel */
3764 /* -----------------------------------------*/
3765 /* execute a parallel composition of statements */
3766 :- assert_pre(b_interpreter:b_execute_statements_in_parallel(Ss,LS,State,_Os,WF,_Paths,_OR),
3767 (ground_check(Ss),type_check(LS,store),
3768 type_check(State,store),type_check(WF,wait_flag))).
3769 :- assert_post(b_interpreter:b_execute_statements_in_parallel(_Ss,_LS,_State,Os,WF,_Paths,_OR),
3770 (type_check(Os,store),type_check(WF,wait_flag))).
3771
3772 b_execute_statements_in_parallel([],_,_,[],_WF,[],_OR).
3773 b_execute_statements_in_parallel([Stmt|TS],LocalState,InState,OutState,WF,[Path1|TPath],OR) :-
3774 ? b_execute_statement(Stmt,LocalState,InState,OutState1,WF,Path1,OR),
3775 ? combine_updates(OutState1,OutState2,OutState), /* merge updates */
3776 ? b_execute_statements_in_parallel(TS,LocalState,InState,OutState2,WF,TPath,OR).
3777
3778
3779 %:- block combine_updates(-,-,?).
3780 %combine_updates(A,B,C) :- (B==[] -> A=C ; combine_updates_aux(A,B,C)).
3781
3782 % TO DO: investigate whether we could also unblock on second argument and copy it to result
3783 :- block combine_updates(-,?,?). % can also be used to merge states
3784 combine_updates([],X,R) :- !,R=X.
3785 ?combine_updates([H|T],Y,Res) :- !, Res=[H|Z], combine_updates(T,Y,Z).
3786 combine_updates(X,Y,Z) :- add_internal_error('Illegal call: ',combine_updates(X,Y,Z)),fail.
3787
3788
3789
3790 b_execute_initialisation_statement(Stmt,LS,In,Out,_OUTERWF,Path,OR) :-
3791 init_wait_flags(WF,[b_execute_initialisation_statement]),
3792 % each initialisation can be executed in isolation (except in CBC mode)
3793 ? b_execute_statement(Stmt,LS,In,Out,WF,Path,OR),
3794 ? ground_wait_flags(WF).
3795
3796 % replace certain parallels by init_parallel for better error reporting in INITIALISATION
3797 % will not be used in CBC mode (by set_up_initialisation or tc_initialise)
3798 translate_init_statements(b(Stmt,subst,I),b(TStmt,subst,I)) :-
3799 tp2(Stmt,I,TStmt).
3800 tp2(assign(LHS,RHS),I,parallel(S)) :- LHS=[_,_|_],
3801 % translate multiple assignment into parallel assignments
3802 maplist(generate_assignment(I),LHS,RHS,S),
3803 !.
3804 tp2(Stmt,I,init_statement(b(Stmt,subst,I))) :- %get_preference(provide_trace_information,true),
3805 wrap_stmt(Stmt),
3806 !.
3807 % TO DO: cover WHILE
3808 tp2(parallel(S),_,parallel(TS)) :- maplist(translate_init_statements,S,TS),
3809 !.
3810 tp2(sequence(A),_,sequence(LA)) :- !,maplist(translate_init_statements,A,LA).
3811 tp2(if(A),_,if(LA)) :- !, maplist(translate_init_statements,A,LA).
3812 tp2(if_elsif(Test,Body),_,if_elsif(Test,LBody)) :- !,
3813 translate_init_statements(Body,LBody).
3814 tp2(X,_,X). % :- functor(X,F,A), nl,nl,print(uncovered(F/A)),nl,nl.
3815
3816 wrap_stmt(assign(_,_)).
3817 wrap_stmt(becomes_element_of(_,_)).
3818 wrap_stmt(becomes_such(_,_)).
3819 wrap_stmt(assign_single_id(_,_)).
3820
3821 generate_assignment(I,V,RHS,b(init_statement(b(Assign,subst,I)),subst,I)) :-
3822 Assign = assign([V],[RHS]).
3823
3824
3825
3826 /* ---------------------------------------*/
3827 /* b_execute_top_level_statement */
3828 /* ---------------------------------------*/
3829
3830 /* this is just like b_execute_statement with the
3831 only difference that a PRE-condition is treated like
3832 a select, i.e., it does not generate an abort if used
3833 outside of its condition */
3834 b_execute_top_level_statement(TExpr,LocalState,InState,OutState,WF,Path,OR) :-
3835 get_texpr_expr(TExpr,Stmt),
3836 ? b_execute_top_level_statement2(Stmt,TExpr,LocalState,InState,OutState,WF,Path,OR).
3837 b_execute_top_level_statement2(precondition(PreCond,Body),TExpr,
3838 LocalState,InState,OutState,WF,Path,OR) :-
3839 preferences:preference(treat_outermost_pre_as_select,true),!,
3840 %debug_println(9,'Top level PRE treated as SELECT'),
3841 preference(ltsmin_do_not_evaluate_top_level_guards,NO_EVAL),
3842 (NO_EVAL=full ->
3843 debug_println(9,pge_guard_will_not_be_evaluated)
3844 ; NO_EVAL=true, % do not evaluate guards detected by guard splitting
3845 get_texpr_info(TExpr,Info),member(prob_annotation('LTSMIN-GUARD'),Info) ->
3846 debug_println(9,ltsmin_guard_will_not_be_evaluated)
3847 ? ; b_test_boolean_expression(PreCond,LocalState,InState,WF)
3848 ),
3849 % b_tracetest_boolean_expression(PreCond,LocalState,InState,WF,one), % comment in for debugging
3850 ? b_execute_statement(Body,LocalState,InState,OutState,WF,Path,OR).
3851 b_execute_top_level_statement2(lazy_let_subst(Id,IdExpr,Body),_,
3852 LocalState,InState,OutState,WF,lazy_let(Path),OR) :-
3853 !,
3854 add_lazy_let_id_and_expression(Id,IdExpr,LocalState,InState,NewLocalState,WF),
3855 b_execute_top_level_statement(Body,NewLocalState,InState,OutState,WF,Path,OR).
3856 b_execute_top_level_statement2(_,TExpr,LocalState,InState,OutState,WF,Path,OR) :-
3857 ? b_execute_statement(TExpr,LocalState,InState,OutState,WF,Path,OR).
3858
3859
3860 /* -----------------------------*/
3861 /* b_execute_operation */
3862 /* -----------------------------*/
3863 /* execute a single operation */
3864
3865 try_get_op_name(FullOperation,_Name) :- var(FullOperation),!.
3866 try_get_op_name('-->'(FO,_),Name) :- !,try_get_op_name(FO,Name).
3867 try_get_op_name(FullOperation,Name) :- functor(FullOperation,Name,_).
3868
3869
3870
3871 :- assert_pre(b_interpreter:b_execute_top_level_operation_update(_Name,_FullOperation,InState,_NewState,_P),
3872 (ground_check(InState),type_check(InState,store))).
3873 :- assert_post(b_interpreter:b_execute_top_level_operation_update(Name,_FullOperation,_InState,NewState,_Path),
3874 (type_check(NewState,store),ground_check(Name))).
3875
3876
3877 b_execute_top_level_operation_update(Name,FullOperation,InState,Updates,Path) :-
3878 ? b_execute_top_level_operation_update_wf(Name,FullOperation,InState,Updates,Path,WF),
3879 ? ground_wait_flags(WF).
3880 %store:store_updates_and_normalise(Updates,InState,NewState).
3881
3882
3883 b_execute_top_level_operation_update_wf(Name,FullOperation,InState,Updates,Path,WF) :-
3884 init_wait_flags(WF,[]), % now treated by call_stack: [expansion_context(op(Name),[])]),
3885 % b_execute_operation2 will push_wait_flag_call_stack_info
3886 try_get_op_name(FullOperation,Name), b_top_level_operation(Name),
3887 setup_result_input_values(Name,RIV),
3888 Info=unknown, % Info extracted later for top_level
3889 ? b_execute_operation2(Name,FullOperation,InState,Updates,_,RIV,_,true,Path,Info,WF,output_not_required).
3890
3891 % set up value of read output variables *before* operation call to some dummy value
3892 setup_result_input_values(Name,ResultInputValues) :-
3893 (get_preference(allow_operations_to_read_outputs,true),
3894 b_operation_reads_output_variables(Name,_Reads,TReadsInfo) ->
3895 maplist(setup_read_output_variable,TReadsInfo,ResultInputValues)
3896 %translate_bstate_limited(ResultInputValues,TS),
3897 %ajoin(['Warning: setting read output variables in ',Name,' to default values: ',TS],Msg),
3898 %add_warning(b_interpreter,Msg),
3899 %store_error_for_context_state(eventerror(Name,event_other_error(Msg),[]),_Id)
3900 ; ResultInputValues=[]).
3901
3902 :- use_module(typing_tools,[any_value_for_type/2]).
3903 setup_read_output_variable(reads_result(_,Name,Type),bind(Name,Val)) :- any_value_for_type(Type,Val).
3904
3905 % for use by CBC:
3906 b_execute_top_level_operation_wf(Name,FullOperation,ParaVals,ResultVals,InState,NewState,Path,WF) :-
3907 try_get_op_name(FullOperation,Name),
3908 if(b_top_level_operation(Name),true,
3909 (add_internal_error('Unknown operation name for b_execute_top_level_operation_wf: ',Name),fail)
3910 ),
3911 % call before execute operation to copy over results immediately in case b_execute_operation2 generates choice points:
3912 store_intermediate_updates_wf(InState,Updates,NewState,operation(Name),WF), % no normalising is better for constraint propagation
3913 % TO DO?: copy over unmodified variables b_get_machine_variables(Variables),copy_unmodified_variables(Variables,OpName,InState,NewState)
3914 setup_result_input_values(Name,RIV),
3915 Info=unknown, % Info extracted later for top_level
3916 b_execute_operation2(Name,FullOperation,InState,Updates,ParaVals,RIV,ResultVals,true,Path,Info,WF,output_required).
3917 % we should ensure that Operation part is executed to instantiate NewOutState skeleton
3918
3919
3920
3921 % Note : if the argument OR (OutputRequired) has value output_required this indicates that the output
3922 % an operation or its effect is required (e.g., because of sequential composition) and the constraint solver
3923 % should not delay computing the effect of the operation
3924 % Atelier-B Handbook 6.16: [R <- op (E)]P = [X := E ; S ; R :=Y] P where op defined by X <- op(Y) = S
3925 b_execute_operation_with_parameters(Name,LocalState,InState,Results,Parameters,OutState,ParamValues,ResultValues,Path,Info,WF,OR) :-
3926 (b_is_operation_name(Name)
3927 -> b_compute_expressions(Parameters,LocalState,InState,ParamValues,WF),
3928 % TO DO : remove local vars from InState
3929 (b_operation_reads_output_variables(Name,_Reads,TReadsInfo)
3930 -> % format('Transferring outputs ~w ~w~n ~w~n',[Name,_Reads,TReadsInfo]),
3931 maplist(output_parameters_value(LocalState,InState,Results,Info,WF),TReadsInfo,ResultInputValues)
3932 ; ResultInputValues=[]),
3933 ? call_b_execute_operation2(Name,InState,OutState,ParamValues,ResultInputValues,ResultValues,false,Path,Info,WF,OR)
3934 ; add_internal_error('Unknown B operation, cannot call: ',
3935 b_execute_operation_with_parameters(Name,LocalState,InState,Results,Parameters,
3936 OutState,ParamValues,ResultValues,Path,Info,WF,OR)),
3937 fail
3938 ).
3939
3940
3941 %b_execute_operation_in_expression(Name,_LocalState,_InState,_Parameters,_Value,Info,_WF) :-
3942 % % This clause is disabled: sometimes variables are marked as read even though they are not:
3943 % % the analysis is not precise due to sequential composition, CASE statements, ...
3944 % b_operation_reads_output_variables(Name,_Reads,_TReadsInfo),!,
3945 % add_error(b_interpreter,'Operation that reads output cannot be called in expression: ',Name,Info),
3946 % fail.
3947 b_execute_operation_in_expression(Name,LocalState,InState,Parameters,Value,Info,WF) :-
3948 % TODO: check that this is a query operation; probably done in type checker
3949 OR=output_required, % alternative: OR=output_not_required,
3950 setup_result_input_values(Name,ResultInputValues),
3951 b_compute_expressions(Parameters,LocalState,InState,ParamValues,WF),
3952 b_get_operation_normalized_read_write_info(Name,Read,_Modified), % Modified should be []
3953 create_inner_wait_flags(WF,operation_call_in_expr,OpWF),
3954 ground_value_check(ParamValues,ParaGround),
3955 exclude(unused_variable(Read),InState,IS),
3956 ground_state_check(IS,StateGround),
3957 % TO DO: in case of recursion it may be good to delay executing sub-operation until some WF is set
3958 call_b_execute_operation2(Name,IS,_OutState,ParamValues,ResultInputValues,ResultValues,false,_Path,Info,OpWF,OR),
3959 ground_inner_wf(ParaGround,StateGround,OpWF),
3960 make_couplise(ResultValues,Value).
3961
3962 % ground inner waitflags when parameters and relevant read variables fully known
3963 :- block ground_inner_wf(-,?,?), ground_inner_wf(?,-,?).
3964 ground_inner_wf(_,_,WF) :-
3965 ? ground_inner_wait_flags(WF).
3966
3967 :- if( environ(prob_profile, true)).
3968 call_b_execute_operation2(Name,InState,OutState,ParamValues,ResultInputValues,ResultValues,false,Path,Info,WF,OR) :-
3969 % TODO: insert operation call as additional error context; stack trace
3970 runtime_profiler:profile_single_call(Name,unknownStateId, b_interpreter:
3971 b_execute_operation2(Name,_,InState,OutState,ParamValues,ResultInputValues,ResultValues,false,Path,Info,WF,OR)
3972 ).
3973 :- else.
3974 call_b_execute_operation2(Name,InState,OutState,ParamValues,ResultInputValues,ResultValues,false,Path,Info,WF,OR) :-
3975 ? b_execute_operation2(Name,_,InState,OutState,ParamValues,ResultInputValues,ResultValues,false,Path,Info,WF,OR).
3976 :- endif.
3977
3978 output_parameters_value(LocalState,InState,Results,_,WF,reads_result(Index,ID,_Type),bind(ID,Val)) :-
3979 nth1(Index,Results,ReadResultTID),!,
3980 def_get_texpr_id(ReadResultTID,ReadID),
3981 (lookup_value_without_check(ReadID,LocalState,InState,Val)
3982 -> true %check_not_undefined(Val,ReadID,ReadResultTID)
3983 ; add_error_wf(output_parameters,'Could not obtain value for read output parameter: ',ReadID,ReadResultTID,WF),
3984 Val = term(undefined)).
3985 output_parameters_value(_LocalState,_InState,_Results,Info,WF,reads_result(_Index,ID,_Type),bind(ID,Val)) :-
3986 add_error_wf(output_parameters,'Could not obtain value for read output parameter: ',ID,Info,WF),
3987 Val = term(undefined).
3988
3989 % TO DO: use this ?
3990 %:- block check_not_undefined(-,?,?).
3991 %check_not_undefined(term(undefined),ReadID,ReadResultTID) :- !,
3992 % add_error(output_parameters_value,'Output parameter not assigned to: ',ReadID,ReadResultTID).
3993 %check_not_undefined(_,_,_).
3994
3995 % ResultInputValues: in Atelier-B result parameters can also be read !
3996 b_execute_operation2(Name,Operation,InState,Updates,ParaValues,ResultInputValues,ResultValues,_TopLevel,TransInfo,_,_WF,_OR) :-
3997 ResultInputValues = [], % in this case the operation's behaviour also depends on current value of output variables
3998 lookup_cached_transitions(Name,InState,Solutions),!,
3999 ? member(transition(ParaValues,ResultValues,Updates,TransInfo),Solutions),
4000 create_full_operation(Name,ResultValues,ParaValues,ResultValues,Operation).
4001
4002 b_execute_operation2(Name,Operation,InState,NewOutState,ParaValues,ResultInputValues,ResultValues,
4003 TopLevel,TransInfo,Info,WF,OutputRequired) :-
4004 b_get_machine_operation_for_animation(Name,Results,Parameters,Body,OType,TopLevel,OpPos),
4005 %% % we do not want skip the evaluation of a guard of an operation with parameters
4006 %% (Parameters==[] ->true; retractall(pge_algo:do_not_evaluate_guard)),
4007 (Info=unknown, TopLevel==true -> CallInfo=OpPos ; CallInfo=Info),
4008 push_wait_flag_call_stack_info(WF,operation_call(Name,ParaValues,CallInfo),WF2),
4009 ? b_execute_operation3(OType,Name,Operation,
4010 InState,NewOutState,
4011 Body,Parameters,ParaValues,Results,ResultInputValues,ResultValues,TopLevel,TransInfo,WF2,OutputRequired).
4012
4013 create_full_operation(Name,Results,ParaValues,ResultValues,FullOperation) :-
4014 %length(ParaValues,Len),print(create_full_op(Name,Len)),nl,
4015 Operation =.. [Name|ParaValues], % TO DO: catch if > 255 args (max_arity)
4016 ( Results == [] -> /* we have an ordinary operation */
4017 FullOperation = Operation
4018 ; FullOperation = '-->'(Operation,ResultValues)
4019 ).
4020
4021 b_execute_operation3(classic,Name,Operation,InState,NewOutState,
4022 Body,Parameters,ParaValues,Results,ResultInputValues,NormalisedResultValues,TopLevel,
4023 [], % [path(Path)], % as path is currently filtered out anyway and not stored !
4024 WF,OR) :-
4025 %print('Attempting Operation ----> '),print(Name),nl,
4026 empty_state(EmptyState),
4027 ? set_up_typed_localstate(Parameters,ParaValues,ParamTypedVals,EmptyState,LocalState,positive),
4028 l_expand_and_normalise_values(ParaValues,NormalisedParaValues,Parameters), % not useful for call_b_execute_operation2
4029 create_full_operation(Name,Results,NormalisedParaValues, % ditto
4030 NormalisedResultValues,Operation),
4031 set_up_undefined_localstate_with_predefined(Results,ResultInputValues,InState,NewInState),
4032 /* to avoid error messages with sequential composition (store_intermediate_updates) */
4033 check_additional_guard(TopLevel,LocalState,NewInState,WF),
4034 (TopLevel==true
4035 ? -> b_execute_top_level_statement(Body,LocalState,NewInState,OutState,WF,_Path1,OR)
4036 ? ; b_execute_statement(Body,LocalState,NewInState,OutState,WF,_Path2,OR)
4037 ),
4038 b_tighter_enumerate_all_values(ParamTypedVals,WF), % moved afer execute for performance reasons; see PerformanceTests/ParameterEnumeration.mch
4039 % print_bt_message('Operation Successful ------> '),
4040 (preferences:preference(treat_outermost_pre_as_select,true),
4041 preferences:preference(require_operations_to_assign_all_outputs,true)
4042 -> ReportError = true ; ReportError = false),
4043 get_results(Results,OutState,NormalisedResultValues,NewOutState,ReportError,normalise_results,WF).
4044 b_execute_operation3(eventb_operation(ChangeSet,ParaValues,Operation),
4045 _Name,Operation, InState,Updates,
4046 TBody,Parameters,ParaValues,[],[],[],true,TransInfo,WF,OutputRequired) :-
4047 % TO DO: check if need to pass _OutputRequired to b_event
4048 ? b_execute_event_with_change_set_wf(TBody,Parameters,ParaValues,InState,ChangeSet,Updates,TransInfo,WF,OutputRequired).
4049
4050 :- use_module(b_global_sets,[add_prob_deferred_set_elements_to_store/3]).
4051 % additional guards can be set by the user to constrain/direct the execution of operations
4052 check_additional_guard(TopLevel,LocalState,State,WF) :-
4053 (TopLevel==true,
4054 bmachine:b_machine_temp_predicate(TempPred)
4055 /* an additional precondition typed in by the user */
4056 -> check_state_skeleton_bound(LocalState,LB),
4057 check_state_skeleton_bound(State,BB),
4058 check_additional_guard_when_bound(LB,BB,TempPred,LocalState,State,WF)
4059 ; true
4060 ).
4061
4062 :- block check_additional_guard_when_bound(-,?,?, ?,?,?), check_additional_guard_when_bound(?,-,?, ?,?,?).
4063 check_additional_guard_when_bound(_,_,TempPred,LocalState,State,WF) :-
4064 (debug_mode(on) -> print(check_additional_guard),nl, print_bexpr(TempPred),nl ; true),
4065 add_prob_deferred_set_elements_to_store(State,BState1,visible),
4066 b_test_boolean_expression(TempPred,LocalState,BState1,WF).
4067
4068 % additional properties can either be set by user or by command-line or by VALUES clause
4069 add_additional_properties(OldProperty,NewProperty) :-
4070 (bmachine:b_machine_temp_predicate(TempPred) % this overrides additional property !
4071 -> conjunct_predicates([TempPred,OldProperty],NewProperty)
4072 ; findall(AddPred,b_machine_additional_property(AddPred),L),
4073 (L=[] -> NewProperty = OldProperty
4074 ; conjunct_predicates([OldProperty|L],NewProperty)
4075 )
4076 ).
4077
4078 % get removes results from OutState
4079 filter_results(Results,OutState,NewOutState,WF) :-
4080 get_results(Results,OutState,_ResultValues,NewOutState,false,do_not_normalise,WF).
4081 get_results(Results,OutState,ResultValues,NewOutState,ReportError,Normalise,WF) :-
4082 (Results==[] -> (ResultValues,NewOutState) = ([],OutState)
4083 ; get_results1(Results,OutState,ResultValues,NewOutState,ReportError,Normalise,WF)).
4084 :- block get_results1(?,-,?,?,?,?,?).
4085 get_results1([],OutState,[],OutState,_ReportError,_Normalise,_WF).
4086 get_results1([R|Results],OutState,[NRV|ResultValues],NewOutState,ReportError,Normalise,WF) :-
4087 def_get_texpr_id(R,ResultId),
4088 lookup_and_delete_value(ResultId,RV,OutState,OutState2,ReportError,WF,Finished),
4089 get_results2(Finished,R,Results,RV,NRV,OutState2,ResultValues,NewOutState,ReportError,Normalise,WF).
4090 :- block get_results2(-,?,?,?,?,?,?,?,?,?,?).
4091 get_results2(_,R,Results,RV,NRV,OutState2,ResultValues,NewOutState,ReportError,Normalise,WF) :-
4092 (Normalise==normalise_results -> normalise_value_for_var(R,true,RV,NRV)
4093 ;
4094 NRV=RV), % Maybe we should not normalise in CBC mode ?
4095 get_results1(Results,OutState2,ResultValues,NewOutState,ReportError,Normalise,WF).
4096
4097
4098
4099 /* ------------------------------------------------------------------ */
4100 /* SET UP CONSTANTS */
4101 /* ------------------------------------------------------------------ */
4102
4103 :- use_module(static_ordering).
4104
4105 :- volatile no_solution_found_for_constants/0, properties_were_filtered/1,
4106 unsat_properties_component/2, unsat_properties_enumeration_warning/1, unsat_properties_abort_error/1,
4107 unsat_properties_conjunct_inside_component/4.
4108 :- dynamic no_solution_found_for_constants/0,
4109 properties_were_filtered/1,
4110 unsat_properties_component/2, unsat_properties_enumeration_warning/1,
4111 unsat_properties_abort_error/1,
4112 unsat_properties_conjunct_inside_component/4.
4113
4114 reset_unsat_component_infos :-
4115 retractall(unsat_properties_component(_,_)),
4116 retractall(unsat_properties_enumeration_warning(_)),
4117 retractall(unsat_properties_abort_error(_)),
4118 retractall(unsat_properties_conjunct_inside_component(_,_,_,_)).
4119
4120 :- use_module(b_interpreter_components,[unsat_conjunct_inside_component/4, unsat_component_abort_error/1,
4121 unsat_component_enumeration_warning/1]).
4122 % store information about unsatisfiable components for later usage
4123 % will only be called when no solution found for components
4124 assert_unsat_component_infos(_) :-
4125 ? unsat_component(X,FalseOrUnknown), % from b_interpreter_components
4126 assertz(unsat_properties_component(X,FalseOrUnknown)),fail.
4127 assert_unsat_component_infos(_) :-
4128 unsat_component_enumeration_warning(X), % from b_interpreter_components
4129 assertz(unsat_properties_enumeration_warning(X)),fail.
4130 assert_unsat_component_infos(_) :-
4131 unsat_component_abort_error(X), % from b_interpreter_components
4132 assertz(unsat_properties_abort_error(X)),fail.
4133 assert_unsat_component_infos(_) :-
4134 ? unsat_conjunct_inside_component(X,BE,Status,Reason), % from b_interpreter_components
4135 assertz(unsat_properties_conjunct_inside_component(X,BE,Status,Reason)),fail.
4136 assert_unsat_component_infos(Status) :-
4137 ? (unsat_conjunct_inside_component(_,_,false,_) -> Status = false
4138 ; unsat_component(X,false), \+ unsat_component_abort_error(X) -> Status = false % what about enumeration warnings?
4139 ; Status=unknown).
4140
4141
4142 all_unsat_components_marked_prob_ignore :-
4143 unsat_properties_conjunct_inside_component(_,_,unknown,'prob-ignore'), % at least one prob-ignore was used
4144 !,
4145 \+ non_ignore_unsat_component.
4146
4147 non_ignore_unsat_component :-
4148 unsat_properties_conjunct_inside_component(_,_,Status,Reason),
4149 \+ (Status = unknown, Reason = 'prob-ignore').
4150
4151 tcltk_unsatisfiable_components_exist :- unsat_or_unknown_component_exists,!.
4152
4153 %tcltk_unsatisfiable_components(list(UnsatComponents)) :-
4154 % findall(C,unsat_properties_component(C),UnsatComponents), UnsatComponents\=[].
4155
4156 get_property_components(Components) :-
4157 b_machine_has_constants_or_properties,
4158 b_get_properties_from_machine(Properties),
4159 add_additional_properties(Properties,NewProperty),
4160 bsyntaxtree:predicate_components(NewProperty,Components),!.
4161 get_property_components([]).
4162
4163 :- dynamic uses_implementable_integers/0.
4164 :- dynamic min_max_integer_value_used/2.
4165
4166
4167 tcltk_quick_describe_unsat_properties(list(FullDescr),STATUS) :-
4168 retractall(uses_implementable_integers),
4169 retractall(min_max_integer_value_used(_,_)), assertz(min_max_integer_value_used(none,none)),
4170 get_property_components(Components),
4171 (unsat_properties_conjunct_inside_component(_,_,false,_)
4172 -> STATUS='FALSE'
4173 ; all_unsat_components_marked_prob_ignore
4174 -> STATUS = 'prob-ignore'
4175 ; STATUS='UNKNOWN'
4176 ),
4177 findall(TP, (unsat_properties_conjunct_inside_component(CompNr,P,_Status,_ReasonMsg), % find individual conjuncts
4178 % Status can be false or unknown
4179 nth1(CompNr,Components,component(FullPred,_Vars)),
4180 check_uses_implementable_integers(FullPred), % for the min-max one may need to look at the entire component !
4181 translate_bexpression_with_limit(P,TrP),
4182 get_component_enum_warning_message(CompNr,EnumWarningAbortMsg),
4183 (EnumWarningAbortMsg = '' -> Prefix = '' ; Prefix = '\n '),
4184 get_span_msg(P,'\n ',SpanMsg),
4185 ajoin([' * ',TrP,Prefix,EnumWarningAbortMsg,SpanMsg,'\n'],TP)),
4186 D1),
4187 findall([Msg1,PS|DescrVars],
4188 (get_unsat_component_description(Components,CompNr,MaxCompNr,
4189 Size,PS,DescrVars,EnumWarningAbortMsg,SpanMsg),
4190 ajoin([' * Predicate Component ',EnumWarningAbortMsg,CompNr,'/',MaxCompNr,
4191 ' (with ',Size,' conjunct(s))',SpanMsg, ':'],Msg1)),
4192 UC),
4193 append(UC,UCL), % join all component descriptions
4194 (D1=[]
4195 % TO DO: adapt message for enumeration warning
4196 -> Descr = D2,
4197 (UCL=[] -> D2 = ['The properties were satisfiable']
4198 ; D2 = ['No solution found for the following predicates: '|UCL]
4199 )
4200 ; Descr = ['The following properties prevented finding a solution:\n'|D12],
4201 % Comment: the predicate can trigger the computation of another earlier registered predicate
4202 % Example f = {1|->2} & f: A --> B & A = 1..5; A=1..5 triggers the check for f
4203 (UCL=[] -> D2=[]
4204 ; D2 = ['\nIn addition no solution was found for the following predicates: '|UCL]
4205 ),
4206 append(D1,D2,D12)),
4207 findall(W,other_warning(W),Warnings),
4208 (Warnings = [] -> FullDescr=Descr ; append(Descr,['\nWARNINGS/MESSAGES:'|Warnings],FullDescr)).
4209
4210 % called by predicate_debugger:
4211 get_unsat_component_predicate(CompNr,Predicate,Vars) :-
4212 unsat_properties_component(CompNr,_FalseOrUnknown),
4213 get_property_components(Components),
4214 nth1(CompNr,Components,component(Predicate,Vars)).
4215
4216 get_unsat_component_description(Components,CompNr,MaxCompNr,Size,PS,DescrVars,EnumWarningAbortMsg,SpanMsg) :-
4217 unsat_properties_component(CompNr,_),
4218 \+ unsat_properties_conjunct_inside_component(CompNr,_,_,_), % we have not yet dealt with this component in first findall above
4219 nth1(CompNr,Components,component(Pred,Vars)),
4220 length(Components,MaxCompNr),
4221 size_of_conjunction(Pred,Size),
4222 describe_constants(Vars,DescrVars),
4223 check_uses_implementable_integers(Pred), % store information in case it does use implementable integers for later user messages
4224 (debug_mode(on) -> Lim = 1500 ; Lim = 250),
4225 translate_bexpression_with_limit(Pred,Lim,PS),
4226 get_component_enum_warning_message(CompNr,EnumWarningAbortMsg),
4227 % note: sometimes we have a conjunction with empty span info, but different conjuncts (possibly from different files):
4228 get_span_msg(Pred,'\n ',SpanMsg).
4229
4230 get_span_msg(Pred,Prefix,SpanMsg) :-
4231 (extract_span_description(Pred,SpanStr) -> ajoin([Prefix,SpanStr],SpanMsg) ; SpanMsg = '').
4232
4233 get_component_enum_warning_message(CompNr,EnumWarningAbortMsg) :-
4234 (unsat_properties_enumeration_warning(CompNr)
4235 ->(unsat_properties_abort_error(CompNr)
4236 -> EnumWarningAbortMsg = '[** with Enumeration Warning and WD-ERROR **] '
4237 ; EnumWarningAbortMsg = '[* with Enumeration Warning *] ')
4238 ; (unsat_properties_abort_error(CompNr)
4239 -> EnumWarningAbortMsg = '[** with WD-ERROR **] '
4240 ; EnumWarningAbortMsg = '')
4241 ).
4242
4243 describe_constants([],R) :- !,R=[].
4244 describe_constants(Vars,['* over identifiers : '|Vars]).
4245
4246 check_uses_implementable_integers(_) :- specfile:eventb_mode,!. % cannot use implementable integers
4247 check_uses_implementable_integers(_) :- uses_implementable_integers,!. % no need to check another component
4248 check_uses_implementable_integers(Pred) :-
4249 (uses_implementable_integers(Pred)
4250 -> assertz(uses_implementable_integers),
4251 retract(min_max_integer_value_used(Min,Max)),
4252 min_max_integer_value_used(Pred,Min,Max,NewMin,NewMax),
4253 assertz(min_max_integer_value_used(NewMin,NewMax))
4254 ; true).
4255
4256 other_warning(W) :- uses_implementable_integers,
4257 preferences:get_preference(minint,MININT),
4258 preferences:get_preference(maxint,MAXINT),
4259 min_max_integer_value_used(Min,Max),
4260 ( (number(Min),Min<MININT ; number(Max),Max>MAXINT)
4261 -> ajoin(['\n MININT...MAXINT only set to ',MININT,'..',MAXINT,' but integers used at least from ',Min,'..',Max],W)
4262 ; (MAXINT < 127 ; MININT > -128)
4263 -> ajoin(['\n MININT...MAXINT possibly too small: ',MININT,'..',MAXINT],W)).
4264 % TO DO: we could also extract explicit integer values used in the component and compare them against MININT/MAXINT
4265 other_warning(W) :- bmachine_eventb:deferred_set_equality_without_enumeration_axioms(X,_Set),
4266 translate_bexpression_with_limit(X,XS),
4267 ajoin(['\n Set not recognized as enumerated: ',XS],W).
4268 % TO DO: generate warning if MAXINT/MININT small and NAT,NAT1 or INT was used in component(s) above
4269
4270 % call if tcltk_quick_describe_unsat_properties fails:
4271 % TODO: maxint warning above
4272 generate_unsat_properties_warnings :- uses_implementable_integers,
4273 preferences:get_preference(minint,MININT),
4274 preferences:get_preference(maxint,MAXINT),
4275 min_max_integer_value_used(Min,Max),
4276 (number(Min),Min<MININT ; number(Max),Max>MAXINT),
4277 ajoin(['MININT...MAXINT only set to ',MININT,'..',MAXINT,' but integers used at least from ',Min,'..',Max],Msg),
4278 add_warning(setup_constants_unknown,Msg),
4279 fail.
4280 generate_unsat_properties_warnings :-
4281 bmachine_eventb:deferred_set_equality_without_enumeration_axioms(X,Set),
4282 translate_bexpression_with_limit(X,TX),
4283 Eq = b(equal(X,Set),pred,[]),
4284 ajoin(['Deferred SET ',TX,' was not recognized as an enumerated set, you may want to use partition instead of the equality: '],Msg),
4285 add_warning(setup_constants_unknown,Msg,Eq,X),
4286 fail.
4287 generate_unsat_properties_warnings.
4288
4289 % -------------
4290
4291 % Complete is either complete_properties or partial_properties if properties were marked as ignore
4292 b_set_up_concrete_constants(NormalisedConstantsState,Complete) :-
4293 reset_unsat_component_infos,
4294 retractall(properties_were_filtered(_)),
4295 (no_solution_found_for_constants -> true ; assertz(no_solution_found_for_constants)),
4296 % preference(allow_incomplete_partial_setup_constants,AllowSkipping),
4297 reset_component_info(true),
4298 b_machine_has_constants_or_properties,
4299 b_get_machine_constants(UnsortedConstants),
4300 !,
4301 silent_mode(SilentMode),
4302 ? (SilentMode=on -> true ; bt_start_ms_timer('SETUP_CONSTANTS')), % TO DO: store time for unsat core
4303 b_get_properties_from_machine(MProperties),
4304 (get_preference(use_ignore_pragmas,true) % filter out prob-ignore predicates here
4305 -> conjunction_to_list(MProperties,LMP), % TO DO avoid this conversion and back
4306 exclude_count(predicate_has_ignore_pragma, LMP,LMP2,Excluded), % exclude props marked as prob-ignore
4307 conjunct_predicates(LMP2,MProperties2),
4308 %format('FILTERED (~w): ',[Excluded]),translate:print_bexpr(MProperties2),nl,
4309 (Excluded=0 -> Complete=complete_properties
4310 ; assertz(properties_were_filtered(Excluded)), Complete=partial_properties)
4311 ; MProperties2=MProperties,
4312 Complete=complete_properties
4313 ),
4314 add_additional_properties(MProperties2,Properties),
4315 project_onto_static_assertions(Properties,UnsortedConstants,PProperties,PUnsortedConstants),
4316 ? solve_properties(PProperties,PUnsortedConstants,ConstantsState),
4317 ? (SilentMode=on -> true ; bt_stop_ms_timer('SETUP_CONSTANTS')),
4318 normalise_store(ConstantsState,NormalisedConstantsState),
4319 retractall(no_solution_found_for_constants). /* ensure that b_partial_set_up_concrete_constants fails */
4320 b_set_up_concrete_constants([],complete).
4321
4322
4323 % solve already projected and filtered properties and constants, return state with solution for constants
4324 % cbc_solve_timed almost does what we want; but looks at current state; see solve_free_aux
4325 % TODO: move this to a separate module and add cdclt
4326 solve_properties(PProperties,PUnsortedConstants,ConstantsState) :-
4327 get_preference(use_solver_on_load,Solver),
4328 ? solve_properties(Solver,PProperties,PUnsortedConstants,ConstantsState).
4329
4330 solve_properties(sat,Properties,_TypedConstants,ConstantsState) :- !,
4331 ? b2sat:solve_predicate_with_satsolver_free(Properties, ConstantsState,Result,[]),
4332 Result=solution(_).
4333 solve_properties('sat-z3',Properties,_TypedConstants,ConstantsState) :- !,
4334 b2sat:solve_predicate_with_satsolver_free(Properties, ConstantsState,Result,[use_satsolver(z3)]),
4335 Result=solution(_).
4336 solve_properties(cdclt,Properties,_TypedConstants,ConstantsState) :- !,
4337 cdclt_solver:cdclt_solve_predicate(Properties, _,Result),
4338 Result=solution(ConstantsState).
4339 solve_properties(kodkod,PProperties,PUnsortedConstants,ConstantsState) :- !,
4340 ? solve_properties(prob,PProperties,PUnsortedConstants,ConstantsState). % Kodkod processing is done elswehere
4341 solve_properties(prob,PProperties,PUnsortedConstants,ConstantsState) :- !,
4342 (preferences:preference(use_static_ordering,true)
4343 -> sort_ids_by_usage(PUnsortedConstants,PProperties,Constants,no_warnings), % no_warnings as Ids could be used in operations, assertions, ...
4344 set_up_typed_localstate(Constants,_FreshVars,TypedVals,[],SortedState,positive),
4345 ? reorder_state(PUnsortedConstants,SortedState,ConstantsState)
4346 ; Constants = PUnsortedConstants,
4347 ? set_up_typed_localstate(Constants,_FreshVars,TypedVals,[],ConstantsState,positive)
4348 ),
4349 % now try and load saved constants from file for sub-machines when -cache is used:
4350 ? load_partial_constants(ConstantsState,PProperties,LPProperties), % Note: this can backtrack
4351 reset_component_info(true), % reset in case load_partial_constants backtracks! relevant for test 2112
4352 b_global_sets:static_symmetry_reduction_for_global_sets(ConstantsState),
4353 ? b_trace_test_components_full(LPProperties,ConstantsState,TypedVals).
4354 solve_properties(SolverName,Properties,_TypedConstants,ConstantsState) :-
4355 temporary_set_preference(z3_solve_for_animation, true,Chng),
4356 call_cleanup(smt_solvers_interface:smt_solve_predicate_free(SolverName, Properties, ConstantsState),
4357 reset_temporary_preference(z3_solve_for_animation,Chng)).
4358
4359
4360 b_trace_test_components_full(LPProperties,ConstantsState,TypedVals) :-
4361 init_wait_flags_and_push_call_stack(no_wf_available,operation_call('SETUP_CONSTANTS',[],unknown),WF),
4362 ? b_trace_test_components_wf(LPProperties,ConstantsState,TypedVals,WF),
4363 ground_wait_flags(WF), % WF is just a dummy waitflag to pass call stack info
4364 (unsat_or_unknown_component_exists -> (!,fail) ; true). % otherwise some expressions were skipped; use partial_set_up
4365
4366 :- volatile project_properties_on_identifiers/1.
4367 :- dynamic project_properties_on_identifiers/1.
4368 set_projection_on_static_assertions(ALL) :-
4369 % set interpreter in mode which projects out all constants not needed
4370 % for static assertion checking; all variables are also projected out
4371 retractall(project_properties_on_identifiers(_)),
4372 (b_get_assertions(ALL,dynamic,[]) -> true
4373 ; nl,print('*** WARNING: DYNAMIC B ASSERTIONS NOT EMPTY'),nl,nl),
4374 ? b_get_assertions(ALL,static,L),
4375 (L=[] -> nl,print('*** WARNING: NO STATIC B ASSERTIONS ***'),nl,nl ; true),
4376 conjunct_predicates(L,Conj),
4377 (debug_mode(on) -> print('Static Assertion: '),translate:print_bexpr(Conj),nl ; true),
4378 bsyntaxtree:predicate_identifiers(Conj,IDs),
4379 (debug_mode(on) -> print('IDS: '), print(IDs),nl ; true),
4380 assertz(project_properties_on_identifiers(IDs)).
4381
4382 % optionally project properties onto those required for checking assertions
4383 project_onto_static_assertions(Properties,Constants,NewProperties,NewConstants) :-
4384 %% set_projection_on_static_assertions(main), %% main or all %% set by probcli if we_need_only_static_assertions
4385 project_properties_on_identifiers(ProjIDs),
4386 bsyntaxtree:project_predicate_on_identifiers(Properties,ProjIDs,NewProperties,PIDs,_),
4387 sort(PIDs,SIPDs),
4388 debug_println(9,projecting(SIPDs)),
4389 include(keep_constant(SIPDs),Constants,NewConstants),!. % Constants is a typed identifier list.
4390 project_onto_static_assertions(Properties,Constants,Properties,Constants).
4391
4392 keep_constant(SIPDs,TypedID) :- get_texpr_id(TypedID,ID),ord_member(ID,SIPDs).
4393
4394
4395
4396 /* can be called if b_set_up_concrete_constants failed; will partially set up the state using values found in first ground value propagation phase */
4397 :- use_module(specfile,[get_specification_description/2]).
4398 b_partial_set_up_concrete_constants(NormalisedConstantsState) :-
4399 assert_unsat_component_infos(Status), % Status is false or unknown
4400 no_solution_found_for_constants,
4401 (b_partial_set_up_concrete_constants2(NormalisedConstantsState,Status)
4402 -> generate_unsat_properties_warnings
4403 ; generate_unsat_properties_warnings,fail).
4404
4405 b_partial_set_up_concrete_constants2(NormalisedConstantsState,Status) :-
4406 b_get_machine_constants(Constants),
4407 Constants \= [],
4408 ? (det_solution_for_constant_was_stored(Cst1) -> true), % we have found a solution for at least one constant
4409 %set_up_typed_localstate(Constants,[],ConstantsState), -> can create call_residue due to typing fd/2 values
4410 findall(bind(ID,_),(member(TID,Constants),def_get_texpr_id(TID,ID)),ConstantsState),
4411 formatsilent('SETUP_CONSTANTS not successful, but solutions were found for some constants (e.g., ~w):~n',[Cst1]),
4412 (fill_in_det_solutions(ConstantsState,FC)
4413 -> All=all, TMSG = [')']
4414 ; All=some, TMSG = [', e.g., ',Cst1,')']
4415 ),
4416 (preference(allow_incomplete_partial_setup_constants,true)
4417 -> true
4418 ; % fill_in_det_solutions will fail if not all constants valued and
4419 % if allow_incomplete_partial_setup_constants is false
4420 get_specification_description(properties,PS),
4421 % TO DO: determine if time-out occurred or not
4422 (Status=false
4423 -> ajoin([PS,' are unsatisfiable (but ',All,' CONSTANTS valued'|TMSG],Msg),
4424 add_error(setup_constants_inconsistent,Msg)
4425 ; unsat_properties_abort_error(_)
4426 -> ajoin([PS,' are unknown due to well-definedness error(s) (but ',All,' CONSTANTS valued'|TMSG],Msg),
4427 add_error(setup_constants_unknown,Msg)
4428 ; unsat_component_enumeration_warning(_)
4429 -> ajoin([PS,' are unknown due to enumeration warning(s) (but ',All,' CONSTANTS valued'|TMSG],Msg),
4430 add_error(setup_constants_unknown,Msg)
4431 ; all_unsat_components_marked_prob_ignore
4432 -> ajoin([PS,' are unknown due to prob-ignore pragmas (but ',All,' CONSTANTS valued'|TMSG],Msg),
4433 add_message(setup_constants_unknown,Msg)
4434 ;
4435 ajoin([PS,' are unknown (but ',All,' CONSTANTS valued'|TMSG],Msg),
4436 add_error(setup_constants_unknown,Msg)
4437 ),
4438 All=all % only continue if all constants valued
4439 ),
4440 normalise_store(FC,NormalisedConstantsState).
4441
4442
4443 :- use_module(store,[no_value_for_variable/2]).
4444 fill_in_det_solutions([],[]).
4445 fill_in_det_solutions([bind(Var,Val)|T],[bind(Var,FVal)|FT]) :-
4446 (det_solution_for_constant(Var,Val)
4447 -> (silent_mode(on) -> true ; write(' --det--> '),print_term_summary(bind(Var,Val))),
4448 FVal=Val
4449 ; %format('No (deterministic) solution was found or stored for constant: ~w~n',[Var]), % message printed by det_solution_for_constant
4450 (preference(allow_incomplete_partial_setup_constants,true)
4451 -> no_value_for_variable(FVal,Var)
4452 ; format('Aborting SETUP_CONSTANTS (set preference ALLOW_INCOMPLETE_SETUP_CONSTANTS to TRUE to allow ProB to proceed without having values for all CONSTANTS)~n',[]),
4453 fail
4454 )
4455 ),
4456 fill_in_det_solutions(T,FT).
4457
4458
4459
4460 /* --------------------------------- */
4461
4462 :- use_module(b_state_model_check, [b_check_valid_state/1]).
4463
4464 % note: set_up_initialisation for CBC checks does not use this predicate
4465 b_initialise_machine(ConstantsState,NormalisedInitialVarsState,FullInitialState,Path) :-
4466 ? if(b_initialise_machine2(ConstantsState,NormalisedInitialVarsState,FullInitialState,Path),
4467 true,
4468 %(add_message(initialisation_fails,'INITIALISATION FAILS'),fail)).
4469 (\+ logged_error(initialisation_fails,_,_,_), % we have already provided a more precise error message
4470 (bmachine:b_machine_temp_predicate(TempPred)
4471 -> add_message(initialisation_fails,'INITIALISATION FAILS with provided predicate',TempPred,TempPred)
4472 ; b_get_initialisation_from_machine(Stmt,_OType),
4473 add_error(initialisation_fails,'INITIALISATION FAILS','',Stmt)
4474 ),
4475 fail)
4476 ).
4477
4478 b_initialise_machine2(ConstantsState,NormalisedInitialVarsState,FullInitialState,Path) :-
4479 /* InitialVarsState is an ouput */
4480 b_get_initialisation_from_machine(InitStatement,OType),
4481 ( InitStatement=[] ->
4482 Path = [],
4483 add_message(b_initialise_machine,'Machine has no INITIALISATION statement(s)!'),
4484 NormalisedInitialVarsState = [],
4485 FullInitialState = ConstantsState
4486 ; OType == classic ->
4487 Path = [path(PathInfo)],
4488 b_get_machine_variables(DeclaredVars),
4489 set_up_undefined_localstate(DeclaredVars,ConstantsState,NewInState),
4490 /* this is if the INITIALISATION has a sequential composition; to avoid error messages */
4491 get_texpr_info(InitStatement,PosInfo),
4492 init_wait_flags_with_call_stack(WF,[operation_call('INITIALISATION',[],PosInfo)]),
4493 (bmachine:b_machine_temp_predicate(_)
4494 -> InitStatement2=InitStatement /* avoid enumerating each init statement in parallel in case additional guard links them */
4495 ; translate_init_statements(InitStatement,InitStatement2)
4496 ),
4497 ? b_execute_statement(InitStatement2,[],NewInState,InitialVarsState,WF,PathInfo),
4498 check_additional_guard(true,InitialVarsState,ConstantsState,WF),
4499 % Warning: in Z mode (e.g. test 565) the variable skeleton may not yet be set up !
4500 sort_variable_binding(InitialVarsState,NormalisedInitialVarsState),
4501 append(NormalisedInitialVarsState,ConstantsState,FullInitialState), % put constants at end to make sharing of complete tail-list easier for successor states; should be compatible with order in expand_const_and_vars
4502 split_names_and_types(DeclaredVars,DeclaredNames,DeclaredTypes),
4503 ? ground_wait_flags(WF),
4504
4505 b_enumerate_values_in_store(DeclaredNames,DeclaredTypes,_,InitialVarsState,WF) %% MOVED HERE TO AVOID that target values are enumerated before initialisation effect computed
4506 ; OType = eventb_operation(_ChangeSet,ParaValues,_Operation) ->
4507 prepare_eventb_initialisation(ConstantsState,InitialVarsUnNormState,FullInitialUnNormState),
4508 get_texpr_expr(InitStatement,
4509 rlevent(_Name,_Sec,_Stat,Parameters,_Grd,_Thm,_Act,_VWit,_PWit,_Unmod,_AbsEv)),
4510 ? b_execute_event('initialisation',InitStatement,Parameters,ParaValues,ConstantsState,FullInitialUnNormState,Path),
4511 normalise_store(InitialVarsUnNormState,NormalisedInitialVarsState),
4512 normalise_store(FullInitialUnNormState,FullInitialState) % a bit of redundant work here; we do the work twice and try to normalise constants again !
4513 ),
4514 b_check_valid_state(FullInitialState).
4515
4516 % ensure that the variables always appear in the same order as reported by b_get_machine_variables:
4517 % this is important for e.g., state_packing TO DO: we could sort them according to the variable names, but would there be a gain ??
4518 sort_variable_binding(Store,SortedStore) :- %print(sort_variable_binding(Store,SortedStore)),nl,
4519 b_get_machine_variables(Variables),
4520 sort_aux(Variables,Store,[],SortedStore).
4521 sort_aux([],S,Acc,NormRes) :- reverse(Acc,Res),
4522 normalise_store(Res,NormRes),
4523 (S=[] -> true ; add_internal_error('Unknown variable bindings: ',S)).
4524 sort_aux([TVar|T],Store,Acc,Res) :- def_get_texpr_id(TVar,ID),
4525 bselect(ID,Val,Store,Rest),
4526 sort_aux(T,Rest,[bind(ID,Val)|Acc],Res).
4527
4528 :- block bselect(?,?,-,?). % in Z mode (e.g. test 565) the variable skeleton may not yet be set up !
4529 bselect(ID,Val,[bind(ID1,Val1)|T],Rest) :- % we assume ID1 is nonvar
4530 (ID=ID1 -> Val=Val1,T=Rest
4531 ; Rest = [bind(ID1,Val1)|RT],
4532 bselect(ID,Val,T,RT)).
4533
4534 prepare_eventb_initialisation(ConstantsState,InitialVarsState,FullInitialState) :-
4535 b_get_machine_variables(Variables),
4536 empty_state(Empty),
4537 set_up_typed_localstate(Variables,_,_,Empty,InitialVarsState,positive),
4538 % NormalisedInitialVarsState = InitialVarsState, % TO DO : check that b_event normalises this
4539 combine_updates(InitialVarsState,ConstantsState,FullInitialState).
4540 % put constants at end, to be compatible with b_initialise_machine2 and expand_const_and_vars order and e.g. ltsmin
4541
4542
4543
4544 reset_b_interpreter :-
4545 %reset_partial_evaluator,
4546 retractall(project_properties_on_identifiers(_)),
4547 reset_unsat_component_infos,
4548 retractall(no_solution_found_for_constants).
4549
4550 :- use_module(eventhandling,[register_event_listener/3]).
4551 :- register_event_listener(clear_specification,reset_b_interpreter,
4552 'Reset B-Interpreter Memo Table & Unsat Components.').