1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(b_interpreter_check,[imply_test_boolean_expression/7,
6 equiv_test_boolean_expression/7,
7 equiv_bidrectional_test_boolean_expression/7,
8 get_priority_of_boolean_expression/2, get_priority_of_boolean_expression2/2,
9 b_check_boolean_expression/5,b_check_boolean_expression/7,
10 b_force_check_boolean_expression/5,
11
12 /* some lower-level propagation predicates */
13 imply/3, imply_true/2,
14 b_check_forall_wf/8, b_check_exists_wf/7,
15
16 reify_closure_with_small_cardinality/5,
17
18 register_predicate/6,
19 norm_pred_check/2, norm_expr_check/2, norm_check/2,
20
21 conjoin/6, disjoin/6,
22 check_less_than_equal/3
23 ]).
24
25 /* A version for checking the truth value of boolean-expressions,
26 the result is instantiated with pred_true/pred_false as soon as the result is known */
27 /* Warning: does not cover all expressions */
28 /* It provides SMT-like performance, for predicates involving arithmetic comparisons (<,...),
29 equality, disequality and membership/not_membership
30 It is not restricted to CNF
31 */
32
33 :- meta_predicate wd_delay(0,-,-,-).
34 :- meta_predicate wd_delay_block(0,-,-,-,-,-).
35 :- meta_predicate wd_delay_until_needed(-,0).
36 :- meta_predicate wd_delay_until_needed_block(-,-,0).
37
38 :- use_module(debug).
39 :- use_module(self_check).
40 :- use_module(error_manager).
41 :- use_module(b_interpreter,[b_compute_expression/5, b_not_test_boolean_expression/6, b_test_boolean_expression/6, b_test_boolean_expression/4]).
42 :- use_module(kernel_waitflags).
43 :- use_module(performance_messages).
44 :- use_module(translate,[print_bexpr/1, convert_and_ajoin_ids/2]).
45
46
47 :- use_module(kernel_objects,[less_than_direct/2, less_than_equal_direct/2]).
48
49 :- use_module(kernel_equality).
50
51 :- use_module(tools).
52
53 :- use_module(module_information,[module_info/2]).
54 :- module_info(group,interpreter).
55 :- module_info(description,'This module provides a reified interpreter for certain predicates.').
56
57
58
59
60 :- block imply_test_boolean_expression(-, ?,?,?,?,?,?). % TO DO: pass at least Ai to it
61 imply_test_boolean_expression(PredRes1,PredRes2, RHS,LocalState,State,WF,Ai) :-
62 (PredRes1=PredRes2
63 ? -> b_test_boolean_expression(RHS,LocalState,State,WF,Ai,_)
64 ; true
65 ).
66
67 :- block equiv_test_boolean_expression(-, ?,?,?,?,?,?).
68 equiv_test_boolean_expression(PredRes,PredRes, RHS,LocalState,State,WF,Ai) :- !,
69 ? b_test_boolean_expression(RHS,LocalState,State,WF,Ai,_).
70 equiv_test_boolean_expression(_PredRes,_, RHS,LocalState,State,WF,Ai) :-
71 ? b_not_test_boolean_expression(RHS,LocalState,State,WF,Ai,_).
72
73 equiv_bidrectional_test_boolean_expression(PredResLHS,PredResRHS, _LHS,_RHS,_LocalState,_State,WF) :-
74 PredResLHS=PredResRHS,
75 ? (var(PredResLHS)
76 -> % create a choice point to enumerate two possible solutions
77 % important, e.g., for not((y > 0 & y * y > 20) <=> (y * y > 25 & y > 0))
78 get_last_wait_flag(equivalence,WF,LWF),
79 enum_bool(PredResLHS,LWF)
80 ; true).
81 :- block enum_bool(-,-).
82 enum_bool(pred_true,_).
83 enum_bool(pred_false,_).
84 /*
85 :- block equiv_bidrectional_test_boolean_expression(-,-, ?,?,?,?,?).
86 equiv_bidrectional_test_boolean_expression(PredResLHS,PredResRHS, LHS,RHS,LocalState,State,WF) :-
87 ( PredResLHS == pred_true -> b_test_boolean_expression(RHS,LocalState,State,WF)
88 ; PredResLHS == pred_false -> b_not_test_boolean_expression(RHS,LocalState,State,WF)
89 ; PredResRHS == pred_true -> b_test_boolean_expression(LHS,LocalState,State,WF)
90 ; PredResRHS == pred_false -> b_not_test_boolean_expression(LHS,LocalState,State,WF)
91 ; add_error_fail(equiv,'Illegal values: ',equiv_bidrectional_test_boolean_expression(PredResLHS,PredResRHS))
92 ).
93 */
94
95 % return starting priority for binary choice points; should be power of 2
96 get_priority_of_boolean_expression(priority(P),Prio) :- !,
97 % case generated for disjoin by contains_fd_element, not_in_difference_set_wf, not_in_intersection_set_wf, in_union_set_wf
98 Prio=P.
99 get_priority_of_boolean_expression(already_reified(_),Prio) :- !, Prio=1.
100 get_priority_of_boolean_expression(b(Expr,_,_Infos),Prio) :- !,
101 % try to estimate a priority for performing a case split upon a predicate
102 % i.e., forcing a predicate Expr to be true/false
103 get_priority_of_boolean_expression2(Expr,Prio).
104 get_priority_of_boolean_expression(E,Prio) :-
105 add_internal_error('Boolean expression not properly wrapped: ',get_priority_of_boolean_expression(E,Prio)),
106 get_priority_of_boolean_expression2(E,Prio).
107
108 :- use_module(bsyntaxtree).
109 get_priority_of_boolean_expression2(truth,1) :- !. %, nl,nl,print('TRUTH in disjunct/conjunct'),nl.
110 get_priority_of_boolean_expression2(falsity,1) :- !. %, nl,nl,print('FALSITY in disjunct/conjunct'),nl.
111 get_priority_of_boolean_expression2(_,R) :-
112 preferences:preference(data_validation_mode,true), % in data validation mode we want to drive enumeration from data values only
113 !, R=4096.
114 get_priority_of_boolean_expression2(_,R) :- !, R=4. % force SMT style case-splitting; was 3 before using get_binary_choice_wait_flag_exp_backoff; raising this to 4 makes test 1358, 49 behave better (baload_R07 recognised possible)
115
116
117
118
119 count_number_of_conjuncts(b(Expr,_,_Infos),Prio) :- !,
120 count_number_of_conjuncts2(Expr,Prio).
121 count_number_of_conjuncts(priority(_),Prio) :- !, Prio=1.
122 count_number_of_conjuncts(B,Prio) :-
123 add_internal_error('Expression not wrapped: ',count_number_of_conjuncts(B,Prio)),Prio=1.
124 count_number_of_conjuncts2(conjunct(A,B),Nr) :- !, count_number_of_conjuncts(A,NA),
125 count_number_of_conjuncts(B,NB), Nr is NA+NB.
126 count_number_of_conjuncts2(norm_conjunct(_,RHS),Res) :- length(RHS,Len),!,
127 Res is Len+1.
128 count_number_of_conjuncts2(negation(A),Nr) :- !, count_number_of_disjuncts(A,Nr).
129 count_number_of_conjuncts2(_,1).
130
131 :- public count_number_of_disjuncts/2. %currently commented out above
132 count_number_of_disjuncts(b(Expr,_,_Infos),Prio) :- !,
133 count_number_of_disjuncts2(Expr,Prio).
134 count_number_of_disjuncts(priority(_),Prio) :- !, Prio=1.
135 count_number_of_disjuncts(B,Prio) :-
136 add_internal_error('Expression not wrapped: ',count_number_of_disjuncts(B,Prio)),Prio=1.
137 count_number_of_disjuncts2(disjunct(A,B),Nr) :- !, count_number_of_disjuncts(A,NA),
138 count_number_of_disjuncts(B,NB), Nr is NA+NB.
139 count_number_of_disjuncts2(norm_disjunct(_,RHS),Res) :- length(RHS,Len),!,
140 Res is Len+1.
141 count_number_of_disjuncts2(negation(A),Nr) :- !, count_number_of_conjuncts(A,Nr).
142 count_number_of_disjuncts2(_,1).
143
144
145
146 % we need to ensure that b_check_boolean_expression does not create a choice point on its own
147
148 b_check_boolean_expression(b(Expr,_,Infos),LS,S,WF,Res) :-
149 (composed(Expr) -> empty_avl(Ai)
150 ; Ai = no_avl), % simple expression: no sharing is possible: no need to register expressions
151 create_wfwd_needed(WF,WFD),
152 b_check_boolean_expression2(Expr,Infos,LS,S,WFD,Res,Ai,_).
153
154 composed(negation(_)).
155 composed(conjunct(_,_)).
156 composed(disjunct(_,_)).
157 composed(implication(_,_)).
158 composed(equivalence(_,_)).
159 composed(if_predicate(_,_,_)).
160 composed(let_predicate(_,_,_)).
161 composed(lazy_let_pred(_,_,_)).
162
163 b_check_boolean_expression(E,LS,S,WF,Res,Ai,Ao) :-
164 % WFD adds information about WD context: wfwd(WF_store, ExpectedVal, Val,Infos)
165 % when Val becomes nonvar: if Val==ExpectedVal we need the value of E, otherwise it should be discarded
166 create_wfwd_needed(WF,WFD),
167 ? b_check_boolean_expression1(E,LS,S,WFD,Res,Ai,Ao).
168
169 b_check_boolean_expression0(WDE,WDV,Expr,LS,S,WF,Res,Ai,Ao) :-
170 create_wfwd(WF,WDE,WDV,WFD),
171 ? b_check_boolean_expression1(Expr,LS,S,WFD,Res,Ai,Ao).
172
173
174 b_check_boolean_expression1(b(Expr,_,Infos),LS,S,WFD,Res,Ai,Ao) :- get_wd(WFD,WDE,WDV),!,
175 % print('check : '), translate:print_bexpr(b(Expr,pred,Infos)),nl,
176 (nonvar(WDV),WDE \= WDV % the expression Expr is not needed
177 -> Ai=Ao,
178 (var(Res)
179 -> Res=pred_false % set it to false, value does not matter; note: predicate is not reused
180 ; true)
181 ? ; b_check_boolean_expression2(Expr,Infos,LS,S,WFD,Res,Ai,Ao)).
182 b_check_boolean_expression1(already_reified(X),_,_,_WFD,Res,Ai,Ao) :- !,Res=X, Ai=Ao.
183 b_check_boolean_expression1(E,LS,S,WFD,Res,Ai,Ao) :-
184 add_internal_error('Boolean expression not properly wrapped: ',b_check_boolean_expression1(E,LS,S,WFD,Res,Ai,Ao)),
185 b_check_boolean_expression2(E,[],LS,S,WFD,Res,Ai,Ao).
186
187 % normalise conjunction into flat list of conjuncts
188 normalise_conjunct(b(E,_,Info)) --> normalise_conjunct2(E,Info).
189 normalise_conjunct2(conjunct(A,B),_) --> !,normalise_conjunct(A),normalise_conjunct(B).
190 normalise_conjunct2(F,Info) --> [b(F,pred,Info)].
191
192 construct_norm_conjunct(A,b(B,pred,Info)) :- construct_norm_conjunct2(A,B,Info).
193 construct_norm_conjunct2([],truth,[]).
194 construct_norm_conjunct2([H|T],Res,Info) :-
195 (T==[] -> H=b(Res,pred,Info) ; Res=norm_conjunct(H,T),Info=[]).
196 % TO DO: build up member(contains_wd_condition,Infos)
197
198
199 % normalise disjunction into flat list of disjuncts
200 normalise_disjunct(b(E,_,Info)) --> normalise_disjunct2(E,Info).
201 normalise_disjunct2(disjunct(A,B),_) --> !,normalise_disjunct(A),normalise_disjunct(B).
202 normalise_disjunct2(F,Info) --> [b(F,pred,Info)].
203
204 construct_norm_disjunct(A,b(B,pred,Info)) :- construct_norm_disjunct2(A,B,Info).
205 construct_norm_disjunct2([],falsity,[]).
206 construct_norm_disjunct2([H|T],Res,Info) :-
207 (T==[] -> H=b(Res,pred,Info) ; Res=norm_disjunct(H,T),Info=[]).
208
209 can_negate_expression(b(Expr,pred,I),b(NExpr,pred,I)) :- can_negate2(Expr,NExpr).
210 can_negate2(equal(A,B),not_equal(A,B)).
211 can_negate2(not_equal(A,B),equal(A,B)).
212 can_negate2(member(A,B),not_member(A,B)).
213 can_negate2(not_member(A,B),member(A,B)).
214 can_negate2(subset(A,B),not_subset(A,B)).
215 can_negate2(not_subset(A,B),subset(A,B)).
216 can_negate2(subset_strict(A,B),not_subset_strict(A,B)).
217 can_negate2(not_subset_strict(A,B),subset_strict(A,B)).
218 can_negate2(greater_equal(A,B),less(A,B)).
219 can_negate2(less(A,B),greater_equal(A,B)).
220 can_negate2(less_equal(A,B),greater(A,B)).
221 can_negate2(greater(A,B),less_equal(A,B)).
222 can_negate2(less_real(A,B),less_equal_real(B,A)).
223 can_negate2(less_equal_real(A,B),less_real(B,A)).
224
225 b_check_boolean_expression2(truth,_,_,_,_WFD,Res,Ai,Ao) :- !,Res=pred_true, Ai=Ao.
226 b_check_boolean_expression2(falsity,_,_,_,_WFD,Res,Ai,Ao) :- !,Res=pred_false, Ai=Ao.
227 b_check_boolean_expression2(negation(BExpr),_,LocalState,State,WFD,Res,Ai,Ao) :- !,
228 (can_negate_expression(BExpr,NBExpr)
229 -> /* avoid introducing negate propagator; maybe not necessary */
230 b_check_boolean_expression1(NBExpr,LocalState,State,WFD,Res,Ai,Ao)
231 ; negate(NR,Res),
232 b_check_boolean_expression1(BExpr,LocalState,State,WFD,NR,Ai,Ao)).
233 b_check_boolean_expression2(conjunct(LHS,RHS),CInfo,LocalState,State,WFD,Res,Ai,Ao) :- !,
234 normalise_conjunct2(conjunct(LHS,RHS),CInfo,NormRes,[]),
235 construct_norm_conjunct2(NormRes,NC,Info),
236 ? b_check_boolean_expression2(NC,Info,LocalState,State,WFD,Res,Ai,Ao).
237 b_check_boolean_expression2(norm_conjunct(LHS,RHS),_,LocalState,State,wfwd(WF,WDE,WDV,_),Res,Ai,Ao) :- !,
238 construct_norm_conjunct(RHS,NC),
239 conjoin(LR,RR,Res,LHS,NC,WF),
240 create_wfwd(WF,WDE,WDV,WFD),
241 ? b_check_boolean_expression1(LHS,LocalState,State,WFD,LR,Ai,Aii),
242 propagagate_wfwd(WDE,WDV,GuardFlag,LR,pred_false), % if WDE/=WDV then set GuardFlag to pred_false; indicating to RHS that it is not needed also
243 ? b_check_boolean_expression0(pred_true,GuardFlag,NC,LocalState,State,WF,RR,Aii,Ao).
244 b_check_boolean_expression2(implication(LHS,RHS),_,LocalState,State,wfwd(WF,WDE,WDV,_),Res,Ai,Ao) :- !,
245 imply(LR,RR,Res),
246 create_wfwd(WF,WDE,WDV,WFD),
247 b_check_boolean_expression1(LHS,LocalState,State,WFD,LR,Ai,Aii),
248 propagagate_wfwd(WDE,WDV,GuardFlag,LR,pred_false), % if WDE/=WDV then set GuardFlag to pred_false
249 ? b_check_boolean_expression0(pred_true,GuardFlag,RHS,LocalState,State,WF,RR,Aii,Ao).
250 b_check_boolean_expression2(if_predicate(Test,LHS,RHS),_,LocalState,State,wfwd(WF,WDE,WDV,_),Res,Ai,Ao) :- !,
251 if_pred(TestR,LR,RR,Res,Test,LHS,RHS,WF),
252 create_wfwd(WF,WDE,WDV,WFD),
253 b_check_boolean_expression1(Test,LocalState,State,WFD,TestR,Ai,Aii),
254 propagagate_wfwd(WDE,WDV,GuardFlag1,TestR,pred_false), % value of LHS ignored with GuardFlag1=pred_false
255 b_check_boolean_expression0(pred_true,GuardFlag1,LHS,LocalState,State,WF,LR,Aii,Aiii),
256 propagagate_wfwd(WDE,WDV,GuardFlag2,TestR,pred_true), % value of RHS ignored with GuardFlag2=pred_true
257 b_check_boolean_expression0(pred_false,GuardFlag2,RHS,LocalState,State,WF,RR,Aiii,Ao).
258 b_check_boolean_expression2(equivalence(LHS,RHS),_,LocalState,State,WFD,Res,Ai,Ao) :- !, equiv(LR,RR,Res),
259 b_check_boolean_expression1(LHS,LocalState,State,WFD,LR,Ai,Aii),
260 ? b_check_boolean_expression1(RHS,LocalState,State,WFD,RR,Aii,Ao).
261 b_check_boolean_expression2(disjunct(LHS,RHS),CInfo,LocalState,State,WFD,Res,Ai,Ao) :- !,
262 normalise_disjunct2(disjunct(LHS,RHS),CInfo,NormRes,[]),
263 construct_norm_disjunct2(NormRes,NC,Info),
264 b_check_boolean_expression2(NC,Info,LocalState,State,WFD,Res,Ai,Ao).
265 b_check_boolean_expression2(norm_disjunct(LHS,RHS),_,LocalState,State,wfwd(WF,WDE,WDV,_),Res,Ai,Ao) :- !,
266 construct_norm_disjunct(RHS,NC),
267 disjoin(LR,RR,Res,LHS,NC,WF),
268 create_wfwd(WF,WDE,WDV,WFD),
269 b_check_boolean_expression1(LHS,LocalState,State,WFD,LR,Ai,Aii),
270 propagagate_wfwd(WDE,WDV,GuardFlag,LR,pred_true),
271 b_check_boolean_expression0(pred_false,GuardFlag,NC,LocalState,State,WF,RR,Aii,Ao).
272 b_check_boolean_expression2(let_predicate(Ids,AssignmentExprs,Pred),_Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
273 wd_set_up_localstate_for_let(Ids,AssignmentExprs,LocalState,State,LetState,WFD),
274 Ao=Ai, % anything cached inside the LET may depend on Ids and should not be reused outside of LET, see test 2397
275 empty_avl(InnerAi), % we can only reuse predicates inside if Ids are fresh, see test 2398
276 b_check_boolean_expression1(Pred,LetState,State,WFD,Res,InnerAi,_).
277 b_check_boolean_expression2(lazy_let_pred(Id,AssignmentExpr,Pred),_I,LocalState,State,wfwd(WF,WDE,WDV,_),Res,Ai,Ao) :- !,
278 set_up_localstate([Id],[(Trigger,IdValue)],LocalState,LetState),
279 b_interpreter:lazy_compute_expression(Trigger,AssignmentExpr,LocalState,State,IdValue,WF,Ai),
280 create_wfwd(WF,WDE,WDV,WFD),
281 b_check_boolean_expression1(Pred,LetState,State,WFD,Res,Ai,Ao). % Lazy lets always unique, we can pass Ai
282 b_check_boolean_expression2(lazy_lookup_pred(Id),Info,LocalState,_State,WFD,Res,Ai,Ao) :- !, Ai=Ao,
283 store:lookup_value_for_existing_id(Id,LocalState,(Trigger,Value)), % should normally only occur in LocalState; value introduced by lazy_let
284 wd_delay(((Trigger,Value) = (pred_true,Res)),
285 Res,b(lazy_lookup_pred(Id),pred,Info),WFD).
286 b_check_boolean_expression2(value(V),_Info,_LocalState,_State,_WFD,Res,Ai,Ao) :- !, % this can occur when lazy_lookup_pred gets compiled by b_compiler
287 Res=V,Ai=Ao.
288 b_check_boolean_expression2(not_equal(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
289 (negate_equal_false(LHS,RHS,LHS1,RHS1)
290 -> /* X/=FALSE equivalent to X=TRUE */
291 b_check_boolean_expression3_pos(equal(LHS1,RHS1),Info,LocalState,State,WFD,Res,Ai,Ao)
292 ? ; b_check_boolean_expression3_neg(equal(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao)
293 ).
294 b_check_boolean_expression2(equal(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
295 (negate_equal_false(LHS,RHS,LHS1,RHS1)
296 -> RHS1=b(boolean_true,boolean,[]), /* X/=FALSE equivalent to X=TRUE */
297 b_check_boolean_expression3_neg(equal(LHS1,RHS1),Info,LocalState,State,WFD,Res,Ai,Ao)
298 ? ; b_check_boolean_expression3_pos(equal(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao)
299 ).
300 b_check_boolean_expression2(not_member(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
301 b_check_boolean_expression3_neg(member(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao).
302 b_check_boolean_expression2(not_subset(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
303 b_check_boolean_expression3_neg(subset(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao).
304 b_check_boolean_expression2(not_subset_strict(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
305 b_check_boolean_expression3_neg(subset_strict(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao).
306 b_check_boolean_expression2(greater(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
307 b_check_boolean_expression3_pos(less(RHS,LHS),Info,LocalState,State,WFD,Res,Ai,Ao).
308 b_check_boolean_expression2(greater_equal(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
309 b_check_boolean_expression3_neg(less(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao).
310 b_check_boolean_expression2(less_equal(LHS,RHS),Info,LocalState,State,WFD,Res,Ai,Ao) :- !,
311 b_check_boolean_expression3_neg(less(RHS,LHS),Info,LocalState,State,WFD,Res,Ai,Ao).
312 b_check_boolean_expression2(Pred,Infos,LocalState,State,WFD,Res,Ai,Ao) :-
313 ? b_check_boolean_expression3_pos(Pred,Infos,LocalState,State,WFD,Res,Ai,Ao).
314
315
316 % check whether one of the two arguments is FALSE
317 % translate X/=FALSE -> X=TRUE for normalisation purposes
318 negate_equal_false(b(boolean_false,boolean,_),E,E,b(boolean_true,boolean,[])).
319 negate_equal_false(E,b(boolean_false,boolean,_),E,b(boolean_true,boolean,[])).
320
321 b_check_boolean_expression3_pos(Pred,Infos,LocalState,State,WFD,Res,Ai,Ao) :-
322 %print(register_predicate(WFD)),nl,portray_avl(Ai),nl,
323 register_predicate_wfd(WFD,Pred,Infos,Res,Reused,Ai,Ai2),
324 (Reused=true
325 -> Ao=Ai2 % , print(reused_pred(Res,WFD,Infos)),nl
326 ? ; b_check_boolean_expression4(Pred,Infos,LocalState,State,WFD,Ok,Res),
327 (Ok=ok_to_store -> Ao=Ai2 ; Ao=Ai)
328 ).
329
330 b_check_boolean_expression3_neg(Pred,Infos,LocalState,State,WFD,NegRes,Ai,Ao) :-
331 %print(register_neg_predicate(WFD,Infos,Pred)),nl,
332 register_predicate_wfd(WFD,Pred,Infos,Res,Reused,Ai,Ai2), negate(Res,NegRes),
333 (Reused=true
334 -> Ao=Ai2
335 ? ; b_check_boolean_expression4(Pred,Infos,LocalState,State,WFD,Ok,Res),
336 (Ok=ok_to_store -> Ao=Ai2 ; Ao=Ai)
337 ).
338
339 % Register a new predicate in the AVL tree if either forced or non-WD condition inside
340 register_predicate_wfd(_,_,_,_,false,Ai,Ao) :- Ai = no_avl,!, Ai=Ao.
341 register_predicate_wfd(_,_Pred,_Infos,_,false,Ai,Ao) :-
342 preferences:preference(use_common_subexpression_elimination,true),
343 preferences:preference(use_common_subexpression_also_for_predicates,true),
344 preferences:preference(disprover_mode,false), % there are still a few things detected here that CSE does not detect (=FALSE,=TRUE,...)
345 !, % CSE already statically detects these ( all of the time !?)
346 Ai=Ao.
347 register_predicate_wfd(WFWD,Pred,Infos,PredTruthVar,Reused,Ai,Ao) :-
348 get_wd(WFWD,A,B),
349 (A==B -> register_predicate_aux(Pred,PredTruthVar,Reused,Ai,Ao) % it will be evaluated; we can share it
350 ; nonmember(contains_wd_condition,Infos) -> register_predicate_aux(Pred,PredTruthVar,Reused,Ai,Ao)
351 % Pred is not guaranteed to be evaluated: WD-condition + not in forced WFD context (beware of exists!)
352 ; register_predicate_aux(Pred,PredTruthVar,true,Ai,Ao) -> Reused=true % the predicate is already stored
353 % Note: as predicate is already stored; no problem with WD; relevant for test 1959
354 ; Ai=Ao, Reused=false % not guaranteed to be evaluated: WD-condition + not in forced WFD context
355 % ,print('NOT REGISTERING: '), translate:print_bexpr(Pred),nl
356 ).
357
358 :- assert_must_succeed((E=empty, %avl:empty_avl(E),
359 A=b(value(_VAR),integer,[]),
360 b_interpreter_check:register_predicate(equal(A,A),[],pred_true,Reused,E,A1),
361 Reused==false, A1==empty)). % ensure we do not store non-var expressions
362 :- assert_must_succeed((E=empty, %avl:empty_avl(E),
363 A=b(value(int(1)),integer,[]),
364 b_interpreter_check:register_predicate(equal(A,A),[],pred_true,Reused,E,A1),
365 Reused==false, A1 \= empty, B=b(value(_),integer,[]),
366 b_interpreter_check:register_predicate(equal(B,B),[],pred_true,Reuse2,A1,A2),
367 Reuse2==false, A2==A1)). % ensure we do not look up non-var expressions
368 :- assert_must_succeed((E=empty, %avl:empty_avl(E),
369 A=b(value(int(1)),integer,[]),
370 b_interpreter_check:register_predicate(equal(A,A),[info1],pred_true,Reused,E,A1),
371 Reused==false,
372 b_interpreter_check:register_predicate(equal(A,A),[info2],pred_true,Reuse2,A1,A2),
373 Reuse2==true, A2==A1)). % ensure registering works
374
375 % Register a new predicate in the AVL tree (for outside callers like b_interpreter.pl)
376 register_predicate(Pred,_Infos,NegPredTruthVar,Reused,Ai,Ao) :- negate_pred(Pred,NegPred),!,
377 %print(negating),nl,
378 negate(PredTruthVar,NegPredTruthVar),
379 register_predicate_aux(NegPred,PredTruthVar,Reused,Ai,Ao).
380 register_predicate(Pred,_Infos,PredTruthVar,Reused,Ai,Ao) :-
381 register_predicate_aux(Pred,PredTruthVar,Reused,Ai,Ao).
382
383 negate_typed_pred(b(A,pred,_),NegA) :- negate_pred(A,NegA).
384 negate_pred(equal(A,B),equal(AA,TRUE)) :- negate_equal_false(A,B,AA,TRUE).
385 negate_pred(not_equal(A,B),equal(A,B)). % TO DO: we should check negate_equal_false
386 negate_pred(not_member(A,B),member(A,B)).
387 negate_pred(not_subset(A,B),subset(A,B)).
388 negate_pred(not_subset_strict(A,B),subset_strict(A,B)).
389 negate_pred(greater_equal(A,B),less(A,B)).
390 negate_pred(less_equal(A,B),less(B,A)).
391 negate_pred(negation(b(A,pred,_)),A).
392
393 % to do: detect convert_bool(Pred) = X and register Pred?
394 register_predicate_aux(Pred,_PredTruthVar,Reused,Ai,Ao) :- do_not_store_pred(Pred),
395 !,
396 Ai=Ao, Reused=false.
397 register_predicate_aux(Pred,PredTruthVar,Reused,Ai,Ao) :- check_pred_truth_var(PredTruthVar),
398 norm_pred_check(Pred,NPred), % We could store this information in the info field computed by ast_cleanup ?
399 (%too_simple(NPred) -> Reused=false, Ao=Ai ; %% even for simple equalities it actually pays off !
400 reuse_predicate(NPred,Var,Ai)
401 -> % nl,print(reusing(NPred,Var)),nl, %%
402 PredTruthVar=Var,Ao=Ai, Reused=true
403 ; add_predicate(NPred,PredTruthVar,Ai,Ao), Reused=false
404 %,nl,print(not_reusing(NPred)),nl
405 ).
406
407 check_pred_truth_var(X) :- var(X),!.
408 check_pred_truth_var(pred_true) :- !.
409 check_pred_truth_var(pred_false) :- !.
410 check_pred_truth_var(X) :- add_internal_error('Illegal Predicate Truth Value: ',check_pred_truth_var(X)).
411
412 :- use_module(kernel_tools,[ground_bexpr/1]).
413 do_not_store_pred(external_pred_call(_P,_)) :- !. % expcept maybe LESS, CHOOSE,... we could check performs_io
414 do_not_store_pred(B) :-
415 (ground_bexpr(b(B,pred,[]))
416 % TO DO: improve performance: marking bexpr with potential non-ground value(.) terms inside
417 % maybe avoid registering predicates with very large values inside
418 % avoid registering predicate if it is the only one in a closure
419 -> fail
420 ; true %print('-> Not storing: '),translate:print_bexpr(b(B,pred,[])),nl
421 ).
422
423
424 % Quantifier Expansion
425
426 b_check_forall_wf(Parameters,LHS,RHS,Info,LocalState,State,WF,PredRes) :-
427 create_wfwd_needed(WF,WFD), % we expect it to be in a context where the value will be needed
428 b_check_forall_wfwd(Parameters,LHS,RHS,Info,LocalState,State,WFD,PredRes).
429 b_check_forall_wfwd(_Parameters,LHS,RHS,_Info,_LocalState,_State,_WFD,PredRes) :-
430 (is_falsity(LHS) ; is_truth(RHS)),!, % quantifier always true
431 PredRes = pred_true.
432 b_check_forall_wfwd(Parameters,LHS,RHS,Info,LocalState,State,WFD,PredRes) :-
433 ? small_quantifier_cardinality(Parameters,LHS,LHS1,LHSRest),
434 %print(expand(forall(Parameters))),nl,
435 expand_quantifier(Parameters,LHS1,List,forall,Info), %print(List),nl,
436 Body = b(implication(LHSRest,RHS),pred,Info),% translate:print_bexpr(Body),nl,
437 get_wf(WFD,WF),
438 check_expanded_forall_quantifier(List,Body, LocalState, State,WF,WFD,PredRes).
439 % TO DO: if not small_quantifier_cardinality: b_check_boolean_expression4_delay
440
441
442 b_check_exists_wf(Parameters,Body,Info,LocalState,State,WF,PredRes) :-
443 create_wfwd_needed(WF,WFD), % we expect it to be in a context where the value will be needed
444 b_check_exists_wfwd(Parameters,Body,Info,LocalState,State,WFD,_,PredRes).
445 b_check_exists_wfwd(Parameters,Body,Info,LocalState,State,WFD,ok_to_store,PredRes) :-
446 % could be generalised to take into consideration domain as restricted by Body
447 ? small_quantifier_cardinality(Parameters,Body,LHS,RHS),!,
448 % print(expanding_check_exists(_Card,Parameters)),nl, % portray_waitflags(WF),
449 expand_quantifier(Parameters,LHS,List,exists,Info),
450 % now compute a priority for the disjunction based on the number of case splits
451 % relevant for tests 1358, 1746
452 length(List,Len), % Note: if Len=1: the body must be true; no disjoin will be set up
453 get_pow2_binary_choice_priority(Len,Prio),
454 % if Len=2 -> we actually have just two possibilities T,_ and F,T; but we want Prio to start at 4 ?
455 % if Len=3 -> we have T,_,_ ; F,T,_ ; F,F,T less possibilites if disjoin enumerated from left-to-right; TO DO: should we lower the priority taking this into account ?
456 % TO DO: maybe we could directly set up an n-ary disjoin predicate;
457 % if one disjunct true; remove case-splits on other disjuncts
458 get_wf(WFD,WF),
459 check_expanded_exists_quantifier(List,Prio,RHS, LocalState, State,WF,WFD,PredRes).
460 b_check_exists_wfwd(Parameters,Body,Infos,LocalState,State,wfwd(WF,WDE,WDV,ContextInfo),do_not_store,PredRes) :-
461 % the above reification has not worked; we now "pretend" that reification worked
462 % and introduce a delayed choice point
463 % do_not_store means that the predicate result should not be re-used somewhere else, because
464 % as the predicate evaluation is delayed it may later not be needed and not evaluated, cf test 2404
465 ContextInfo \= outer_wfwd_context, % at the outer-level interpreter expects reification succeeds only if
466 % at least top-level operator was reified deterministically,
467 % important for tests 1074, 1338, 1358, 1915 with this clause enabled
468 % test 305 #x.(x + x = 1000) now works, but not 1739 (timeout)
469 reify_inner_exists_non_deterministically, % hence we currently only use it in data validation mode
470 % here we enumerate reification variables with a much lower priority (data driven enumeration)
471 % (see get_binary_choice_wait_flag_exp_backoff)
472 % this clause relevant for 0323/CCSL/TYPES_AUTORISES_RVF3_GEN__MRGA.mch
473 Pred = exists(Parameters,Body),
474 perfmessage(reify,reifiying_inner_exists_non_deterministically(Parameters),Infos),
475 b_check_boolean_expression4_delay(WDE,WDV,Pred,Infos,LocalState,State,WF,PredRes).
476
477 % true if we allow reification of exists which cannot be expanded
478 % by delayed non-det enumeration (of pred_false, pred_true) if exists is not at top-level
479 reify_inner_exists_non_deterministically :- preferences:preference(data_validation_mode,true).
480
481
482 :- use_module(b_enumerate, [b_tighter_enumerate_values_in_ctxt/3]).
483 expand_quantifier(Parameters,Pred,ListOfNewLocalStates,QuantKind,Span) :-
484 % at the moment LS,State not really needed; only necessary if non-compiled Pred can be used
485 % also: feeding in any non-bound variables in LocalState or State would cause problems in findall !
486 findall(ParLocalState,
487 (b_interpreter:set_up_typed_localstate(Parameters,ParaValues,ParamTypedVals,
488 [],ParLocalState,all_solutions),
489 kernel_waitflags:init_wait_flags_with_call_stack(WF,
490 [quantifier_call(QuantKind,Parameters,ParaValues,Span)]),
491 b_test_boolean_expression(Pred,[],ParLocalState,WF),
492 b_tighter_enumerate_values_in_ctxt(ParamTypedVals,Pred,WF),
493 kernel_waitflags:ground_wait_flags(WF)),
494 ListOfNewLocalStates).
495
496 % a version which ensures that we have unique solutions of the bindings
497 expand_quantifier_normalised(Parameters,Pred,ListOfNewLocalStates,QuantKind,Span) :-
498 expand_quantifier(Parameters,Pred,List,QuantKind,Span),
499 normalise_local_states(List,NList),
500 sort(NList,ListOfNewLocalStates). % will remove duplicates
501
502 normalise_local_states([],[]).
503 normalise_local_states([State|T],[NS|NT]) :-
504 convert_bindings_to_avl(State,NS),
505 normalise_local_states(T,NT).
506
507 :- use_module(custom_explicit_sets,[convert_to_avl/2]).
508 convert_bindings_to_avl([],[]).
509 convert_bindings_to_avl([bind(Var,Val)|T],[bind(Var,NVal)|NT]) :-
510 (convert_to_avl(Val,NVal) -> true ; add_internal_error('Cannot normalise:',Val),fail),
511 convert_bindings_to_avl(T,NT).
512
513 check_expanded_forall_quantifier([], _Body, _LS, _State,_WF,_WFD,Res) :-
514 Res=pred_true.
515 check_expanded_forall_quantifier([LS1|TLS], Body, LS, State,WF,WFD,Res) :-
516 conjoin(Res1,TRes,Res,Body,Body,WF),
517 empty_avl(InnerAi), % TO DO: maybe use no_avl ?
518 append(LS1,LS,InnerLS),
519 % Note: we do not need to guard against wd-definition from other instances inside a quantified expression
520 % either all conjuncts can be evaluated or none
521 % print(expand_forall(WFD)), translate:print_bexpr(Body),nl,
522 b_check_boolean_expression1(Body,InnerLS,State,WFD,Res1,InnerAi,_Aii),
523 %instantiate_wfwd_result(WDE,WDV,Res1),
524 check_expanded_forall_quantifier(TLS,Body,LS,State,WF,WFD,TRes).
525
526 /*
527 :- block instantiate_wfwd_result(?,-,-).
528 % instantiate a boolean variable in case it is no longer needed and not set by something else
529 instantiate_wfwd_result(WDE,WDV,Res) :-
530 (nonvar(Res) -> true
531 ; WDE==WDV -> true
532 ; Res = pred_false). */
533
534 check_expanded_exists_quantifier([], _, _Body, _LS, _State,_WF,_WFD,Res) :-
535 Res=pred_false.
536 check_expanded_exists_quantifier([LS1|TLS], Priority, Body, LS, State,WF,WFD,Res) :-
537 (TLS = [] -> Res=Res1
538 ; disjoin(Res1,TRes,Res,priority(Priority),priority(Priority),WF)), % was using Body instead of priority(Priority)
539 empty_avl(InnerAi), % TO DO: maybe use no_avl ?
540 append(LS1,LS,InnerLS),
541 b_check_boolean_expression1(Body,InnerLS,State,WFD,Res1,InnerAi,_Aii),
542 % Note: we do not need to guard against wd-definition from other instances inside a quantified expression
543 check_expanded_exists_quantifier(TLS,Priority,Body,LS,State,WF,WFD,TRes).
544
545
546 % try and convert a closure into a list of 0/1 variables for each potential element
547 reify_closure_with_small_cardinality(P,T,Body, WF,ReifiedList) :- %print(try(P)),nl,
548 create_typed_ids(P,T,Parameters),
549 small_quantifier_cardinality(Parameters,Body,LHS,RHS,350,25000), % TO DO: how to choose these parameters ?
550 % for card({x|x:1..n & x mod 3=0})=c & n=24000 -> 340 ms with reification; 320 ms without; n=74000 : 1020 ms without, 1160 with reification
551 % but there is a big difference for card({x|x:1..n & x mod 3=0 & x<10}) with n=74000 : 0 ms without reification, 1580 with; n=500: 20 ms with reification; n=250: 10 ms with reification
552 expand_quantifier_normalised(Parameters,LHS,List,comprehension_set,Body),
553 % important to normalise and have unique solutions for cardinality reification,
554 % see tests 639, 640 for card(POW(SS)-{{}}) with SS full set
555 create_wfwd_needed(WF,WFD), % is this ok ??
556 ? reifiy_list(List,RHS,WFD,ReifiedList).
557
558
559
560 reifiy_list([], _Body,_WFD,[]).
561 reifiy_list([LS1|TLS], Body,WFD,[Res_01|TRes]) :-
562 empty_avl(InnerAi),
563 ? b_check_boolean_expression1(Body,LS1,[],WFD,Res1_pred,InnerAi,_Aii),
564 prop_pred_01(Res1_pred,Res_01),
565 %format(' reify ~w : ~w~n',[Res_01,LS1]),
566 % Note: we do not need to guard against wd-definition from other instances inside a quantified expression
567 reifiy_list(TLS,Body,WFD,TRes).
568
569
570
571 :- use_module(library(lists),[select/3]).
572
573 % check if Body produces a small cardinality for the paramters Par
574 % if yes: the predicates constraining Par are put into LHS, the rest into RHS
575 % also: LHS must ensure that ground values are produced for Par and that we can enumerate with a separate WF (in expand_quantifier)
576 small_quantifier_cardinality(Par,Body,LHS,RHS) :-
577 %preferences:preference(solver_strength,SS), NL is 10+SS, SMTL is 40+SS,
578 NL=10,SMTL=40,
579 ? small_quantifier_cardinality(Par,Body,LHS,RHS,NL,SMTL). % was 10,35; raising it to 10,41 makes tests 1441, 1442 fail due to expansion of exists; raising it to 16,50 makes test 1112 fail; TO DO: investigate
580 small_quantifier_cardinality(Par,Body,LHS,RHS,NormalLimit,SMTLimit) :-
581 conjunction_to_list(Body,BodyList),
582 def_get_texpr_ids(Par,AllParas),
583 ? small_quantifier_cardinality_aux(Par,AllParas,BodyList,_UpBoundOnSize,LLHS,LRHS,NormalLimit,SMTLimit),
584 conjunct_predicates_with_pos_info(LLHS,LHS),
585 conjunct_predicates_with_pos_info(LRHS,RHS).
586
587 is_membership_or_eq(b(P,pred,Info),TLHS,RHS,Info) :- is_mem_aux(P,TLHS,RHS).
588 is_mem_aux(member(TLHS,b(RHS,_,_)),TLHS,RHS).
589 %is_mem_aux(subset(SONE,b(RHS,_,_)),TLHS,RHS) :- singleton_set_extension(SONE,TLHS).
590 is_mem_aux(equal(TLHS,b(value(V),_,_)),TLHS,value([V])). % x = V is the same as x:{V}
591 %TODO: use :- use_module(bsyntaxtree,[is_membership_or_equality/3]). % will create set_extension
592
593 % do not rely on size for anything: it is just an upper bound on the size; the actual size could be smaller
594 small_quantifier_cardinality_aux([],_,Body,Size,LHS,RHS,_,_) :- !,
595 LHS=[],RHS=Body,Size=1.
596 small_quantifier_cardinality_aux(Parameters,AllParas,[LHS|TBody],FullSize,FullLHS,FullRHS,NormalLimit,SMTLimit) :-
597 is_membership_or_eq(LHS,SID,MemRHS,Info),
598 ? constrains_ID(SID,AllParas,Parameters,RestParameters,SkelVal,SkelToUnify,BindList), % we could check RestParameters /= Parameters
599 % TO DO: we could also allow parameter to be constrained twice x: 1..100 & x: {...} ?
600 (is_small_set(MemRHS,Size,NormalLimit,SMTLimit,Info) % we have a small set of ground values: we can evaluate LHS to expand the quantifier/set_comprehension for the parameters occuring in LHS
601 -> FullLHS = [LHS|RestLHS],FullRHS = RestRHS
602 ; infer_ground_membership(MemRHS,SID,SkelVal,SkelToUnify,BindList,NormalLimit,SMTLimit, Size,InferredLHS) ->
603 % we have inferred a superset InferredLHS of MemRHS which is small and known
604 FullLHS = [InferredLHS|RestLHS], % we have added an inferred membership constraint
605 FullRHS = [LHS|RestRHS]), % the original membership LHS still needs to be checked later, after expansion of the quantifier
606 !,
607 % we select LHS to be included in FullLHS and mark parameter ID as constrained
608 small_quantifier_cardinality_aux(RestParameters,AllParas,TBody,RestSize,RestLHS,RestRHS,NormalLimit,SMTLimit),
609 FullSize is Size*RestSize,
610 is_small_size(FullSize,NormalLimit,SMTLimit, Parameters).
611 small_quantifier_cardinality_aux(Parameters,AllParas,[H|Rest],FullSize,RestLHS,[H|RestRHS],NormalLimit,SMTLimit) :- !,
612 % skip the conjunct H
613 ? small_quantifier_cardinality_aux(Parameters,AllParas,Rest,FullSize,RestLHS,RestRHS,NormalLimit,SMTLimit).
614 small_quantifier_cardinality_aux(Parameters,_AllParas,Body,ParCard,[],Body,NormalLimit,SMTLimit) :-
615 % if the remaining parameter type cardinality is small: just use "truth" as body; will instantiate parameters
616 ? b_interpreter:parameter_list_cardinality(Parameters,ParCard),
617 is_small_size(ParCard,NormalLimit,SMTLimit, Parameters).
618
619 % try and extract a ground superset (InferredLHS) of the RHS (ID:RHS) which constrains ID
620 infer_ground_membership(value(List),SID,SkelVal,SkelToUnify,BindList,NormalLimit,SMTLimit, Size,InferredLHS) :-
621 !,
622 % the List is probably not ground; let's try and see if we can extract ground matches for the parameters at least; see test 1627 (s=1..20 & x: s-->BOOL & card({t|t|->TRUE:x}):18..19)
623 extract_bind_list(BindList,LHSTerm,RHSValue),
624 has_bounded_ground_matches(List,SkelVal,SkelToUnify,RHSValue,MatchedValues,1,NrMatches), % TO DO: provide SMTLimit as upper limit
625 NrMatches = Size,
626 is_small_size(Size,NormalLimit,SMTLimit, SID),
627 get_texpr_type(LHSTerm,LHSTermType),
628 InferredLHS = b(member(LHSTerm,b(value(MatchedValues),set(LHSTermType),[])),pred,[generated]).
629 infer_ground_membership(Set,SID,SkelVal,SkelToUnify,BindList,NormalLimit,SMTLimit,Size,InferredLHS) :-
630 ? superset(Set,SuperSet),
631 % e.g., if ID: {1} /\ x -> InferredLHS = {1} and we will add ID : {1} to the LHS of the quantifier and keep ID : {1} /\ x as the RHS
632 infer_ground_mem_aux(SuperSet,SID,SkelVal,SkelToUnify,BindList,NormalLimit,SMTLimit,Size,InferredLHS).
633
634
635 superset(intersection(A,B),Set) :- (Set=A ; Set=B). % Set /\ X <: Set
636 superset(set_subtraction(Set,_),Set). % Set \ X <: Set
637 superset(domain_restriction(_,Set),Set). % X <| Set <: Set
638 superset(domain_subtraction(_,Set),Set). % X <<| Set <: Set
639 superset(range_subtraction(Set,_),Set). % Set |> X <: Set
640 superset(range_restriction(Set,_),Set). % Set |>> X <: Set
641
642 infer_ground_mem_aux(b(Set,T,I),SID,SkelVal,SkelToUnify,BindList,NormalLimit,SMTLimit, Size,InferredLHS) :-
643 (is_small_set(Set,Size,NormalLimit,SMTLimit,I)
644 -> InferredLHS = b(member(SID,b(Set,T,I)),pred,[generated])
645 ; infer_ground_membership(Set,SID,SkelVal,SkelToUnify,BindList,NormalLimit,SMTLimit, Size,InferredLHS)).
646
647 :- use_module(bsyntaxtree, [create_couple/3]).
648 % extract result of constrains_ID BindList into an Expression-Tuple for new membership constraint and a value that will be put into a value(List)
649 extract_bind_list([TID/Val],TID,Val) :- !.
650 extract_bind_list([TID/Val|BList],Couple,(Val,RestVal)) :-
651 create_couple(TID,RestExpr,Couple),
652 extract_bind_list(BList,RestExpr,RestVal).
653
654 :- use_module(kernel_tools,[can_match/2]).
655 % check if we can find a bounded / fixed number of ground matches for Skeleton Value in List
656 has_bounded_ground_matches(Var,_,_,_, _,_,_) :- var(Var),!.
657 has_bounded_ground_matches([],_SkelVal,_SkelToUnify,_,[],LenAcc,LenAcc).
658 has_bounded_ground_matches([H|T],SkelVal,SkelToUnify,ValueToStore,Matches,LenAcc,LenRes) :-
659 (can_match(H,SkelVal) -> copy_term((SkelToUnify,ValueToStore),(H,HValueToStore)),
660 ground_value(HValueToStore),
661 Matches = [HValueToStore|MT],
662 A1 is LenAcc+1 ; Matches=MT,A1=LenAcc),
663 has_bounded_ground_matches(T,SkelVal,SkelToUnify,ValueToStore,MT,A1,LenRes).
664
665 % check if the Expr contains ID, i.e., matching Expr with an element of a set will also instantiate and determine TID
666 % TO DO: also accept other patterns: records, sets?,....
667
668 % SkeletonToUnify: a skeleton that can be used to unify with any value and extracts value in BindList
669 :- assert_must_succeed(( TID = b(identifier(t),integer,[]),
670 b_interpreter_check:constrains_ID(
671 b(rec([field(a,TID),field(b,b(value(pred_true),boolean,[]))]),record([field(a,integer),field(b,boolean)]),[]),
672 [t],[TID],Rest,SkelVal,SkelUnify,Bind),
673 Rest==[], Bind = [TID2/BV], TID2==TID,
674 SkelVal = rec([field(a,_),field(b,PT)]), PT==pred_true, % skeleton must be a record value rec/1
675 SkelUnify = rec([field(a,BV2),field(b,_)]), BV2==BV,
676 % now check that the skeleton can be used to extract the ground matches for t:
677 b_interpreter_check:has_bounded_ground_matches(
678 [rec([field(a,int(1)),field(b,pred_true)]), rec([field(a,int(2)),field(b,pred_false)]),
679 rec([field(a,int(3)),field(b,_)])], SkelVal,SkelUnify,BV,Matches,1,Len),
680 Matches == [int(1),int(3)], Len==3 )).
681 :- assert_must_succeed(( TID = b(identifier(t),integer,[]),
682 b_interpreter_check:constrains_ID(
683 b(couple(TID,b(rec([field(b,b(value(pred_true),boolean,[]))]),record([field(b,boolean)]),[])),
684 couple(integer,record([field(b,boolean)])),[]),
685 [t],[TID],[],SkelVal,SkelUnify,[_/BV]),
686 b_interpreter_check:has_bounded_ground_matches(
687 [(int(1),rec([field(b,_)])), (int(2),rec([field(b,pred_false)]))], SkelVal,SkelUnify,BV,Matches,1,Len),
688 Matches == [int(1)], Len==2 )).
689 constrains_ID(b(E,_,_),AllParas,Parameters,RestParameters,SkeletonValue,SkeletonToUnify,BindList) :-
690 ? constrains_ID_aux(E,AllParas,Parameters,RestParameters,SkeletonValue,SkeletonToUnify,BindList).
691 constrains_ID_aux(couple(A,B),AllParas,Parameters,RestParameters,(V1,V2),(Skel1,Skel2),Bind) :-
692 constrains_ID(A,AllParas,Parameters,Rest1,V1,Skel1,Bind1),
693 constrains_ID(B,AllParas,Rest1,RestParameters,V2,Skel2,Bind2),
694 append(Bind1,Bind2,Bind). % TO DO: use DCGs
695 constrains_ID_aux(rec(F),AllParas,Parameters,RestParameters,rec(SkelV),rec(SkelU),Bind) :-
696 ? constrains_ID_fields(F,AllParas,Parameters,RestParameters,SkelV,SkelU,Bind).
697 constrains_ID_aux(identifier(ID),AllParas,Parameters,RestParameters,_SkelV,SkelU,Bind) :-
698 % TO DO: allow same id to appear multiple times in expression + allow to re-use parameters in another conjunct
699 ? (select(TID,Parameters,RestParameters), get_texpr_id(TID,ID)
700 -> Bind = [TID/SkelU]
701 ? ; member(ID,AllParas), % we have already used/bound ID; we will use first occurence for skeleton/bind; this one is simply ignored
702 % TO DO: we could try and see whether using the second occurence gives a better result
703 RestParameters=Parameters, Bind=[]
704 ).
705 constrains_ID_aux(value(V),_AllParas,P,P,V,_,[]) :- ground_value(V).% if not ground value we may not be able to compute all possible values for ID
706 constrains_ID_aux(boolean_true,_AllParas,P,P,pred_true,pred_true,[]). % needed ?? everything is compiled anway ?
707 constrains_ID_aux(boolean_false,_AllParas,P,P,pred_false,pred_false,[]). % needed ?? everything is compiled anway ?
708 % Below: allow any other expression as long as it only uses AllParas
709 % e.g. x+1 in : s: 1..20 --> (BOOL*(1..20)) & card({x|x|->(TRUE|->x):s})=10 & card({x|x|->(FALSE|->x+1):s})=10
710 constrains_ID_aux(add(A,B),AllParas,P,P,_,_,[]) :- % basically allow other Parameters or ground values
711 ? constrains_ID(A,AllParas,[],[],_,_,_), constrains_ID(B,AllParas,[],[],_,_,_).
712 constrains_ID_aux(minus(A,B),AllParas,P,P,_,_,[]) :- % TO DO: allow other binary/unary operators ?
713 constrains_ID(A,AllParas,[],[],_,_,_), constrains_ID(B,AllParas,[],[],_,_,_).
714 %constrains_ID_aux(Other,All,P,P,_,_,[]) :- print(other(Other)),nl,fail.
715
716 constrains_ID_fields([],_AllParas,P,P,[],[],[]).
717 constrains_ID_fields([field(Field,Val)|TF],AllParas,Parameters,RestParameters,
718 [field(Field,SkelVal)|TSkelV],[field(Field,SkelUnify)|TSkelU],Bind) :-
719 ? constrains_ID(Val,AllParas,Parameters,Rest1,SkelVal,SkelUnify,Bind1),
720 ? constrains_ID_fields(TF,AllParas,Rest1,RestParameters,TSkelV,TSkelU,Bind2),
721 append(Bind1,Bind2,Bind). % TO DO: use DCGs
722
723 :- use_module(custom_explicit_sets,[efficient_card_for_set/3]).
724
725
726 is_small_set(Val,Size,NormalLimit,SMTLimit,SrcLoc) :-
727 get_small_set_size(Val,Size),
728 is_small_size(Size,NormalLimit,SMTLimit,SrcLoc).
729
730 :- use_module(kernel_card_arithmetic,[safe_mul/3]).
731 :- use_module(kernel_tools,[ground_value/1]).
732 get_small_set_size(value(S),Size) :- !,
733 ground_value(S), % otherwise we could have S=[X] and expand_quantifier will erroneously create multiple solutions for parameter=X
734 efficient_card_for_set(S,Size,C),
735 call(C).
736 get_small_set_size(interval(From,To),Size) :- !,
737 custom_explicit_sets:is_interval_with_integer_bounds(interval(From,To),Low,Up),
738 number(Low), number(Up),
739 (Low > Up -> Size = 1 ; Size is 1+Up-Low).
740 % we provide dom/ran here explicitly as this is often used {i|i:dom(f) ...}
741 get_small_set_size(bool_set,Size) :- !, Size=2.
742 get_small_set_size(domain(b(Val,_,_)),Size) :- !,
743 get_small_domain_set_size(Val,Size). % this is only an upper bound on the size !!
744 get_small_set_size(range(b(Val,_,_)),Size) :- !,
745 get_small_set_size(Val,Size). % this is only an upper bound on the size !!
746 get_small_set_size(cartesian_product(b(A,_,_),b(B,_,_)),Size) :- !,
747 get_small_set_size(A,SizeA), number(SizeA),
748 get_small_set_size(B,SizeB), number(SizeB),
749 safe_mul(SizeA,SizeB,Size), number(Size).
750
751 %get_small_set_size(set_extension(L),Size,_,_,_) :- !, length(L,Size), is_small_size(Size). what if elements itself notknown ?? probably the case as otherwise this would have been compiled into a value
752 %get_small_set_size(sequence_extension(L),Size,_,_,_) :- !, length(L,Size), is_small_size(Size). ditto
753 %get_small_set_size(interval...
754 %get_small_set_size(domain(value([....]))...
755 % for this to work efficiently one should call b_compiler:compile on the predicates before sending them
756 % to b_interpreter_check; otherwise the sets will not yet be in value(_) form
757
758 % TO DO: the same for range or find more principled solution
759 %get_small_domain_set_size(value(S),Size) :- var(S), frozen(S,Frozen), print(var_value(S,Frozen)),nl,fail.
760 get_small_domain_set_size(value(Val),Size) :- nonvar(Val), Val=[H|T],!,
761 efficient_card_for_set([H|T],Size,C),
762 ground_domain([H|T]), % rather than requiring ground of entire list; we only require ground for domain (see test 1272)
763 call(C).
764 get_small_domain_set_size(Val,Size) :-
765 get_small_set_size(Val,Size).
766 ground_domain(V) :- var(V),!,fail.
767 ground_domain([]).
768 ground_domain([H|T]) :-
769 nonvar(H), H=(D,_),
770 ground_value(D), ground_domain(T).
771
772 is_small_size(Size,NormalLimit,SMTLimit,SrcLoc) :- number(Size), %Size \= inf,
773 (Size < NormalLimit -> true
774 ; preferences:preference(use_smt_mode,true)
775 -> preference(solver_strength,SS),
776 (Size < SMTLimit + SS
777 -> true
778 ; perfmessage(reify,'Not reifiying quantifier, try increasing SOLVER_STRENGTH: ','>'(Size,'+'(SMTLimit,SS)),SrcLoc),
779 fail
780 )
781 ; perfmessage(reify,'Not reifiying quantifier, try setting SMT preference: ','>'(Size,limit(NormalLimit)),SrcLoc),
782 fail
783 ).
784
785 % -------------------------------------
786 % EXPRESSIONS
787
788 :- use_module(store,[set_up_localstate/4]).
789
790 wd_set_up_localstate_for_let(Ids,Exprs,LocalState,State,LetState,WFD) :-
791 set_up_localstate(Ids,Vars,LocalState,LetState),
792 wd_compute_let_expressions(Exprs,Vars,LetState,State,WFD).
793 wd_compute_let_expressions([],[],_,_,_).
794 wd_compute_let_expressions([Expr|RestExprs],[Var|RestVars],LocalState,State,WFD) :-
795 b_wd_compute_expression(Expr,LocalState,State,Value,WFD),
796 kernel_objects:equal_object_optimized(Var,Value,compute_let_expressions),
797 wd_compute_let_expressions(RestExprs,RestVars,LocalState,State,WFD).
798
799
800 % compute a Prolog list of expressions:
801 b_wd_compute_expressions([], _, _, [],_WFD).
802 b_wd_compute_expressions([EXPRsHd|EXPRsTl],LocalState,State,[ValHd|ValTl],WFD) :-
803 b_wd_compute_expression(EXPRsHd,LocalState,State,ValHd,WFD),
804 b_wd_compute_expressions(EXPRsTl,LocalState,State,ValTl,WFD).
805
806 % we have to avoid trying to compute certain expressions: evaluation can fail if not well-defined !
807 b_wd_compute_expression(Expr,LocalState,State,Value,wfwd(WF,WDE,WDV,_)) :- !,
808 (nonvar(WDV)
809 -> (WDE==WDV
810 -> % print('REQUIRED: '), translate:print_bexpr(Expr),nl,
811 ? if(b_compute_expression(Expr,LocalState,State,Value,WF), % TO DO: we could use fresh variable for Value
812 true,
813 (kernel_objects:unbound_value(Value), % we have a WD error, if nonvar it could be because we expect a wrong value
814 add_wd_error_span('Well-definedness error evaluating expression: ',Expr,span_predicate(Expr,LocalState,State),WF)
815 %Value = term(undefined),
816 )
817 )
818 ; instantiate_to_any_value(Value,Expr,WF))
819 ; always_wd_no_fail_nor_error(Expr)
820 -> % print('ALWAYS WD: '), translate:print_bexpr(Expr),nl, %
821 ? b_compute_expression(Expr,LocalState,State,Value,WF)
822 ; b_compiler:b_optimize(Expr,[],LocalState,State,CExpr,WF),
823 % try compiling; this will inline values and may make the expression well_defined; relevant for test 2013
824 (always_wd_no_fail_nor_error(CExpr)
825 % it is important that this computation cannot fail and cannot raise any errors
826 % an example showing this is :wde f=[2,4] & xx:1..3 & (xx=1 or f(xx-1)=4) with -p TRY_FIND_ABORT TRUE
827 % even though the whole expression is well-defined, the function call f(xx-1) does lead
828 % to an error with xx=1
829 -> b_compute_expression(CExpr,LocalState,State,Value,WF)
830 ; % print('DELAYING DUE TO WD: '), translate:print_bexpr(CExpr),nl, %%
831 b_compute_expression_delay(WDE,WDV, CExpr,LocalState,State,Value,WF)
832 )
833 ).
834 b_wd_compute_expression(Expr,LocalState,State,Value,WFD) :-
835 add_internal_error('Illegal WFD value: ', b_wd_compute_expression(Expr,LocalState,State,Value,WFD)),fail.
836
837
838 always_wd_no_fail_nor_error(Expr) :-
839 always_well_defined(Expr).
840 % should not use always_well_defined_or_disprover_mode or WD discharged information!
841
842 :- block b_compute_expression_delay(?,-, ?,?,?,?,?).
843 b_compute_expression_delay(WDE,WDV,Expr,LocalState,State,Value,WF) :-
844 (WDE==WDV
845 -> % write('WD Evaluation: '), print(WDE),write(' =?= '), print(WDV), write(' '),translate:print_bexpr(Expr),nl,
846 b_compute_expression(Expr,LocalState,State,Value,WF)
847 ; %print(instantiate_to_any_value(Value,Expr)),nl,
848 instantiate_to_any_value(Value,Expr,WF) % does not matter anyway; but there can be pending co-routines :-(
849 ).
850
851 % WARNING: the variable could be used in another context, where it is relevant !
852
853
854 wd_delay(WDCall,Res, Expr,wfwd(WF,WDExpected,WDV,_)) :-
855 (WDExpected==WDV -> call(WDCall) % WDV truth value on left is ok: we can evaluate
856 ; nonvar(WDV) -> instantiate_to_any_value(Res,Expr,WF) % truth value not ok; we do not need the value
857 ; always_wd_no_fail_nor_error(Expr) -> call(WDCall)
858 ; wd_delay_block(WDCall,Res,Expr,WDExpected,WDV,WF)).
859 :- block wd_delay_block(?,?,?,?,-,?).
860 wd_delay_block(WDCall,Res,Expr,WDExpected,WDV,WF) :-
861 (WDExpected==WDV -> call(WDCall)
862 ; instantiate_to_any_value(Res,Expr,WF)).
863
864
865 :- use_module(typing_tools,[any_value_for_type/2]).
866 :- use_module(kernel_tools,[ground_value_check/2]).
867 %instantiate_to_any_value(V,E,_) :- print(instantiate_to_any_value(V)),nl,translate:print_bexpr(E),nl,nl,fail.
868 instantiate_to_any_value(V,_,_) :- ground_value(V),!.
869 instantiate_to_any_value(V,b(_B,TYPE,_I),WF) :-
870 get_enumeration_finished_wait_flag(WF,EWF),
871 ground_value_check(V,GV),
872 blocking_any_value_for_type(EWF,GV,TYPE,V).
873
874 :- block blocking_any_value_for_type(-,-,?,?).
875 blocking_any_value_for_type(_,_,TYPE,V) :- any_value_for_type(TYPE,V). % , print(inst2(TYPE,V)),translate:print_bexpr(b(_B,TYPE,_I)),nl.
876
877
878 :- block propagagate_wfwd(-,?,?,-,?), propagagate_wfwd(?,-,?,-,?).
879 % propagate expected and actual value guarding left with actual predicate value obtained for left
880 propagagate_wfwd(WDE,WDV,Res,F1,F2) :-
881 (F1==F2 -> Res=F1 % then value of WDE does not matter at all; Res always the same
882 ? ; propagagate_wfwd2(WDE,WDV,Res,F1,F2)).
883
884 :- block propagagate_wfwd2(-,?,?,?,?), propagagate_wfwd2(?,-,?,?,?).
885 propagagate_wfwd2(WDE,WDV,Res,F1,F2) :- (WDE==WDV -> Res=F1 ; Res=F2).
886
887 :- use_module(external_functions,[external_fun_has_wd_condition/1]).
888 :- use_module(preferences).
889 b_check_boolean_expression4(exists(Parameters,Body),Info,LocalState,State,WFD,OkToStore,Res) :- !,
890 if(b_check_exists_wfwd(Parameters,Body,Info,LocalState,State,WFD,OkToStore,Res),true,
891 (perfmessagecall(reify,cannot_reify_exists(Parameters),translate:print_bexpr(Body),Body),
892 fail)).
893 b_check_boolean_expression4(Pred,Infos,LocalState,State,WFD,ok_to_store,Res) :-
894 ? b_check_boolean_expression4_ok(Pred,Infos,LocalState,State,WFD,Res).
895
896 b_check_boolean_expression4_ok(equal(LHS,RHS),_,LocalState,State,WFD,EqRes) :- !,
897 ? b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
898 ? b_wd_compute_expression(RHS,LocalState,State,RHValue,WFD),
899 get_texpr_type(LHS,Type), get_wf(WFD,WF),
900 equality_objects_with_type_wf(Type,LHValue,RHValue,EqRes,WF).
901 % we may need to improve not_member for closure to invert symbolic operators
902 b_check_boolean_expression4_ok(member(LHS,RHS),Info,LocalState,State,WFD,Res) :-
903 %member_check_should_be_reified(LHS,RHS), % no longer need this: symbolic operators will be kept as closures if large ?!
904 !,
905 get_texpr_expr(RHS,ERHS),
906 ? b_check_member_expression(ERHS,RHS,LHS,Info,LocalState,State,WFD,Res).
907 % TO DO: compile forall, exists + setup choice point if expansion fails + remove compile calls in b_interpreter
908 b_check_boolean_expression4_ok(forall(Parameters,LHS,RHS),Info,LocalState,State,WFD,Res) :- !,
909 ? if(b_check_forall_wfwd(Parameters,LHS,RHS,Info,LocalState,State,WFD,Res),true,
910 (perfmessages_bexpr_call(reify,['Cannot reify forall over ', Pids, ': '],LHS,
911 convert_and_ajoin_ids(Parameters,Pids)),
912 fail)).
913 b_check_boolean_expression4_ok(subset(LHS,RHS),_,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
914 ? b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
915 ? b_wd_compute_expression(RHS,LocalState,State,RHValue,WFD),
916 subset_test(LHValue,RHValue,Res,WF).
917 b_check_boolean_expression4_ok(subset_strict(LHS,RHS),_,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
918 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
919 b_wd_compute_expression(RHS,LocalState,State,RHValue,WFD),
920 subset_strict_test(LHValue,RHValue,Res,WF).
921 b_check_boolean_expression4_ok(external_pred_call(FunName,Args),Info,LocalState,State,WFD,Res) :-
922 !,
923 (external_fun_has_wd_condition(FunName)
924 -> wd_delay_until_needed(WFD,b_check_external_pred_call(FunName,Args,Info,LocalState,State,WFD,Res))
925 ; b_check_external_pred_call(FunName,Args,Info,LocalState,State,WFD,Res)).
926 b_check_boolean_expression4_ok(freetype_case(FT,IsCase,Expr),_Infos,LocalState,State,WFD,Res) :- !,
927 b_wd_compute_expression(Expr,LocalState,State,freeval(FT,ActualCase,_A),WFD),
928 eq_atomic(IsCase,ActualCase,freeval_case,Res).
929 b_check_boolean_expression4_ok(finite(Expr),_Infos,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
930 b_wd_compute_expression(Expr,LocalState,State,ExprVal,WFD),
931 kernel_objects:test_finite_set_wf(ExprVal,Res,WF).
932 b_check_boolean_expression4_ok(partition(Expr,ListOfSets),_Infos,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
933 b_wd_compute_expression(Expr,LocalState,State,ExprVal,WFD),
934 b_wd_compute_expressions(ListOfSets,LocalState,State,PartitionList,WFD), % arg is a Prolog list, not a set
935 ? kernel_objects:test_partition_wf(ExprVal,PartitionList,Res,WF).
936 b_check_boolean_expression4_ok(Pred,_,LocalState,State,WFD,Res) :-
937 arithmetic_op(Pred,Op,LHS,RHS),!,
938 ? b_wd_compute_expression(LHS,LocalState,State,int(LHValue),WFD),
939 ? b_wd_compute_expression(RHS,LocalState,State,int(RHValue),WFD),
940 check_arithmetic_operator(Op,LHValue,RHValue,Res).
941 b_check_boolean_expression4_ok(Pred,_,LocalState,State,WFD,Res) :-
942 real_arithmetic_op(Pred,Op,LHS,RHS),!,
943 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
944 b_wd_compute_expression(RHS,LocalState,State,RHValue,WFD),
945 get_wf(WFD,WF),
946 real_comp_wf(Op,LHValue,RHValue,Res,WF).
947 % TO DO ???: use idea of b_artihmetic_expression to avoid intermediate CLPFD variables
948 % TO DO: add other operators, ...
949 /* use_smt_mode = full is never set; at some point we should enable the following clause by default
950 b_check_boolean_expression4_ok(Pred,Infos,LocalState,State,wfwd(WF,WDE,WDV,ContextInfos),Res) :-
951 % preferences:preference(use_smt_mode,full), %% comment out to enable check testing of complicated predicates inside;
952 % caused slowdowns of cbtc/actions_cbtc.mch (test 1751); but no longer the case
953 functor(Pred,F,N),format('~n Cannot reify ~w/~w~n~n',[F,N]),fail,
954 %ContextInfo \= outer_wfwd_context,
955 b_check_boolean_expression4_delay(WDE,WDV,Pred,Infos,LocalState,State,WF,Res).
956 */
957
958 :- use_module(library(lists),[maplist/3]).
959 % TO DO: add member(,pow_subset, fin_subset) --> subset_test
960 % we could distribute RHS=union -> disjunction, LHS=intersection -> conjunction ,... ?
961 %b_check_member_expression(EHRS,_RHS,_LHS,_,_LocalState,_State,_WFD,_Res) :-
962 % print('member : '), print(EHRS),nl,fail.
963 %b_check_member_expression(union(A,B),LHS,_,LocalState,State,WFD,Res) :-
964 b_check_member_expression(pow_subset(RHS),_,LHS,_Info,LocalState,State,WFD,Res) :- !,
965 b_check_boolean_expression4_ok(subset(LHS,RHS),[],LocalState,State,WFD,Res).
966 %b_check_member_expression(NotContainingEmptySet,_TRHS,LHS,LocalState,State,WFD,Res) :-
967 % non_empty_set_version_of(NotContainingEmptySet,RHS_With_EmptySet),
968 % % translate x:seq1(RHS) -> x /= {} & x:seq(RHS), ...
969 % % this improves propagation, in particular in light of WD issues
970 % % TO DO: avoid computing LHS twice !
971 % !,
972 % get_texpr_type(LHS,LType),
973 % EMPTYVERSION = b(member(LHS,b(RHS_With_EmptySet,set(LType),[])),pred,[]),
974 % NOTEMPTYPRED = b(not_equal(LHS,b(empty_set,LType,[])),pred,[]),
975 % print('Translating : '), translate:print_bexpr(EMPTYVERSION), print(' & '), translate:print_bexpr(NOTEMPTYPRED),nl,
976 % empty_avl(Ai), Infos=[], % Infos not important for conjunction
977 % b_check_boolean_expression2(conjunct(EMPTYVERSION,NOTEMPTYPRED),Infos,LocalState,State,WFD,Res,Ai,_).
978 b_check_member_expression(interval(Low,Up),_,LHS,_Info,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
979 % to do: should we also match interval value closure
980 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
981 b_wd_compute_expression(Low,LocalState,State,LowValue,WFD),
982 b_wd_compute_expression(Up,LocalState,State,UpValue,WFD),
983 kernel_objects:test_in_nat_range_wf(LHValue,LowValue,UpValue,Res,WF).
984 b_check_member_expression(set_extension(SetExt),_RHS,LHS,_Info,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
985 % rewrite x:{a,b,c} into x=a or x=b or x=c (is the opposite of rewrite_disjunct_to_member)
986 % The rewrite_disjunct_to_member is good when we know a membership to be true; the disjunct is better for reification
987 % Note: the problem is in particular when the result of the membership is not needed and an uninstantiated
988 % variable is used in the set extension, example y:dom(f) => (x:{f(y),0} or f(y)=0)
989 % print(mem_check_set_extension),print(' '),translate:print_bexpr(b(member(LHS,_RHS),pred,[])),nl,
990 b_wd_compute_expressions(SetExt,LocalState,State,SetExtValues,WFD),
991 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
992 get_texpr_type(LHS,Type),
993 NewLHS = b(value(LHValue),Type,[]),
994 (ground_value(SetExtValues)
995 -> % better to use normal treatment, we can compute the entire set and translate it into an AVL tree
996 maplist(construct_value(Type),SetExtValues,Vals),
997 b_wd_compute_expression(b(set_extension(Vals),set(Type),[]),LocalState,State,RHValue,WFD),
998 membership_test_wf(RHValue,LHValue,Res,WF),
999 force_membership_test(Res,LHValue,RHValue,WF)
1000 ; maplist(construct_equality(NewLHS,Type),SetExtValues,Disjuncts),
1001 construct_norm_disjunct2(Disjuncts,NC,InfoNC),
1002 empty_avl(Ai),
1003 b_check_boolean_expression2(NC,InfoNC,LocalState,State,WFD,Res,Ai,_)
1004 ).
1005 b_check_member_expression(closure(Relation),_RHS,LHS,Info,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
1006 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
1007 b_wd_compute_expression(Relation,LocalState,State,RelValue,WFD),
1008 opt_push_wait_flag_call_stack_info(WF,b_operator_call(member,
1009 [LHValue,b_operator(closure,[RelValue])],Info),WF2), % this is closure1
1010 kernel_relations:in_closure1_membership_test_wf(LHValue,RelValue,Res,WF2).
1011 b_check_member_expression(partial_function(Dom,Range),_RHS,LHS,Info,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
1012 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
1013 b_wd_compute_expression(Dom,LocalState,State,DomValue,WFD),
1014 b_wd_compute_expression(Range,LocalState,State,RangeValue,WFD),
1015 opt_push_wait_flag_call_stack_info(WF,b_operator_call(member,
1016 [LHValue,b_operator(partial_function,[DomValue,RangeValue])],Info),WF2),
1017 kernel_relations:partial_function_test_wf(LHValue,DomValue,RangeValue,Res,WF2).
1018 b_check_member_expression(total_function(Dom,Range),_RHS,LHS,Info,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
1019 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
1020 b_wd_compute_expression(Dom,LocalState,State,DomValue,WFD),
1021 b_wd_compute_expression(Range,LocalState,State,RangeValue,WFD),
1022 opt_push_wait_flag_call_stack_info(WF,b_operator_call(member,
1023 [LHValue,b_operator(total_function,[DomValue,RangeValue])],Info),WF2),
1024 kernel_relations:total_function_test_wf(LHValue,DomValue,RangeValue,Res,WF2).
1025 b_check_member_expression(partial_surjection(Dom,Range),_RHS,LHS,Info,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
1026 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
1027 b_wd_compute_expression(Dom,LocalState,State,DomValue,WFD),
1028 b_wd_compute_expression(Range,LocalState,State,RangeValue,WFD),
1029 opt_push_wait_flag_call_stack_info(WF,b_operator_call(member,
1030 [LHValue,b_operator(partial_surjection,[DomValue,RangeValue])],Info),WF2),
1031 kernel_relations:partial_surjection_test_wf(LHValue,DomValue,RangeValue,Res,WF2).
1032 b_check_member_expression(seq1(SeqType),_RHS,LHS,Info,LocalState,State,WFD,Res) :- !, get_wf(WFD,WF),
1033 b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
1034 b_wd_compute_expression(SeqType,LocalState,State,SeqTValue,WFD),
1035 opt_push_wait_flag_call_stack_info(WF,b_operator_call(member,
1036 [LHValue,b_operator(seq1,[SeqTValue])],Info),WF2),
1037 kernel_relations:test_finite_non_empty_sequence(LHValue,SeqTValue,Res,WF2).
1038 % TODO: more sequence checks seq()
1039 b_check_member_expression(_Arg,RHS,LHS,_Info,LocalState,State,WFD,Res) :- get_wf(WFD,WF),
1040 ? b_wd_compute_expression(LHS,LocalState,State,LHValue,WFD),
1041 b_wd_compute_expression(RHS,LocalState,State,RHValue,WFD),
1042 membership_test_wf(RHValue,LHValue,Res,WF),
1043 %(var(Res) -> add_message(reify,member,LHS,_Info) ; true),
1044 force_membership_test(Res,LHValue,RHValue,WF).
1045
1046 % -------------------------
1047
1048 % wfwd/4 add information about WD context to a WF store: wfwd(WF_store, ExpectedVal, Val,Infos)
1049 % when Val becomes nonvar: if Val==ExpectedVal we need the value of E, otherwise it should be discarded
1050
1051 % get WF store from WFD record
1052 get_wf(wfwd(WF,_,_,_),Res) :- !, Res=WF.
1053 get_wf(WFD,WF) :- add_internal_error('Illegal WFD store: ',get_wf(WFD,WF)),
1054 WF = no_wf_available.
1055
1056 % get expected PredicateResult and actual value; if both identical the associated expression is needed
1057 get_wd(wfwd(_,WDExpected,WDVal,_),WDE,WDV) :- !, (WDExpected,WDVal)=(WDE,WDV).
1058 get_wd(WFWD,WDE,WDV) :- add_internal_error('Illegal WFWD info:',get_wd(WFWD,WDE,WDV)), WDE=pred_true,WDV=pred_true.
1059
1060 % create a WFWF construct for an expression that is needed and where reification should only succeed
1061 % if the top-level construct at least can be fully reified (without non-determinism)
1062 create_wfwd_needed(WF,wfwd(WF,pred_true,pred_true,outer_wfwd_context)).
1063
1064 create_wfwd(WF,WDExpected,WDVal,wfwd(WF,WDExpected,WDVal,inner_wfwd_context)).
1065
1066 :- public portray_wfwd/1.
1067 portray_wfwd(wfwd(_,WDExpected,WDVal,Ctxt)) :-
1068 format('Sub-formula required if ~w is expected ~w (ctxt: ~w)~n',[WDVal,WDExpected,Ctxt]).
1069
1070 % ----------------------
1071
1072 construct_value(Type,Val,b(value(Val),Type,[])).
1073
1074 :- use_module(bsyntaxtree, [safe_create_texpr/3]).
1075 construct_equality(NewLHS,Type,ElementV,Equality) :-
1076 Element = b(value(ElementV),Type,[]),
1077 safe_create_texpr(equal(NewLHS,Element),pred,Equality). %, translate:print_bexpr(Equality),nl.
1078
1079 %non_empty_set_version_of(seq1(RHS),seq(RHS)).
1080 %non_empty_set_version_of(iseq1(RHS),iseq(RHS)).
1081 %non_empty_set_version_of(fin1_subset(RHS),fin_subset(RHS)).
1082 %non_empty_set_version_of(pow1_subset(RHS),pow_subset(RHS)).
1083
1084 % check a boolean expression without reification attempt: wait until result is known or waitflag triggered
1085 % can be useful for predicates which we know cannot be reified
1086 b_force_check_boolean_expression(b(Pred,pred,Infos),LocalState,State,WF,Res) :-
1087 b_check_boolean_expression4_delay(pred_true,pred_true,Pred,Infos,LocalState,State,WF,Res).
1088
1089 :- block b_check_boolean_expression4_delay(?,-,?,?,?,?,?,?).
1090 % currently only used for existential quantified predicates in data_validation_mode
1091 b_check_boolean_expression4_delay(WDE,WDV,_Pred,_Infos,_,_,_WF,Res) :- WDE \= WDV,
1092 % no need to check reify_inner_exists_non_deterministically, as we have marked _Pred as do_not_store
1093 % ignoring (not evaluating) predicate
1094 !,
1095 Res=pred_false. % does not matter here (but Res could have been in another context, see above and test 2404)
1096 b_check_boolean_expression4_delay(_WDE,_WDV,Pred,Infos,LocalState,State,WF,Res) :-
1097 % we currently have not yet implemented a way to check the Pred; wait until Result is known
1098 (preferences:preference(use_smt_mode,false)
1099 -> get_last_wait_flag(b_check_test_boolean_expression,WF,WF2)
1100 ; get_binary_choice_wait_flag(b_check_test_boolean_expression,WF,WF2)
1101 ),
1102 (debug_level_active_for(19) -> print(' Check Testing: '),translate:print_bexpr(Pred),nl ; true),
1103 b_check_test_boolean_expression(Res,WF2,b(Pred,pred,Infos),LocalState,State,WF).
1104
1105 :- block b_check_test_boolean_expression(-,-,?,?,?,?).
1106 %b_check_test_boolean_expression(P,LWF,Pred,LocalState,State,WF) :- write(check_test4(P,LWF)),nl,fail.
1107 b_check_test_boolean_expression(pred_true,_,Pred,LocalState,State,WF) :-
1108 b_test_boolean_expression(Pred,LocalState,State,WF).
1109 b_check_test_boolean_expression(pred_false,_,Pred,LocalState,State,WF) :-
1110 b_interpreter:b_not_test_boolean_expression(Pred,LocalState,State,WF).
1111
1112
1113 /*
1114 :- use_module(kernel_mappings).
1115 member_check_should_be_reified(_,b(RHS,_,_)) :- functor(RHS,BOP,Arity), print(check(BOP,Arity)),nl,!.
1116 member_check_should_be_reified(_,_) :- \+ preferences:preference(use_smt_mode,false),!.
1117 member_check_should_be_reified(_LHS,b(RHS,_,_)) :- functor(RHS,BOP,Arity),
1118 % check if we have optimized treatments available, for which we do not yet have reified versions
1119 (Arity=1 -> \+ kernel_mappings:unary_in_boolean_type(BOP,_)
1120 ; Arity=2 -> \+ kernel_mappings:binary_in_boolean_type(BOP,_)
1121 ; Arity=0 -> \+ kernel_mappings:cst_in_boolean_type(BOP,_)
1122 ; true).
1123 */
1124
1125
1126 :- block force_membership_test(-,?,?,?).
1127 % currently required for ensuring that following fails:
1128 % kernel_objects:union(closure(['_zzzz_unit_tests'],[integer],b(member(b(identifier('_zzzz_unit_tests'),integer,[generated]),b(value([int(3),int(4)]),set(integer),[])),pred,[])),closure(['_zzzz_unit_tests'],[integer],b(member(b(identifier('_zzzz_unit_tests'),integer,[generated]),b(value([int(2),int(1)]),set(integer),[])),pred,[])),[int(1),int(3),int(2)])
1129 % Reason: membership_test does not on its own enumerate
1130 force_membership_test(pred_true,X,Set,WF) :-
1131 Set \= [],
1132 (ground_value(X) -> true
1133 ; nonvar(Set),no_use_forcing(Set) -> true % no use in forcing membership, will call same element_of_avl_set_wf
1134 ? ; kernel_objects:check_element_of_wf(X,Set,WF)
1135 ).
1136 force_membership_test(pred_false,_X,_Set,_WF).
1137
1138 % forcing is sometimes useful because we can transmit a WF, currently some of the reification predicates
1139 % do not have a WF-Store and can thus do limited enumeration ! in particular true for CLPFD = FALSE mode
1140 no_use_forcing(avl_set(_)) :- preferences:preference(use_clpfd_solver,true).
1141 no_use_forcing(global_set(_)).
1142 %no_use_forcing(closure(_,_,B)) :- preferences:preference(use_clpfd_solver,true).
1143
1144
1145
1146 :- use_module(external_functions,[call_external_predicate/8, do_not_evaluate_args/1]).
1147 b_check_external_pred_call(FunName,Args,Info,LocalState,State,WFD,Res) :-
1148 get_wf(WFD,WF),
1149 (do_not_evaluate_args(FunName) -> EvaluatedArgs=[]
1150 ; b_wd_compute_expressions(Args, LocalState,State, EvaluatedArgs, WFD)),
1151 push_wait_flag_call_stack_info(WF,external_call(FunName,EvaluatedArgs,Info),WF2),
1152 call_external_predicate(FunName,Args,EvaluatedArgs,LocalState,State,Res,Info,WF2).
1153
1154 wd_delay_until_needed(WFWD,Call) :-
1155 get_wd(WFWD,WDExpected,WDV),
1156 wd_delay_until_needed_block(WDExpected,WDV,Call).
1157 :- block wd_delay_until_needed_block(-,?,?), wd_delay_until_needed_block(?,-,?).
1158 wd_delay_until_needed_block(WDExpected,WDV,Call) :- WDExpected==WDV,!,
1159 call(Call).
1160 wd_delay_until_needed_block(_,_,_). % first call not needed
1161
1162
1163 :- use_module(library(avl)).
1164 reuse_predicate(_,_,no_avl) :- !,fail.
1165 reuse_predicate(Pred,Var,AVL) :-
1166 avl_fetch(Pred,AVL,Var),!. %pred_var(Var)).
1167 reuse_predicate(Pred,Var,AVL) :- %print(check(Pred)),nl, portray_avl(AVL),nl,
1168 preferences:preference(use_smt_mode,true), % it does not seem very expensive; we could always enable it
1169 ? implied_by(Pred,Val,OtherPred,OVal),
1170 avl_fetch(OtherPred,AVL,OVar), OVar==OVal,!,
1171 %print(reused_due_to_implication(Pred)),nl,nl,
1172 Var=Val.
1173
1174 add_predicate(_Pred,_Var,no_avl,NewAVL) :- !, NewAVL=no_avl.
1175 add_predicate(Pred,Var,AVL,NewAVL) :-
1176 % we could compute terms:term_hash(Pred,H) and add pred(H,Pred) to AVL to avoid comparing terms during avl_fetch
1177 (avl_store(Pred,AVL,Var,NewAVL) -> true ; NewAVL=no_avl). %pred_var(Var),NewAVL).
1178
1179 % detect whether predicate implied by some registered predicate
1180 % detects inconsistency in x:INTEGER & x>y & y>x
1181 % very lightweight propagation also achieved by CHR for less
1182 implied_by(less(A,B),pred_false,less(B,A),pred_true). % A>B => not( A<B ) <=> A>=B
1183 implied_by(subset_strict(A,B),pred_false,subset_strict(B,A),pred_true). % B <<: A => not( A<<:B )
1184 implied_by(subset_strict(A,B),pred_false,subset(B,A),pred_true). % B <: A => not( A<<:B )
1185 implied_by(subset(A,B),pred_false,subset_strict(B,A),pred_true). % B <<: A => not( A<:B )
1186 % TO DO: add more rules; e.g., less(x,10) implied by less(x,9)
1187
1188 % normalises a typed predicate by removing position information and ordering commutative operators in a canonical way
1189 norm_pred_check(B,Res) :-
1190 ( norm_pred(B,Res)
1191 -> true
1192 ; bget_functor(B,F,N),
1193 print(norm_pred_failed(F/N)), nl,
1194 print_bexpr(B), nl,
1195 Res=B
1196 ).
1197
1198 bget_functor(b(B,_,_),F,N) :- functor(B,F,N).
1199 bget_functor(B,F,N) :- functor(B,F,N).
1200
1201 %% :-(+List, -UntypedConj).
1202 conjunct_untyped([], Res) :- !, Res=truth.
1203 conjunct_untyped([P|Rest],Result) :- conjunct2(Rest,P,Result).
1204 conjunct2([],P,P).
1205 conjunct2([Q|Rest],P,Result) :- conjunct2(Rest,conjunct(P,Q),Result).
1206
1207 %% disjunct_untyped(+List, -UntypedDisj).
1208 disjunct_untyped([], Res) :- !, Res=falsity.
1209 disjunct_untyped([P|Rest],Result) :- disjunct2(Rest,P,Result).
1210 disjunct2([],P,P).
1211 disjunct2([Q|Rest],P,Result) :- disjunct2(Rest,disjunct(P,Q),Result).
1212
1213 :- assert_must_succeed((I=b(identifier(i),integer,[]),P1=b(greater_equal(I,I),pred,[]),norm_pred(P1,N1),
1214 P2=b(greater_equal(I,I),pred,[info]),norm_pred(P2,N2), N2==N1)). % info ignored
1215 :- assert_must_succeed((I1=b(identifier(i1),integer,[]),I2=b(identifier(i2),integer,[]),
1216 P1=b(equal(I1,I2),pred,[]),norm_pred(P1,N1),
1217 P2=b(equal(I2,I1),pred,[info]),norm_pred(P2,N2), N2==N1)). % equal re-ordered
1218 :- assert_must_succeed((I1=b(identifier(i1),integer,[]),I2=b(identifier(i2),integer,[]),
1219 P1=b(greater_equal(I1,I2),pred,[]),norm_pred(P1,N1),
1220 P2=b(less_equal(I2,I1),pred,[info]),norm_pred(P2,N2), N2==N1)). % <= and >= re-ordered
1221 :- assert_must_succeed((I1=b(identifier(i1),integer,[]),I2=b(identifier(i2),integer,[]),
1222 P1=b(greater(I1,I2),pred,[]),norm_pred(P1,N1),
1223 P2=b(less(I2,I1),pred,[info]),norm_pred(P2,N2), N2==N1)). % < and > re-ordered
1224 :- assert_must_succeed((I1=b(identifier(i1),integer,[]),I2=b(identifier(i2),integer,[]),
1225 P1=b(greater(I1,I2),pred,[]),norm_pred(P1,N1),
1226 P2=b(less_equal(I2,I1),pred,[]),norm_pred(P2,N2), N2 \= N1)). % > and <= not made equal
1227 :- assert_must_succeed((I=b(identifier(i),integer,[]),P1=b(greater_equal(I,I),pred,[was(test1)]),
1228 P2=b(not_equal(I,I),pred,[was(test2)]),
1229 conjunct_predicates_with_pos_info([P1,P2],C1),norm_pred(C1,N1),
1230 conjunct_predicates_with_pos_info([P2,P1],C2),norm_pred(C2,N2), N2==N1)). % conjunct re-ordered
1231 :- assert_must_succeed((I=b(identifier(i),integer,[]),P1=b(greater_equal(I,I),pred,[was(test1)]),
1232 P2=b(not_equal(I,I),pred,[was(test2)]), P3=b(equal(I,I),pred,[was(test3)]),
1233 conjunct_predicates_with_pos_info([P1,P2,P3],C1),norm_pred(C1,N1),
1234 conjunct_predicates_with_pos_info([P2,P3,P1],C2),norm_pred(C2,N2), N2==N1)).
1235
1236 %% norm_pred(+AstOrExpr, -Norm).
1237 norm_pred(X,Res) :- var(X),!,Res=X.
1238 norm_pred(b(B,_,_),Res) :- !, norm_pred(B,Res).
1239 norm_pred(falsity,Res) :- !, Res=falsity.
1240 norm_pred(truth,Res) :- !, Res=truth.
1241 norm_pred(conjunct(A,B),Res) :-
1242 !,
1243 flatten_conjunctions([A,B],CList),
1244 % sort nested conjunctions and disjunctions instead of only single ones
1245 % e.g., difference for '#i.(i : NATURAL & (i > `max`(self) & num′ = num <+ {self |-> i}))' if removing nested parentheses
1246 l_norm_pred(CList, NormedList),
1247 sort(NormedList,SortedList), % better to sort after normalisation
1248 conjunct_untyped(SortedList, Res).
1249 norm_pred(disjunct(A,B),Res) :-
1250 !,
1251 disjunction_to_list(b(disjunct(A,B),pred,[]), CList), % it would be more efficient not to re-construct the b/3 term
1252 l_norm_pred(CList, NormedList),
1253 sort(NormedList,SortedList),
1254 disjunct_untyped(SortedList, Res).
1255 norm_pred(equal(A,B),Res) :- !,norm_expr(A,AA),norm_expr(B,BB),
1256 (BB @< AA -> Res = equal(AA,BB) ; Res= equal(BB,AA)).
1257 norm_pred(equivalence(A,B),Res) :- !, norm_pred(A,AA), norm_pred(B,BB),
1258 (BB @< AA -> Res = equivalence(AA,BB) ; Res= equivalence(BB,AA)).
1259 norm_pred(exists(A,B),Res) :- !, Res=exists(AA,BB),l_norm_expr(A,AA), norm_pred(B,BB).
1260 norm_pred(finite(A),finite(AA)) :- !,norm_expr(A,AA).
1261 norm_pred(forall(A,B,C),Res) :- !, Res=forall(AA,BB,CC),l_norm_expr(A,AA), norm_pred(B,BB), norm_pred(C,CC).
1262 norm_pred(greater(A,B),Less) :- !,norm_expr(A,AA),norm_expr(B,BB), norm_less(BB,AA,Less).
1263 norm_pred(greater_equal(A,B),Leq) :- !,norm_expr(A,AA),norm_expr(B,BB), norm_less_equal(BB,AA,Leq).
1264 norm_pred(if_predicate(A,B,C),Res) :- !, % we could rewrite this to implications but check ok for WD prover
1265 Res=if_predicate(AA,BB,CC), norm_pred(A,AA), norm_pred(B,BB), norm_pred(C,CC).
1266 norm_pred(implication(A,B),Res) :- !, % we could rewrite this to disjunct(not(A),B); but check ok for WD prover
1267 Res=implication(AA,BB),norm_pred(A,AA), norm_pred(B,BB).
1268 norm_pred(less(A,B),Less) :- !,norm_expr(A,AA),norm_expr(B,BB), norm_less(AA,BB,Less).
1269 norm_pred(less_real(A,B),less_real(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1270 norm_pred(less_equal(A,B),Leq) :- !,norm_expr(A,AA),norm_expr(B,BB), norm_less_equal(AA,BB,Leq).
1271 norm_pred(less_equal_real(A,B),less_equal_real(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1272 norm_pred(let_predicate(A,B,C),Res) :- !,
1273 Res=let_predicate(AA,BB,CC),
1274 l_norm_expr(A,AA), l_norm_expr(B,BB),norm_pred(C,CC).
1275 norm_pred(lazy_let_pred(A,B,C),Res) :- !,
1276 Res = lazy_let_pred(AA,BB,CC),
1277 norm_expr(A,AA),
1278 norm_pred_or_expr(B,BB),norm_pred(C,CC).
1279 norm_pred(lazy_lookup_pred(A),Res) :- !, Res = lazy_lookup_pred(A).
1280 norm_pred(member(A,B),member(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1281 norm_pred(negation(A),Res) :- !,
1282 (negate_typed_pred(A,NegA) -> norm_pred(NegA,Res)
1283 ; Res=negation(AA), norm_pred(A,AA)).
1284 norm_pred(not_equal(A,B),Res) :- !,norm_expr(A,AA),norm_expr(B,BB),
1285 (BB @< AA -> Res = not_equal(AA,BB) ; Res= not_equal(BB,AA)).
1286 norm_pred(not_member(A,B),not_member(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1287 norm_pred(not_subset(A,B),not_subset(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1288 norm_pred(not_subset_strict(A,B),not_subset_strict(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1289 norm_pred(partition(A,L),partition(AA,LL)) :- !,norm_expr(A,AA),l_norm_expr(L,LL).
1290 norm_pred(subset(A,B),subset(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1291 norm_pred(subset_strict(A,B),subset_strict(AA,BB)) :- !,norm_expr(A,AA),norm_expr(B,BB).
1292 norm_pred(freetype_case(Type,Case,A),freetype_case(Type,Case,AA)) :- !,norm_expr(A,AA).
1293 norm_pred(X,X). % :- print(norm_pred(X)),nl.
1294
1295
1296 l_norm_pred([],[]).
1297 l_norm_pred([H|T],[NH|NT]) :- norm_pred(H,NH), l_norm_pred(T,NT).
1298
1299 norm_pred_or_expr(b(B,pred,_),Res) :- norm_pred(B,Res).
1300 norm_pred_or_expr(B,Res) :- norm_expr(B,Res).
1301
1302 norm_less(unary_minus(A),MB,Res) :- apply_unary_minus(MB,B), !,norm_less(B,A,Res). % -A < -B => A > B
1303 % we could also move unary_minus to B if not present
1304 norm_less(MA,unary_minus(B),Res) :- apply_unary_minus(MA,A), !,norm_less(B,A,Res).
1305 norm_less(A,B,less(A,B)).
1306
1307 apply_unary_minus(unary_minus(A),A).
1308 apply_unary_minus(Nr,MNr) :- number(Nr), MNr is -Nr.
1309
1310 norm_less_equal(unary_minus(A),MB,Res) :- apply_unary_minus(MB,B), !,norm_less_equal(B,A,Res). % -A <= -B => A >= B
1311 norm_less_equal(MA,unary_minus(B),Res) :- apply_unary_minus(MA,A), !,norm_less_equal(B,A,Res).
1312 norm_less_equal(A,B,less_equal(A,B)).
1313
1314 % ---------------------
1315
1316 % generic normalisation predicate
1317 norm_check(BExpr,Res) :- BExpr = b(_,pred,_),!, norm_pred_check(BExpr,Res).
1318 norm_check(BExpr,Res) :- norm_expr_check(BExpr,Res).
1319
1320 % normalise expressions and check for failure
1321 norm_expr_check(X,Res) :- var(X),!,Res=X.
1322 norm_expr_check(b(B,_,_),Res) :- !, norm_expr_check2(B,Res).
1323 norm_expr_check(X,X).
1324
1325 norm_expr_check2(B,Res) :-
1326 (norm_expr2(B,Res) -> true
1327 ; functor(B,F,N),print(norm_expr2_failed(F/N)),nl,
1328 Res=B).
1329
1330 norm_expr(X,Res) :- var(X),!,Res=X.
1331 norm_expr(b(B,_,_),Res) :- !, norm_expr2(B,Res).
1332 %norm_expr_check2(B,Res). %% comment in to obtain details about failed normalisation for expressions
1333 norm_expr(X,X). % :- add_internal_error('Expr not wrapped:',norm_expr(X,X)).
1334
1335 :- use_module(kernel_reals,[construct_real_number/2]).
1336 norm_expr2(assertion_expression(Cond,E,Expr),assertion_expression(AA,E,BB)) :- norm_pred(Cond,AA),norm_expr(Expr,BB).
1337 norm_expr2(add(A,B),Res) :- norm_expr(A,AA), norm_expr(B,BB), (BB @< AA -> Res = add(AA,BB) ; Res= add(BB,AA)).
1338 norm_expr2(add_real(A,B),add_real(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1339 norm_expr2(bag_items(A),bag_items(AA)) :- norm_expr(A,AA).
1340 norm_expr2(boolean_false,boolean_false).
1341 norm_expr2(boolean_true,boolean_true).
1342 norm_expr2(bool_set,bool_set).
1343 norm_expr2(card(A),card(AA)) :- norm_expr(A,AA).
1344 norm_expr2(cartesian_product(A,B),cartesian_product(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1345 norm_expr2(closure(A),closure(AA)) :- norm_expr(A,AA). % this is closure1
1346 norm_expr2(compaction(A),compaction(AA)) :- norm_expr(A,AA).
1347 norm_expr2(composition(A,B),composition(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1348 norm_expr2(comprehension_set(A,B),comprehension_set(AA,BB)) :- l_norm_expr(A,AA), norm_pred(B,BB).
1349 norm_expr2(concat(A,B),concat(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1350 norm_expr2(convert_bool(A),convert_bool(AA)) :- norm_pred_check(A,AA).
1351 norm_expr2(convert_real(A),convert_real(AA)) :- norm_expr(A,AA).
1352 norm_expr2(convert_int_floor(A),convert_int_floor(AA)) :- norm_expr(A,AA).
1353 norm_expr2(convert_int_ceiling(A),convert_int_ceiling(AA)) :- norm_expr(A,AA).
1354 norm_expr2(couple(A,B),couple(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1355 norm_expr2(direct_product(A,B),direct_product(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1356 norm_expr2(div(A,B),div(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1357 norm_expr2(div_real(A,B),div_real(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1358 norm_expr2(floored_div(A,B),floored_div(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1359 norm_expr2(domain_restriction(A,B),domain_restriction(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1360 norm_expr2(domain_subtraction(A,B),domain_subtraction(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1361 norm_expr2(domain(A),domain(AA)) :- norm_expr(A,AA).
1362 norm_expr2(empty_sequence,empty_sequence).
1363 norm_expr2(empty_set,empty_set).
1364 norm_expr2(event_b_identity,event_b_identity).
1365 norm_expr2(external_function_call(A,B),external_function_call(A,BB)) :- l_norm_expr(B,BB).
1366 norm_expr2(fin_subset(A),fin_subset(AA)) :- norm_expr(A,AA).
1367 norm_expr2(fin1_subset(A),fin1_subset(AA)) :- norm_expr(A,AA).
1368 norm_expr2(first(A),first(AA)) :- norm_expr(A,AA).
1369 norm_expr2(first_of_pair(A),first_of_pair(AA)) :- norm_expr(A,AA).
1370 norm_expr2(first_projection(A,B),first_projection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1371 norm_expr2(float_set,float_set).
1372 norm_expr2(front(A),front(AA)) :- norm_expr(A,AA).
1373 norm_expr2(function(A,B),function(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1374 norm_expr2(general_concat(A),general_concat(AA)) :- norm_expr(A,AA).
1375 norm_expr2(general_intersection(A),general_intersection(AA)) :- norm_expr(A,AA).
1376 norm_expr2(general_product(A,B,C),Res) :- !,
1377 Res=general_product(AA,BB,CC),l_norm_expr(A,AA), norm_pred(B,BB), norm_expr(C,CC).
1378 norm_expr2(general_sum(A,B,C),Res) :- !,
1379 Res=general_sum(AA,BB,CC),l_norm_expr(A,AA), norm_pred(B,BB), norm_expr(C,CC).
1380 norm_expr2(general_union(A),general_union(AA)) :- norm_expr(A,AA).
1381 norm_expr2(identifier(A),'$'(A)). % need wrapper to avoid confusion with other terms !
1382 norm_expr2(identity(A),identity(AA)) :- norm_expr(A,AA).
1383 norm_expr2(if_then_else(P,A,B),if_then_else(PP,AA,BB)) :- norm_pred(P,PP),norm_expr(A,AA), norm_expr(B,BB).
1384 norm_expr2(image(A,B),image(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1385 norm_expr2(insert_front(A,B),insert_front(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1386 norm_expr2(insert_tail(A,B),insert_tail(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1387 norm_expr2(integer_set(A),A).
1388 norm_expr2(integer(A),A). % integer represented as number
1389 norm_expr2(intersection(A,B),Res) :- norm_expr(A,AA), norm_expr(B,BB),
1390 (BB @< AA -> Res = intersection(AA,BB) ; Res= intersection(BB,AA)).
1391 norm_expr2(interval(A,B),interval(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1392 norm_expr2(iseq(A),iseq(AA)) :- norm_expr(A,AA).
1393 norm_expr2(iseq1(A),iseq1(AA)) :- norm_expr(A,AA).
1394 norm_expr2(iteration(A,B),iteration(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1395 norm_expr2(last(A),last(AA)) :- norm_expr(A,AA).
1396 norm_expr2(lazy_let_expr(A,B,C),lazy_let_expr(AA,BB,CC)) :-
1397 norm_expr(A,AA),norm_pred_or_expr(B,BB),norm_expr(C,CC).
1398 norm_expr2(lazy_lookup_expr(A),lazy_lookup_expr(A)) :- !.
1399 norm_expr2(let_expression(A,B,C),let_expression(AA,BB,CC)) :- l_norm_expr(A,AA), l_norm_expr(B,BB),norm_expr(C,CC).
1400 norm_expr2(let_expression_global(A,B,C),let_expression_global(AA,BB,CC)) :- l_norm_expr(A,AA), l_norm_expr(B,BB),norm_pred(C,CC).
1401 norm_expr2(max(A),max(AA)) :- norm_expr(A,AA).
1402 norm_expr2(max_real(A),max_real(AA)) :- norm_expr(A,AA).
1403 norm_expr2(max_int,max_int).
1404 norm_expr2(min(A),min(AA)) :- norm_expr(A,AA).
1405 norm_expr2(min_real(A),min_real(AA)) :- norm_expr(A,AA).
1406 norm_expr2(min_int,min_int).
1407 norm_expr2(minus(A,B),minus(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1408 norm_expr2(minus_or_set_subtract(A,B),minus_or_set_subtract(AA,BB)) :- write(cannot_normalise_minus_or_set_subtract),nl,
1409 norm_expr(A,AA), norm_expr(B,BB). % should have been removed by cleanup_pre !!
1410 norm_expr2(minus_real(A,B),minus_real(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1411 norm_expr2(modulo(A,B),modulo(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1412 norm_expr2(mu(A),mu(AA)) :- norm_expr(A,AA).
1413 norm_expr2(multiplication(A,B),Res) :-
1414 norm_expr(A,AA), norm_expr(B,BB), (BB @< AA -> Res = multiplication(AA,BB) ; Res= multiplication(BB,AA)).
1415 norm_expr2(mult_or_cart(A,B),mult_or_cart(AA,BB)) :- write(cannot_normalise_mult_or_cart),nl,
1416 norm_expr(A,AA), norm_expr(B,BB). % should have been removed by cleanup_pre !!
1417 norm_expr2(multiplication_real(A,B),multiplication_real(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1418 norm_expr2(operation_call_in_expr(A,B),operation_call_in_expr(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1419 norm_expr2(overwrite(A,B),overwrite(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1420 norm_expr2(parallel_product(A,B),parallel_product(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1421 norm_expr2(partial_bijection(A,B),partial_bijection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1422 norm_expr2(partial_function(A,B),partial_function(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1423 norm_expr2(partial_injection(A,B),partial_injection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1424 norm_expr2(partial_surjection(A,B),partial_surjection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1425 norm_expr2(perm(A),perm(AA)) :- norm_expr(A,AA).
1426 norm_expr2(power_of(A,B),power_of(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1427 norm_expr2(power_of_real(A,B),power_of_real(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1428 norm_expr2(pow_subset(A),pow_subset(AA)) :- norm_expr(A,AA).
1429 norm_expr2(pow1_subset(A),pow1_subset(AA)) :- norm_expr(A,AA).
1430 norm_expr2(predecessor,predecessor).
1431 % quantified_intersection, quantified_union : should be removed by ast_cleanup
1432 norm_expr2(range_restriction(A,B),range_restriction(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1433 norm_expr2(range_subtraction(A,B),range_subtraction(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1434 norm_expr2(range(A),range(AA)) :- norm_expr(A,AA).
1435 norm_expr2(real(Atom),Nr) :- construct_real_number(Atom,Nr).
1436 norm_expr2(real_set,real_set).
1437 norm_expr2(rec(A),rec(AA)) :- norm_fields(A,AA).
1438 norm_expr2(record_field(A,Field),record_field(AA,Field)) :- norm_expr(A,AA).
1439 norm_expr2(relations(A,B),relations(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1440 norm_expr2(restrict_front(A,B),restrict_front(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1441 norm_expr2(restrict_tail(A,B),restrict_tail(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1442 norm_expr2(reflexive_closure(A),reflexive_closure(AA)) :- norm_expr(A,AA). % this is rewritten in ast_cleanup
1443 norm_expr2(rev(A),rev(AA)) :- norm_expr(A,AA).
1444 norm_expr2(reverse(A),reverse(AA)) :- norm_expr(A,AA).
1445 norm_expr2(second_of_pair(A),second_of_pair(AA)) :- norm_expr(A,AA).
1446 norm_expr2(second_projection(A,B),second_projection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1447 norm_expr2(seq(A),seq(AA)) :- norm_expr(A,AA).
1448 norm_expr2(seq1(A),seq1(AA)) :- norm_expr(A,AA).
1449 norm_expr2(sequence_extension(L),sequence_extension(NL)) :- l_norm_expr(L,NL).
1450 norm_expr2(set_extension(L),set_extension(NL)) :- l_norm_expr(L,NL).
1451 norm_expr2(set_subtraction(A,B),set_subtraction(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB). % set difference
1452 norm_expr2(size(A),size(AA)) :- norm_expr(A,AA).
1453 norm_expr2(string(A),string(A)). % need wrapper to avoid confusion with other terms !
1454 norm_expr2(string_set,string_set).
1455 norm_expr2(struct(A),struct(AA)) :- norm_expr(A,AA).
1456 norm_expr2(successor,successor).
1457 norm_expr2(surjection_relation(A,B),surjection_relation(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1458 norm_expr2(tail(A),tail(AA)) :- norm_expr(A,AA).
1459 norm_expr2(total_bijection(A,B),total_bijection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1460 norm_expr2(total_function(A,B),total_function(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1461 norm_expr2(total_injection(A,B),total_injection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1462 norm_expr2(total_relation(A,B),total_relation(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1463 norm_expr2(total_surjection(A,B),total_surjection(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1464 norm_expr2(total_surjection_relation(A,B),total_surjection_relation(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1465 norm_expr2(typeof(A,B),Res) :- norm_expr(A,AA),
1466 (wrap_with_typeof(AA) -> (norm_expr(B,BB), Res = typeof(AA,BB)) ; Res = AA).
1467 norm_expr2(typeset,typeset).
1468
1469 norm_expr2(unary_minus(A),unary_minus(AA)) :- norm_expr(A,AA).
1470 norm_expr2(unary_minus_real(A),unary_minus_real(AA)) :- norm_expr(A,AA).
1471 norm_expr2(union(A,B),Res) :- norm_expr(A,AA), norm_expr(B,BB), (BB @< AA -> Res = union(AA,BB) ; Res= union(BB,AA)).
1472 norm_expr2(value(A),NA) :- norm_value(A,NA).
1473
1474 norm_expr2(freetype_set(T),freetype_set(T)).
1475 norm_expr2(freetype_constructor(FT,Case,A), freetype_constructor(FT,Case,AA)) :- norm_expr(A,AA).
1476 norm_expr2(freetype_destructor(FT,Case,A),freetype_destructor(FT,Case,AA)) :- norm_expr(A,AA).
1477 norm_expr2(recursive_let(A,B),recursive_let(AA,BB)) :- norm_expr(A,AA),norm_expr(B,BB).
1478
1479 % needed if ast_cleanup and replacements were not performed
1480 norm_expr2(event_b_comprehension_set(A,B,C),event_b_comprehension_set(AA,BB,CC)) :- l_norm_expr(A,AA), norm_expr(B,BB), norm_pred(C,CC).
1481 norm_expr2(event_b_first_projection_v2,event_b_first_projection_v2).
1482 norm_expr2(event_b_second_projection_v2,event_b_second_projection_v2).
1483 norm_expr2(quantified_intersection(A,B,C),quantified_intersection(AA,BB,CC)) :- l_norm_expr(A,AA), norm_pred(B,BB), norm_expr(C,CC).
1484 norm_expr2(quantified_union(A,B,C),quantified_union(AA,BB,CC)) :- l_norm_expr(A,AA), norm_pred(B,BB), norm_expr(C,CC).
1485 norm_expr2(ring(A,B),ring(AA,BB)) :- norm_expr(A,AA), norm_expr(B,BB).
1486
1487 wrap_with_typeof(event_b_first_projection_v2).
1488 wrap_with_typeof(event_b_identity).
1489 wrap_with_typeof(event_b_second_projection_v2).
1490
1491 norm_fields([],[]).
1492 norm_fields([field(Name,H)|T],[field(Name,NH)|NT]) :- norm_expr(H,NH), norm_fields(T,NT).
1493
1494 l_norm_expr([],[]).
1495 l_norm_expr([H|T],[NH|NT]) :- norm_expr(H,NH), l_norm_expr(T,NT).
1496
1497 :- use_module(closures,[is_member_closure/5]).
1498 norm_value(V,R) :- var(V),!,R=value(V).
1499 norm_value(int(Nr),R) :- integer(Nr),!,R=Nr.
1500 norm_value(term(F),R) :- nonvar(F),F=floating(Nr),number(Nr),!,R=Nr.
1501 norm_value([],R) :- !, R=empty_set.
1502 norm_value(pred_false,R) :- !, R=boolean_false.
1503 norm_value(pred_true,R) :- !, R=boolean_true.
1504 norm_value(closure(P,T,B),R) :-
1505 (is_member_closure(P,T,B,_,Set) % peel useless member closure wrapper, see test 2483
1506 -> !, norm_expr_check2(Set,R)
1507 ; norm_pred_check(B,NB)
1508 -> !, % normalising relevant for test 1544 with position info added by construct_member_closure
1509 R=value(closure(P,T,NB))
1510 ).
1511 norm_value((A,B),R) :- !, R=(NA,NB), norm_value(A,NA), norm_value(B,NB).
1512 norm_value(rec(Fields),rec(NFields)) :- !, norm_field_values(Fields,NFields).
1513 norm_value(V,value(V)). % we could normalise AVL, or pairs
1514
1515 norm_field_values([],[]).
1516 norm_field_values([field(Name,H)|T],[field(Name,NH)|NT]) :- norm_inner_value(H,NH), norm_field_values(T,NT).
1517
1518 % norm inside values; e.g., getting rid of info fields of closures, see test 2483
1519 norm_inner_value((A,B),R) :- !, R=(NA,NB), norm_inner_value(A,NA), norm_inner_value(B,NB).
1520 norm_inner_value(rec(Fields),rec(NFields)) :- !, norm_field_values(Fields,NFields).
1521 norm_inner_value(closure(P,T,B),R) :- norm_pred_check(B,NB),!,
1522 R=closure(P,T,NB).
1523 % TODO: inside sets ? but AVL sets contain no closures
1524 norm_inner_value(V,V).
1525
1526
1527 arithmetic_op(less(LHS,RHS),'<',LHS,RHS).
1528 arithmetic_op(less_equal(LHS,RHS),'<=',LHS,RHS).
1529 arithmetic_op(greater(LHS,RHS),'<',RHS,LHS).
1530 arithmetic_op(greater_equal(LHS,RHS),'<=',RHS,LHS).
1531
1532 :- use_module(probsrc(kernel_reals),[real_comp_wf/5]).
1533 % these two predicates can be checked by real_comp_wf:
1534 real_arithmetic_op(less_real(LHS,RHS),'<',LHS,RHS).
1535 real_arithmetic_op(less_equal_real(LHS,RHS),'=<',LHS,RHS).
1536
1537 :- use_module(clpfd_interface).
1538 :- use_module(library(clpfd), [(#<=>)/2]).
1539 check_arithmetic_operator('<',X,Y,Res) :- check_less(X,Y,Res),
1540 (nonvar(Res) -> true
1541 ; clpfd_interface:try_post_constraint((X#<Y) #<=> R01), prop_pred_01(Res,R01)).
1542 check_arithmetic_operator('<=',X,Y,Res) :- check_less_than_equal(X,Y,Res),
1543 (nonvar(Res) -> true
1544 ; clpfd_interface:try_post_constraint((X#=<Y) #<=> R01), prop_pred_01(Res,R01)).
1545
1546
1547 :- block prop_pred_01(-,-).
1548 prop_pred_01(A,B) :- B==1,!,A=pred_true. % cut ok: either pred_true or 1 set
1549 prop_pred_01(pred_true,1).
1550 prop_pred_01(pred_false,0).
1551
1552 :- block check_less(-,?,-), check_less(?,-,-).
1553 check_less(X,Y,Res) :- nonvar(Res),!, /* truth value known: enforce it */
1554 (Res=pred_true -> less_than_direct(X,Y) ; less_than_equal_direct(Y,X)).
1555 check_less(X,Y,Res) :-
1556 X < Y,!,/* we could call safe_less_than(X,Y), */
1557 Res=pred_true.
1558 check_less(_,_,pred_false).
1559 :- block check_less_than_equal(-,?,-), check_less_than_equal(?,-,-).
1560 check_less_than_equal(X,Y,Res) :- nonvar(Res),!, /* truth value known: enforce it */
1561 (Res=pred_true -> less_than_equal_direct(X,Y) ; less_than_direct(Y,X)).
1562 check_less_than_equal(X,Y,Res) :- X =< Y,!,Res=pred_true.
1563 check_less_than_equal(_,_,pred_false).
1564
1565
1566
1567 :- use_module(bool_pred).
1568
1569 :- use_module(kernel_objects,[exhaustive_kernel_check_wf/2,
1570 exhaustive_kernel_check/1, exhaustive_kernel_check/2, exhaustive_kernel_fail_check/1]).
1571
1572 :- assert_must_succeed(exhaustive_kernel_check_wf(b_interpreter_check:conjoin(pred_false,pred_false,pred_false,b(truth,pred,[]),b(truth,pred,[]),WF),WF)).
1573 :- assert_must_succeed(exhaustive_kernel_check_wf(b_interpreter_check:conjoin(pred_false,pred_true,pred_false,b(truth,pred,[]),b(truth,pred,[]),WF),WF)).
1574 :- assert_must_succeed(exhaustive_kernel_check_wf(b_interpreter_check:conjoin(pred_true,pred_false,pred_false,b(truth,pred,[]),b(truth,pred,[]),WF),WF)).
1575 :- assert_must_succeed(exhaustive_kernel_check_wf(b_interpreter_check:conjoin(pred_true,pred_true,pred_true,b(truth,pred,[]),b(truth,pred,[]),WF),WF)).
1576 :- assert_must_fail(b_interpreter_check:conjoin(pred_true,pred_false,pred_true,b(truth,pred,[]),b(truth,pred,[]),_WF)).
1577 :- assert_must_fail(b_interpreter_check:conjoin(pred_true,pred_true,pred_false,b(truth,pred,[]),b(truth,pred,[]),_WF)).
1578
1579
1580 % same as and_equality/3 but for pred_false/pred_true rather than eq_obj/pred_false
1581 :- block conjoin(-,-,-,?,?,?).
1582 conjoin(X,Y,Res,LHS,RHS,WF) :- % print(conjoin(X,Y,Res)),nl, translate:print_bexpr(LHS),nl,%
1583 ( Res==pred_true -> X=pred_true,Y=pred_true % on SWI these propagations happen one after the other, see test 2202
1584 ; X==pred_true -> Res=Y
1585 ; X==pred_false -> Res=pred_false
1586 ; Y==pred_true -> Res=X
1587 ; Y==pred_false -> Res=pred_false
1588 ? ; Res==pred_false -> conjoin_false0(X,Y,LHS,RHS,WF)
1589 ; add_error_fail(conjoin,'Illegal values: ', conjoin(X,Y,Res,LHS,RHS,WF))
1590 ).
1591 conjoin_false0(X,Y,_LHS,_RHS,_WF) :- X==Y,!,
1592 %print(conjoin_false_eqeq(X,Y)),nl, translate:print_bexpr(_LHS),nl,
1593 X=pred_false.
1594 conjoin_false0(X,Y,_LHS,_RHS,_WF) :- % X & not(X) -> always false
1595 bool_negate_check(X,Y),!
1596 . %,print(conjoin_false_neqeq(X,Y)),nl,translate:print_bexpr(_LHS),nl.
1597 conjoin_false0(X,Y,LHS,RHS,WF) :-
1598 %%Prio=1, %%
1599 %%(preferences:preference(use_smt_mode,full) -> FullPrio=1.5 ;
1600 get_priority_of_boolean_expression(LHS,Prio),
1601 (preferences:preference(use_clpfd_solver,true) ->
1602 % relevant for tests 349, 362:
1603 count_number_of_conjuncts(RHS,NrC),
1604 FullPrio is Prio+(NrC-1)/10,
1605 get_wait_flag(FullPrio,conjoin,WF,LWF) %%
1606 ; % in non-clpfd mode: much less propagation going on, avoid explosion of choice points
1607 % tests 349, 362 fail with the following for CLPFD: TO DO investigate and use this also in CLPFD mode
1608 get_binary_choice_wait_flag_exp_backoff(Prio,not_conjunct,WF,LWF)
1609 ),
1610 ? conjoin_false(X,Y,LHS,RHS,LWF).
1611 % missing rule: if X==Y -> X=pred_true
1612 :- block conjoin_false(-,-,?,?,-).
1613 conjoin_false(X,Y,LHS,_RHS,_LWF) :-
1614 ( X==pred_true -> pred_false=Y
1615 ; X==pred_false -> true
1616 ; Y==pred_true -> pred_false=X
1617 ; Y==pred_false -> true
1618 ; useless_to_force(LHS) ->
1619 ( % print(forcing_conjoin_rhs_false(X,Y,_LWF)), translate:print_bexpr(_RHS), print(' == FALSE '),nl,
1620 Y=pred_false
1621 ;
1622 (Y,X)=(pred_true,pred_false)
1623 )
1624 ; ( % print(forcing_conjoin_lhs_false(X,Y,_LWF)), translate:print_bexpr(LHS), print(' == FALSE '),nl,
1625 X=pred_false
1626 ; % print(forcing_conjoin_rhs_false(X,Y,_LWF)), translate:print_bexpr(LHS), print(' == TRUE ; '), nl,
1627 (X,Y)=(pred_true,pred_false)
1628 )
1629 ).
1630
1631 % determine when forcing a predicate to true/false does not really help; better choose something else
1632 useless_to_force(b(B,T,I)) :- useless_to_force3(B,T,I).
1633 useless_to_force3(finite(_),_,_). % forcing finite to be false usually not a good idea; we cannot propagate this
1634 % what are other predicates useless to force: some foralls/exists ? some external_pred_call
1635 % in principle a conjunction of useless predicates is also useless: but could be more expensive to check
1636
1637 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:disjoin(pred_false,pred_false,pred_false,_,_,_WF))).
1638 :- assert_must_succeed(exhaustive_kernel_check([commutative],b_interpreter_check:disjoin(pred_false,pred_true,pred_true,_,_,_WF))).
1639 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:disjoin(pred_true,pred_true,pred_true,_,_,_WF))).
1640 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:disjoin(pred_true,pred_true,pred_false,_,_,_WF))).
1641 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:disjoin(pred_true,pred_false,pred_false,_,_,_WF))).
1642 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:disjoin(pred_false,pred_true,pred_false,_,_,_WF))).
1643 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:disjoin(pred_false,pred_false,pred_true,_,_,_WF))).
1644
1645 :- block disjoin(-,-,-,?,?,?).
1646 disjoin(X,Y,Res,LHS,RHS,WF) :-
1647 %print(disjoin(X,Y,Res,WF)),nl, %% translate:print_bexpr(LHS),print(' or '),translate:print_bexpr(RHS),nl,%%
1648 ( Res==pred_false -> X=pred_false,Y=pred_false
1649 ; X==pred_true -> Res=pred_true
1650 ; X==pred_false -> Res=Y
1651 ; Y==pred_true -> Res=pred_true
1652 ; Y==pred_false -> Res=X
1653 ? ; Res==pred_true -> disjoin_true0(X,Y,LHS,RHS,WF)
1654 ; add_error_fail(disjoin,'Illegal values: ',disjoin(X,Y,Res,LHS,RHS,WF))
1655 ).
1656 disjoin_true0(X,Y,_LHS,_RHS,_WF) :- X==Y,!,
1657 X=pred_true.
1658 %disjoin_true0(X,Y,LHS,_,WF) :- !, disjoin_true(X,Y,_).
1659 disjoin_true0(X,Y,_LHS,_RHS,_WF) :- % X or not(X) -> always true
1660 bool_negate_check(X,Y),!.
1661
1662 disjoin_true0(X,Y,LHS,_RHS,WF) :-
1663 %%(preferences:preference(use_smt_mode,full) -> FullPrio=2.5 ;
1664 % poses problem for test 1096:
1665 % count_number_of_disjuncts(RHS,NrC),
1666 %FullPrio is Prio+(NrC-1)/10,
1667 %get_wait_flag(FullPrio,disjoin,WF,LWF), %%
1668 get_priority_of_boolean_expression(LHS,StartPrio),
1669 get_binary_choice_wait_flag_exp_backoff(StartPrio,disjunct,WF,LWF),
1670 % TO DO: extract FD information from LHS and RHS and assert, e.g. x:1..2 or x:4..5
1671 ? disjoin_true(X,Y,LHS,LWF).
1672 % missing rule: if X==Y -> X=pred_true ; if X==~Y -> no need to setup choice point
1673 :- block disjoin_true(-,-,?,-).
1674 disjoin_true(X,Y,LHS,_LWF) :-
1675 ( X==pred_true -> true
1676 ; X==pred_false -> pred_true=Y
1677 ; Y==pred_true -> true
1678 ; Y==pred_false -> pred_true=X
1679 ; useless_to_force(LHS) ->
1680 ( %% print(forcing_disjoin_true(X,Y,_LWF)),nl, %%
1681 Y=pred_true
1682 ;
1683 %%print(forcing_disjoin_false(X,Y,_LWF)),nl,
1684 (Y,X) = (pred_false,pred_true) % these two unifications will happen atomically !
1685 )
1686 ; ( %% print(forcing_disjoin_true(X,Y,_LWF)),nl, %%
1687 X=pred_true
1688 ;
1689 %%print(forcing_disjoin_false(X,Y,_LWF)),nl,
1690 (X,Y) = (pred_false,pred_true) % these two unifications will happen atomically !
1691 )
1692 %add_error_fail(disjoin_true,'Illegal values: ',disjoin_true(X,Y))
1693 ).
1694
1695 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:imply(pred_false,pred_false,pred_true))).
1696 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:imply(pred_false,pred_true,pred_true))).
1697 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:imply(pred_true,pred_false,pred_false))).
1698 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:imply(pred_true,pred_true,pred_true))).
1699 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:imply(pred_false,pred_false,pred_false))).
1700 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:imply(pred_false,pred_true,pred_false))).
1701 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:imply(pred_true,pred_false,pred_true))).
1702 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:imply(pred_true,pred_true,pred_false))).
1703
1704 imply(X,Y,Res) :-
1705 (var(X),var(Y),var(Res) -> bool_equality(X,Y,EqXY) ; true /* impl4 will not block anyway */),
1706 impl4(X,Y,EqXY,Res).
1707 :- block impl4(-,-,-,-).
1708 impl4(X,Y,EqXY,Res) :-
1709 ( Res==pred_false -> X=pred_true,Y=pred_false
1710 ; Res==pred_true -> imply_true3(X,Y,EqXY)
1711 ; X==pred_false -> Res=pred_true
1712 ; X==pred_true -> Res=Y
1713 ; Y==pred_true -> Res=pred_true
1714 ; Y==pred_false -> negate(X,Res)
1715 ; EqXY==pred_true -> Res=pred_true % X => X is always true
1716 ; EqXY==pred_false -> Y=Res % not(Y) => Y is true iff Y is true
1717 ; add_error_fail(impl,'Illegal values: ',imply(X,Y,EqXY,Res))
1718 ).
1719
1720 % assert X=pred_true => Y=pred_true
1721 imply_true(X,Y) :-
1722 (var(X),var(Y) -> bool_equality(X,Y,EqXY) ; true /* imply_true will not block anyway */),
1723 ? imply_true3(X,Y,EqXY).
1724 :- block imply_true3(-,-,-).
1725 imply_true3(X,Y,EqXY) :-
1726 ( X==pred_false -> true
1727 ; X==pred_true -> Y=pred_true
1728 ; Y==pred_true -> true
1729 ; Y==pred_false -> X=pred_false
1730 ; EqXY==pred_true -> true
1731 ; EqXY==pred_false -> X=pred_false % X => not(X) ===> X=pred_false
1732 ; add_error_fail(imply_true,'Illegal values: ',imply_true3(X,Y,EqXY))
1733 ).
1734
1735
1736 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:equiv(pred_false,pred_false,pred_true))).
1737 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:equiv(pred_false,pred_true,pred_false))).
1738 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:equiv(pred_true,pred_false,pred_false))).
1739 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:equiv(pred_true,pred_true,pred_true))).
1740 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:equiv(pred_false,pred_false,pred_false))).
1741 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:equiv(pred_false,pred_true,pred_true))).
1742 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:equiv(pred_true,pred_false,pred_true))).
1743 :- assert_must_succeed(exhaustive_kernel_fail_check(b_interpreter_check:equiv(pred_true,pred_true,pred_false))).
1744
1745 % b_interpreter_check:equiv(X,Y,Res),X=Y, Res==pred_true
1746 equiv(X,Y,Res) :-
1747 bool_equality(X,Y,Res).
1748
1749
1750 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:if_pred(pred_false,pred_false,pred_true,pred_true,priority(1),priority(1),priority(1),no_wf_available))).
1751 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:if_pred(pred_true,pred_false,pred_true,pred_false,priority(1),priority(1),priority(1),no_wf_available))).
1752 :- assert_must_succeed(exhaustive_kernel_check(b_interpreter_check:if_pred(pred_true,pred_false,pred_true,pred_false,priority(1),priority(1),priority(1),no_wf_available))).
1753
1754 /*
1755 Here is the truth-table of the IF-THEN-ELSE predicate generated in the ProB repl:
1756 >>> {test,lhs,rhs,res|(IF test=TRUE THEN lhs=TRUE ELSE rhs=TRUE END)<=> res=TRUE}
1757 Expression Value =
1758 {(FALSE|->FALSE|->FALSE|->FALSE),(FALSE|->FALSE|->TRUE|->TRUE),(FALSE|->TRUE|->FALSE|->FALSE),(FALSE|->TRUE|->TRUE|->TRUE),(TRUE|->FALSE|->FALSE|->FALSE),(TRUE|->FALSE|->TRUE|->FALSE),(TRUE|->TRUE|->FALSE|->TRUE),(TRUE|->TRUE|->TRUE|->TRUE)}
1759 >>> :show
1760 Nr test lhs rhs res
1761 1 FALSE FALSE FALSE FALSE
1762 2 FALSE FALSE TRUE TRUE
1763 3 FALSE TRUE FALSE FALSE
1764 4 FALSE TRUE TRUE TRUE
1765 5 TRUE FALSE FALSE FALSE
1766 6 TRUE FALSE TRUE FALSE
1767 7 TRUE TRUE FALSE TRUE
1768 8 TRUE TRUE TRUE TRUE
1769 */
1770
1771 % propagate reified version of IF-THEN-ELSE predicate
1772 % Note: IF pt THEN qt ELSE rt END <=> ((pt => qt) & (not(pt) => rt))
1773 :- block if_pred(-,-,-,-,?,?,?,?).
1774 if_pred(Test,LHS,RHS,Res,T,L,R,WF) :-
1775 ( Test == pred_true -> LHS=Res
1776 ; Test == pred_false -> RHS=Res
1777 ; LHS == pred_true -> negate(Test,NegTest), imply(NegTest,RHS,Res)
1778 ? ; LHS == pred_false -> negate(Test,NegTest), conjoin(NegTest,RHS,Res,T,R,WF)
1779 ; RHS == pred_true -> imply(Test,LHS,Res)
1780 ; RHS == pred_false -> conjoin(Test,LHS,Res,T,L,WF)
1781 ; Res == pred_true -> imply_true(Test,LHS), negate(Test,NegTest), imply_true(NegTest,RHS)
1782 ; Res == pred_false -> if_pred_false(Test,LHS,RHS)
1783 ; add_internal_error('Illegal call: ',if_pred(Test,LHS,RHS,Res,WF))
1784 ).
1785
1786 % as facts the truth table for if_pred_false would be:
1787 %if_pred_false(pred_true,pred_false,_).
1788 %if_pred_false(pred_false,_,pred_false).
1789 % but we provide a deterministic propagator:
1790 :- block if_pred_false(-,-,-).
1791 if_pred_false(Test,LHS,RHS) :-
1792 ( Test==pred_true -> LHS=pred_false
1793 ; Test==pred_false -> RHS=pred_false
1794 ; LHS == pred_true -> Test = pred_false, RHS = pred_false
1795 ; RHS == pred_true -> Test = pred_true, LHS = pred_false
1796 ; LHS == pred_false -> if_false_lhs(Test,RHS)
1797 ; RHS == pred_false -> if_false_rhs(Test,LHS)
1798 ).
1799
1800 :- block if_false_lhs(-,-).
1801 if_false_lhs(Test,RHS) :- var(Test), RHS==pred_false,!. % Test value does not matter, both lhs/rhs false
1802 if_false_lhs(pred_false,pred_false). % we choose RHS which must be false for the if_predicate to be false
1803 if_false_lhs(pred_true,_). % we choose the lhs which is false, RHS does not matter
1804
1805 :- block if_false_rhs(-,-).
1806 if_false_rhs(Test,LHS) :- var(Test), LHS==pred_false,!. % Test value does not matter, both lhs/rhs false
1807 if_false_rhs(pred_true,pred_false).
1808 if_false_rhs(pred_false,_). % we choose the rhs which is false, LHS does not matter