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(kernel_objects,[basic_type/2,
6 enumerate_basic_type/2, enumerate_basic_type_wf/3, enumerate_basic_type_wf/4,
7 all_objects_of_type/2,
8 max_cardinality/2,
9 enumerate_type/3, % last argument basic or tight
10 enumerate_type_wf/4,
11 enumerate_type/4, % last argument false/true disables/enables enum warning
12 enumerate_basic_type/3,
13 enumerate_tight_type/2, enumerate_tight_type/3, enumerate_tight_type_wf/4,
14 enumerate_int/3,
15 gen_enum_warning_wf/6,
16 all_strings_wf/2, is_string/2, is_not_string/1,
17
18 top_level_dif/2,
19 equal_object_optimized/2, equal_object_optimized/3, equal_object_optimized_wf/4,
20 equal_object/2, equal_object/3, equal_object_wf/3, equal_object_wf/4,
21 not_equal_object/2, not_equal_object_wf/3,
22 equal_cons/3, equal_cons_wf/4, equal_cons_lwf/5,
23 get_next_element/3,
24 is_marked_to_be_computed/1, mark_as_to_be_computed/1,
25
26 %equality_objects/3,
27 membership_test_wf/4,
28
29 %is_a_set/1,
30 empty_set/1, empty_set_wf/2,
31 not_empty_set/1, not_empty_set_wf/2,
32 exact_element_of/2,
33 check_element_of/2, check_element_of_wf/3,
34 not_element_of/2, not_element_of_wf/3,
35
36 add_element/3, add_element/4, add_element_wf/4, add_element_wf/5,
37 add_new_element_wf/4,
38 delete_element_wf/4,
39 %remove_element/3,
40 remove_element_wf/4,remove_element_wf/5,remove_element_wf_if_not_infinite_or_closure/6,
41 remove_exact_first_element/3,
42 check_no_duplicates_in_list/3,
43
44 partition_wf/3, not_partition_wf/3, test_partition_wf/4,
45 %all_different/2,
46 disjoint_sets/3, not_disjoint_sets/3, test_disjoint_wf/4,
47
48 union/3, union_wf/4, union_generalized/2, union_generalized_wf/3,
49 intersection/3, intersection_generalized_wf/4,
50 difference_set/3, difference_set_wf/4,
51 in_difference_set_wf/4, not_in_difference_set_wf/4,
52 in_union_set_wf/4, not_in_union_set_wf/4,
53 in_intersection_set_wf/4, not_in_intersection_set_wf/4,
54
55 strict_subset_of/2, strict_subset_of_wf/3,
56 check_subset_of/2, check_subset_of_wf/3, check_finite_subset_of_wf/3,
57 check_non_empty_subset_of_wf/3, check_finite_non_empty_subset_of_wf/3,
58 not_subset_of/2, not_subset_of_wf/3, not_both_subset_of/5,
59 not_finite_subset_of_wf/3,
60 not_strict_subset_of/2, not_strict_subset_of_wf/3,
61 not_non_empty_subset_of_wf/3, not_non_empty_finite_subset_of_wf/3,
62 both_global_sets/4,check_subset_of_global_sets/2, check_not_subset_of_global_sets/2,
63
64 first_of_pair_wf/3, second_of_pair_wf/3,
65 minimum_of_set_extension_list/4,
66 maximum_of_set_extension_list/4,
67 minimum_of_set/4, maximum_of_set/4,
68 is_finite_set_wf/2, is_infinite_set_wf/2, test_finite_set_wf/3,
69 %finite_cardinality_as_int/3, % now we use kernel_cardinality_attr
70 cardinality_as_int_for_wf/2,
71 cardinality_as_int_wf/3,
72 cardinality_as_int/2, %cardinality_peano_wf/3,
73 card_convert_int_to_peano/2,
74 same_cardinality_wf/3,
75 % card_geq/2,
76 cardinality_greater/5, cardinality_greater_equal/5,
77 cardinality_of_range/3,
78 cardinality_of_set_extension_list/3,
79
80 cartesian_product_wf/4,
81 is_cartesian_pair_wf/4, not_is_cartesian_pair/4,
82
83 power_set/2, non_empty_power_set/2,
84
85 % is_boolean/1, %is_not_boolean/1,
86 is_integer/2, is_not_integer/1,
87 is_natural/2, is_natural1/2,
88 is_implementable_int/2,is_implementable_nat/2, is_implementable_nat1/2,
89 is_not_natural/1, is_not_natural1/1,
90 is_not_implementable_int/1,is_not_implementable_nat/1, is_not_implementable_nat1/1,
91
92 less_than/2, less_than_equal/2,
93 less_than_direct/2, less_than_equal_direct/2,
94 safe_less_than_equal/2, safe_less_than_equal/3,
95
96 greater_than/2, greater_than_equal/2,
97 int_plus/3,
98 division/5, floored_division/5,
99 modulo/5,
100 int_minus/3, unary_minus_wf/3,
101 % nat_range/3, % removed
102 in_nat_range_wf/4, not_in_nat_range/3, not_in_nat_range_wf/4, test_in_nat_range_wf/5,
103 in_nat_range/3, % version without enumeration
104 times/3, square/3,
105 int_power/5,
106 % pred/2, succ/2, removed
107 integer_global_set/1,
108
109 element_of_global_set/2,element_of_global_set_wf/3,not_element_of_global_set/2,
110
111 exhaustive_kernel_check/1, exhaustive_kernel_check_wf/2, exhaustive_kernel_check_wf/3,
112 exhaustive_kernel_check_wfdet/2, exhaustive_kernel_check_wf_upto/3,
113 exhaustive_kernel_succeed_check/1, exhaustive_kernel_fail_check/1,
114 exhaustive_kernel_fail_check_wf/2, exhaustive_kernel_fail_check_wfdet/2,
115 exhaustive_kernel_fail_check_wf_upto/3,
116 exhaustive_kernel_fail_check_wfinit/2,
117 exhaustive_kernel_check/2, exhaustive_kernel_succeed_check/2, exhaustive_kernel_fail_check/2,
118
119 singleton_set_element/4, singleton_set_element_wd/4,
120 infer_value_type/2,
121 check_values_have_same_type/3,
122 contains_any/1
123 ]).
124
125 :- meta_predicate exhaustive_kernel_check_opt(-,0).
126 :- meta_predicate exhaustive_kernel_fail_check_opt(-,0).
127 :- meta_predicate not_strict_eq_check(-,0).
128
129 %:- use_module('../extensions/profiler/profiler.pl').
130 %:- use_module('../extensions/profiler/profiler_te.pl').
131 %:- enable_profiling(enumerate_basic_type/3).
132 %:- enable_profiling(enumerate_type/3).
133 %:- enable_profiling(enumerate_tight_type/2).
134
135 %:- print(loading_kernel_objects),nl.
136
137 %:- multifile user:portray_message/2.
138 %user:portray_message(informational, _).
139 :- use_module(library(terms)).
140 :- use_module(self_check).
141
142 :- use_module(debug).
143 :- use_module(tools_platform, [platform_is_64_bit/0]).
144 :- use_module(tools_printing).
145 :- use_module(tools).
146
147 :- use_module(module_information,[module_info/2]).
148 :- module_info(group,kernel).
149 :- module_info(description,'This module provides operations for the basic datatypes of ProB (equal, not_equal, enumeration).').
150
151 :- use_module(typechecker).
152 :- use_module(error_manager).
153 :- use_module(b_global_sets). %,[global_type/2, b_global_set_cardinality/2, b_empty_global_set/1]).
154 :- use_module(kernel_waitflags).
155 :- use_module(library(lists)).
156 :- use_module(library(avl),[avl_min/2, avl_max/2]).
157 :- use_module(library(clpfd)).
158 :- use_module(fd_utils_clpfd).
159 :- use_module(kernel_freetypes).
160 :- use_module(kernel_card_arithmetic).
161 :- use_module(custom_explicit_sets).
162 :- use_module(typechecker).
163 %:- use_module(clpfd_off_interface). %
164 % on a 32 bit system: use clpfd_off_interface; on 64 bit system clpfd_interface should be ok (integer overflows)
165 :- use_module(clpfd_interface). %
166 :- use_module(bsyntaxtree, [get_texpr_id/2, get_texpr_pos/2]).
167
168 :- type atomic_type +--> (term(integer,[]) ; term(string,[]) ; term(real,[]) ; constant(list(atomic)) ; abort ; boolean ; global(atomic)).
169 :- type atomic_any_type +--> (type(atomic_type) ; term(any,[]) ).
170 :- type basic_type_descriptor +--> (type(atomic_any_type) ; set(basic_type_descriptor) ;
171 seq(basic_type_descriptor) ;
172 couple(basic_type_descriptor,basic_type_descriptor) ;
173 record(list(type(field_type))) ;
174 freetype(atomic)).
175
176 :- type inferred_basic_type_descriptor +--> (var ; type(atomic_type) ; set(inferred_basic_type_descriptor) ;
177 seq(inferred_basic_type_descriptor) ;
178 couple(inferred_basic_type_descriptor,inferred_basic_type_descriptor)).
179
180 :- type fd_index +--> (integer ; var).
181 :- type fd_set +--> (atomic ; var).
182 :- type fd_term +--> fd(fd_index,fd_set).
183 :- type bsets_integer +--> int((integer ; var)).
184 :- type bsets_string +--> string((atomic ; var)).
185 :- type bsets_bool +--> (pred_false /* bool_false */ ; pred_true /* bool_true */).
186 :- type field_type +--> field(atomic,basic_type_descriptor).
187
188 %:- type bsets_sequence +--> (nil_seq ; cons(type(bsets_object),type(bsets_sequence))).
189 %:- type bsets_set +--> vlist(type(bsets_object)).
190 :- functor([_|_],ListFunctor,_),
191 (type bsets_set +--> (term([],[]) ; var ; term(ListFunctor,[type(bsets_object),type(bsets_set)]) ;
192 avl_set( ground ) ;
193 closure(list(type(variable_id)),
194 list(type(basic_type_descriptor)),type(boolean_expression))
195 ; closure_x(list(type(variable_id)),
196 list(type(basic_type_descriptor)),type(boolean_expression),any))).
197 :- type bsets_couple +--> term(',',[type(bsets_object),type(bsets_object)]).
198 :- type bsets_global +--> global_set((atomic ; var)).
199 :- type bsets_field +--> field(atomic,type(bsets_object)).
200 :- type bsets_record +--> rec((var ; list(bsets_field))).
201 :- type bsets_freetype +--> freeval(atomic,(atomic ; var),type(bsets_object)).
202
203 :- type bsets_object +--> (fd_term ; bsets_integer ; bsets_bool ; term(term,[any]) ; bsets_set ;
204 % abort(any) ; % deprecated
205 bsets_couple ; bsets_string ; bsets_global ; var;
206 bsets_record ; bsets_freetype).
207
208
209 :- assert_must_succeed(kernel_waitflags:set_silent(true)). % disable waitflag store not init msgs
210
211
212
213
214 % a predicate to exhaustively check a kernel predicate with all possible modes
215
216 :- use_module(tools_timeout,[time_out_call/1]).
217 exhaustive_kernel_check_opt(C,Cond) :- (Cond -> exhaustive_kernel_check(C) ; true).
218 exhaustive_kernel_check(C) :- exhaustive_kernel_check4([],C,true,true).
219 exhaustive_kernel_check(Opts,C) :- exhaustive_kernel_check4(Opts,C,true,true).
220 exhaustive_kernel_check_wf(C,WF) :- exhaustive_kernel_check_wf([],C,WF).
221 exhaustive_kernel_check_wf(Opts,C,WF) :-
222 exhaustive_kernel_check4(Opts,C,kernel_waitflags:init_wait_flags(WF),
223 kernel_waitflags:ground_wait_flags(WF)).
224 exhaustive_kernel_check_wfdet(C,WF) :-
225 exhaustive_kernel_check4([],C,kernel_waitflags:init_wait_flags(WF),
226 kernel_waitflags:ground_det_wait_flag(WF)).
227 exhaustive_kernel_check_wf_upto(C,WF,Limit) :-
228 exhaustive_kernel_check4([],C,kernel_waitflags:init_wait_flags(WF),
229 (kernel_waitflags:ground_wait_flag_to(WF,Limit),
230 kernel_waitflags:portray_waitflags(WF))).
231
232 ?exhaustive_kernel_check4(Opts,Call,Pre,Post) :- enumerate_kernel_call(Call,Opts,ECall,Code),
233 debug_println(9,exhaustive_kernel_check(ECall,Code)),
234 flatten_call((Pre,ECall,Code,Post),FullCall),
235 must_succeed_without_residue_and_time_out(FullCall), debug_println(9,ok),
236 fail.
237 exhaustive_kernel_check4(_,_,_,_).
238
239 flatten_call((A,B),Res) :- !,flatten_call(A,FA), flatten_call(B,FB), conjoin_call(FA,FB,Res).
240 flatten_call(Module:Call,Res) :- !, flatten_call(Call,F), Res=Module:F.
241 flatten_call(X,X).
242
243 conjoin_call(true,X,R) :- !,R=X.
244 conjoin_call(X,true,R) :- !, R=X.
245 conjoin_call(X,Y,(X,Y)).
246
247 exhaustive_kernel_succeed_check(C) :- exhaustive_kernel_succeed_check([],C).
248 ?exhaustive_kernel_succeed_check(Opts,Call) :- enumerate_kernel_call(Call,Opts,ECall,Code),
249 debug_println(9,exhaustive_kernel_succeed_check(ECall,Code)),
250 flatten_call((ECall,Code),FullCall),
251 time_out_call(must_succeed(FullCall)),debug_println(9,ok),
252 fail.
253 exhaustive_kernel_succeed_check(_,_).
254
255 exhaustive_kernel_fail_check_opt(C,Cond) :- (Cond -> exhaustive_kernel_fail_check(C) ; true).
256 exhaustive_kernel_fail_check(C) :- exhaustive_kernel_fail_check4([],C,true,true).
257 exhaustive_kernel_fail_check(Opts,C) :- exhaustive_kernel_fail_check4(Opts,C,true,true).
258 exhaustive_kernel_fail_check_wf(C,WF) :-
259 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF),
260 kernel_waitflags:ground_wait_flags(WF)).
261 exhaustive_kernel_fail_check_wfdet(C,WF) :-
262 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF),
263 kernel_waitflags:ground_det_wait_flag(WF)).
264 exhaustive_kernel_fail_check_wf_upto(C,WF,Limit) :-
265 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF),
266 kernel_waitflags:ground_wait_flag_to(WF,Limit)).
267 exhaustive_kernel_fail_check_wfinit(C,WF) :-
268 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF), true).
269
270 ?exhaustive_kernel_fail_check4(Opts,Call,Pre,Post) :- enumerate_kernel_call(Call,Opts,ECall,Code),
271 debug_println(9,exhaustive_kernel_fail_check(ECall,Code)),
272 flatten_call((Pre,ECall,Code,Post),FullCall),
273 time_out_call(must_fail(FullCall)),debug_println(9,ok),
274 fail.
275 exhaustive_kernel_fail_check4(_,_,_,_).
276
277 % enumerate_kernel_call(Call, OptionList, NewCall, CodeAfter)
278 enumerate_kernel_call((A,B),Opts,(EA,EB),(CA,CB)) :- !,
279 ? enumerate_kernel_call(A,Opts,EA,CA), enumerate_kernel_call(B,Opts,EB,CB).
280 ?enumerate_kernel_call(Module:Call,Opts,Module:ECall,Code) :- !, enumerate_kernel_call(Call,Opts,ECall,Code).
281 enumerate_kernel_call(Call,Opts,ECall,Code) :- Call=..[KernelPred|CArgs],
282 (member(commutative,Opts)
283 -> (Args=CArgs ; CArgs=[A1,A2|T], Args=[A2,A1|T])
284 ; Args=CArgs
285 ),
286 ? l_enumerate_kernel_args(Args,EArgs,Code,KernelPred,1), ECall=..[KernelPred|EArgs].
287 l_enumerate_kernel_args([],[],true,_,_).
288 l_enumerate_kernel_args([H|T],[EH|ET],Code,KernelPred,Nr) :-
289 ? enumerate_kernel_args(H,EH,C1,KernelPred/Nr),
290 N1 is Nr+1,
291 ? l_enumerate_kernel_args(T,ET,C2,KernelPred,N1),
292 ? permute_code((C1,C2),Code).
293
294 permute_code((true,C),R) :- !,R=C.
295 permute_code((C,true),R) :- !, R=C.
296 permute_code((C1,C2),(C1,C2)).
297 permute_code((C1,C2),(C2,C1)).
298
299 enumerate_kernel_args(Var,Res,Code,_) :- var(Var),!, Res=Var, Code=true.
300 ?enumerate_kernel_args(X,Res,Code,KP_Nr) :- do_not_delay(X,KP_Nr),!, Res=X, Code=true.
301 enumerate_kernel_args(Arg,Arg,true,_). % just keep the argument
302 enumerate_kernel_args(Args,NewArg,Code,KP_Nr) :- arg_is_list(KP_Nr),!,
303 % we have a list of B expressions (e.g., in partition_wf)
304 ? (Code = '='(NewArg,Args) ; l_enumerate_kernel_args(Args,NewArg,Code,arg_is_list,1)).
305 enumerate_kernel_args(Arg,NewArg,Code,_) :- % delay the argument fully
306 (term_is_of_type(Arg,bsets_object,no)
307 -> Code = equal_object(NewArg,Arg,enumerate_kernel_args)
308 ; Code = '='(NewArg,Arg)).
309 enumerate_kernel_args(int(X),int(XX),Code,_) :- nonvar(X), Code = '='(X,XX). % delay setting number content
310 enumerate_kernel_args(string(X),string(XX),Code,_) :- nonvar(X), Code = '='(X,XX). % delay setting string content
311 enumerate_kernel_args(term(floating(X)),term(floating(XX)),Code,_) :- nonvar(X), Code = '='(X,XX). % delay setting real number content
312 enumerate_kernel_args(term(floating(X)),term(F),Code,_) :- Code = '='(F,floating(X)). % delay setting floating constructor
313 enumerate_kernel_args((A,B),(AA,BB),(CodeA,CodeB),KP_Nr) :-
314 ? enumerate_kernel_args(A,AA,CodeA,KP_Nr),enumerate_kernel_args(B,BB,CodeB,KP_Nr),
315 (AA,BB) \== (A,B). % avoid re-generating case 3 above (just keep argument)
316 enumerate_kernel_args(freeval(ID,Case,A),freeval(ID,Case,AA),CodeA,KP_Nr) :-
317 ? enumerate_kernel_args(A,AA,CodeA,KP_Nr),
318 AA \== A. % avoid re-generating case 3 above (just keep argument)
319 enumerate_kernel_args([H|T],[H|NewT],Code,_) :- Code = equal_object(NewT,T). % delay tail
320 enumerate_kernel_args([H|T],[(int(NewI),H2)|T],Code,_) :- nonvar(H), % make index (e.g. of sequence) nonvar first
321 ? H = (II,H2), ground(II), II=int(I), \+ member((int(I),_),T), % the element is unique in domain
322 Code = '='(NewI,I).
323 enumerate_kernel_args([H|T],[(H1,NewH2)|T],Code,_) :- nonvar(H),
324 ? H = (H1,H2), ground(H2), \+ member((_,H2),T), % the element is unique in ragne
325 Code = equal_object(NewH2,H2).
326 enumerate_kernel_args([H|T],Res,Code,KP_Nr) :-
327 try_expand_and_convert_to_avl([H|T],AVL),
328 ? AVL \= [H|T], enumerate_kernel_args(AVL,Res,Code,KP_Nr).
329 enumerate_kernel_args([H|T],Res,Code,KP_Nr) :- ground([H|T]),generate_member_closure([H|T],Closure),
330 ? enumerate_kernel_args(Closure,Res,Code,KP_Nr).
331
332 % check if an argument is a list not a set.
333 arg_is_list(KernelPred/Nr) :- argument_is_list_not_set(KernelPred,Nr).
334 %arg_is_not_list(KernelPred/Nr) :- \+ argument_is_list_not_set(KernelPred,Nr).
335 argument_is_list_not_set(partition_wf,2).
336 argument_is_list_not_set(not_partition_wf,2).
337 argument_is_list_not_set(test_partition_wf,2).
338 argument_is_list_not_set(disjoint_union_generalized_wf,1).
339
340 do_not_delay(b(_,_,_),_). % do not delay instantiation B predicates and expressions
341 ?do_not_delay(global_set(G),KP/ArgNr) :- custom_explicit_sets:is_infinite_global_set(G,_),
342 ? do_not_delay_arg(KP,ArgNr).
343 do_not_delay(no_wf_available,_). % do not delay waitflag store arguments
344 do_not_delay(priority(_),_).
345 do_not_delay(already_reified(_),_).
346 do_not_delay(wfx(_,_,_,_),_). % ditto
347 % these arguments cause difficulty if infinite sets are delayed (i.e., instantiated later)
348 do_not_delay_arg(partial_function_wf,2).
349 do_not_delay_arg(partial_function_wf,3).
350 do_not_delay_arg(subset_test,2).
351 do_not_delay_arg(subset_strict_test,2).
352
353 generate_member_closure(ExplicitSet,closure(['_zzzz_unit_tests'],[Type],Pred)) :-
354 infer_type(ExplicitSet,set(Type)),
355 Pred =
356 b(member(b(identifier('_zzzz_unit_tests'),Type,[generated]),
357 b(value(ExplicitSet),set(Type),[])),pred,[]).
358
359 infer_type(Value,Type) :- (infer_value_type(Value,Type)
360 -> true %,print(inferred(Type,Value)),nl
361 ; print('### Could not infer type: '), print(Value),nl,fail).
362
363 :- use_module(btypechecker,[couplise_list/2]).
364 infer_value_type(Var,Type) :- var(Var),!,Type=any.
365 infer_value_type([],set(any)).
366 infer_value_type([H|T],set(ResType)) :- infer_value_type(H,Type),
367 ((contains_any(Type),T=[H2|_], % try H2; maybe we can infer a better type here
368 infer_value_type(H2,Type2), \+ contains_any(Type2))
369 -> ResType = Type2
370 ; ResType = Type).
371 infer_value_type(avl_set(node(H,_True,_,_,_)),set(Type)) :- infer_value_type(H,Type).
372 infer_value_type(int(_),integer).
373 infer_value_type(string(_),string).
374 infer_value_type((A,B),couple(TA,TB)) :- infer_value_type(A,TA), infer_value_type(B,TB).
375 infer_value_type(fd(_,T),global(T)).
376 infer_value_type(pred_true /* bool_true */,boolean).
377 infer_value_type(pred_false /* bool_false */,boolean).
378 infer_value_type(rec(Fields),record(FieldTypes)) :- infer_field_types(Fields,FieldTypes).
379 infer_value_type(freeval(Id,_Case,_Val),freetype(Id)).
380 infer_value_type(closure(_,Types,_),set(Res)) :- couplise_list(Types,Res).
381 infer_value_type(global_set('STRING'),R) :- !, R=set(string). % what if Event-B/TLA have a deferred set of that name
382 infer_value_type(global_set('FLOAT'),R) :- !, R=set(real).
383 infer_value_type(global_set('REAL'),R) :- !, R=set(real).
384 infer_value_type(global_set(X),R) :- b_integer_set(X),!,R=set(integer).
385 ?infer_value_type(global_set(Name),set(global(Name))) :- b_global_set(Name).
386 infer_value_type(term(floating(_)),real). % see kernel_reals:is_real(.)
387
388 infer_field_types([],[]).
389 infer_field_types([field(Name1,Val)|T],[field(Name1,VT)|TT]) :-
390 infer_value_type(Val,VT),
391 infer_field_types(T,TT).
392
393 contains_any(any).
394 contains_any(couple(A,B)) :- (contains_any(A) -> true ; contains_any(B)).
395 contains_any(set(A)) :- contains_any(A).
396 % to do: fields
397
398 :- assert_pre(kernel_objects:basic_type(Obj,Type), (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
399 :- assert_post(kernel_objects:basic_type(Obj,_), type_check(Obj,bsets_object)).
400
401 %:- block basic_type(-,-).
402
403 basic_type(FD,global(T)) :- !, global_type(FD,T). % will set up CLP(FD) domain for X
404 % TO DO: Also: what about global(T) inside other structures (pairs) ?
405 basic_type(Rec,record(FieldTypes)) :- !, Rec=rec(Fields),
406 ? basic_field_types(Fields,FieldTypes).
407 %basic_type(Set,set(Type)) :- !, basic_type_set(Type,Set,inf).
408 basic_type(_X,_TY). %basic_type2(TY,X) %basic_symbreak(TY,X)
409 %print(ignore_basic_type(X,Y)),nl %, basic_type2(TY,X) %%STILL REQUIRED ?????
410
411 basic_field_types([],[]).
412 basic_field_types([field(Name1,Val)|T],[field(Name2,VT)|TT]) :-
413 check_field_name_compatibility(Name1,Name2,basic_field_types2),
414 ? basic_type(Val,VT),basic_field_types(T,TT).
415
416
417
418 /* ------------------------- */
419 /* enumerate_basic_type/2 */
420 /* ------------------------- */
421 /* a version of basic_type that enumerates */
422
423 :- assert_must_succeed(enumerate_basic_type([],set(couple(integer,integer)) )).
424 :- assert_must_succeed(enumerate_basic_type([([],int(2)), ([int(3)],int(4))],
425 set(couple(set(integer),integer)) )).
426 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
427 set(couple(integer,integer)) )).
428 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
429 seq(integer) )).
430 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
431 seq(integer) )).
432 :- assert_must_succeed((enumerate_basic_type(X,global('Name')),
433 equal_object(X,fd(1,'Name')) )).
434 :- assert_must_succeed((enumerate_basic_type(X,global('Name')),
435 equal_object(X,fd(2,'Name')) )).
436 :- assert_must_succeed((enumerate_basic_type(X,global('Name')),
437 X==fd(2,'Name')) ).
438 :- assert_must_succeed((enumerate_basic_type(X,record([field(a,global('Name'))])),
439 equal_object(X,rec([field(a,fd(1,'Name'))])) )).
440 :- assert_must_succeed((enumerate_basic_type(X,record([field(a,integer),field(b,global('Name'))])),
441 equal_object(X,rec([field(a,int(1)),field(b,fd(1,'Name'))])) )).
442 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc1,[case(a,constant([a])),case(b,integer)]),
443 kernel_freetypes:set_freetype_depth(2),
444 enumerate_basic_type(X,freetype(selfc1)),equal_object(X,freeval(selfc1,a,term(a))),
445 kernel_freetypes:reset_freetypes)).
446 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc5,[case(a,constant([a])),case(b,integer)]),
447 kernel_freetypes:set_freetype_depth(2),
448 enumerate_basic_type(X,freetype(selfc5)),equal_object(X,freeval(selfc5,b,int(1))),
449 kernel_freetypes:reset_freetypes)).
450 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc7,[case(nil,constant([nil])),case(node,couple(freetype(selfc7),freetype(selfc7)))]),
451 kernel_freetypes:set_freetype_depth(3),
452 findall(X,enumerate_basic_type(X,freetype(selfc7)),Solutions),
453 length(Solutions,5),
454 kernel_freetypes:reset_freetypes)).
455 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc2,[case(a,constant([a])),case(b,freetype(selfc3))]),
456 kernel_freetypes:add_freetype(selfc3,[case(c,constant([c])),case(d,freetype(selfc2))]),
457 kernel_freetypes:set_freetype_depth(4),
458 enumerate_basic_type(X,freetype(selfc2)),
459 equal_object(X,freeval(selfc2,b,freeval(selfc3,d,freeval(selfc2,b,freeval(selfc3,c,term(c)))))),
460 kernel_freetypes:reset_freetypes)).
461 :- assert_must_succeed((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
462 equal_object(X,[(fd(1,'Name'),fd(1,'Code'))])) ).
463 :- assert_must_succeed((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
464 equal_object(X,[(fd(2,'Name'),fd(1,'Code')), (fd(1,'Name'),fd(2,'Code'))])) ).
465 :- assert_must_succeed((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
466 equal_object(X,[(fd(1,'Name'),fd(2,'Code')), (fd(2,'Name'),fd(1,'Code'))])) ).
467 :- assert_must_succeed_any((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
468 equal_object(X,[(fd(1,'Name'),fd(2,'Code')), (fd(2,'Name'),fd(1,'Code'))])) ).
469 :- assert_must_succeed(enumerate_basic_type([(int(2),(int(1),int(2))),
470 (int(1),(int(3),int(4)))],
471 set(couple(integer,couple(integer,integer))) )).
472 :- assert_must_succeed(enumerate_basic_type([(int(2),(int(1),int(2))),
473 (int(55),(int(3),int(4)))],
474 set(couple(integer,couple(integer,integer))) )).
475 :- assert_must_succeed(enumerate_basic_type([term('err')],set(constant([err])))).
476 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
477 set(couple(integer,integer)))).
478
479 :- assert_must_succeed_multiple(enumerate_basic_type([(int(2),fd(_A,'Name')),(int(3),fd(_B,'Name')),
480 (int(4),fd(_C,'Name')),(int(5),fd(_D,'Name')),(int(6),fd(_E,'Name')),(int(7),fd(_F,'Name')),
481 (int(8),fd(_G,'Name')),(int(9),fd(_H,'Name')),(int(10),fd(_I,'Name')),
482 (int(11),fd(_,'Name')),(int(12),fd(_,'Name')),(int(13),fd(_,'Name')),
483 (int(14),fd(_,'Name'))],set(couple(integer,global('Name'))))).
484
485 :- assert_must_fail(( findall(XX,enumerate_basic_type(XX, set(set(global('Code')))) ,S), member(X,S), remove(S,X,R), member(X2,R), equal_object(X,X2) )).
486
487 :- assert_must_succeed(( enumerate_basic_type(global_set('Code'),
488 set(global('Code'))) )).
489
490 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([(fd(1,'Name'),fd(2,'Code')), (fd(2,'Name'),fd(1,'Code'))],set(couple(global('Name'),global('Code')))))).
491 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([(fd(1,'Name'),pred_true), (fd(2,'Name'),pred_false), (fd(2,'Name'),pred_true)],set(couple(global('Name'),boolean))))).
492 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([pred_true,pred_false],set(boolean)))).
493 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([[],[pred_true,pred_false]],set(set(boolean))))).
494
495 :- assert_pre(kernel_objects:enumerate_basic_type(Obj,Type),
496 (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
497 :- assert_post(kernel_objects:enumerate_basic_type(Obj,_), (type_check(Obj,bsets_object),ground_check(Obj))).
498
499 enumerate_basic_type_wf(Obj,Type,WF) :-
500 enumerate_basic_type_wf(Obj,Type,enumerate_basic_type,WF).
501 :- block enumerate_basic_type_wf(?,-,?,?).
502 enumerate_basic_type_wf(Obj,Type,EnumWarning,WF) :-
503 enumerate_basic_type4(Type,Obj,basic,trigger_true(EnumWarning),WF). % add WF context info
504
505 :- block enumerate_basic_type(?,-).
506 enumerate_basic_type(Obj,Type) :-
507 %enumerate_basic_type2(Obj,Type).
508 ? enumerate_basic_type4(Type,Obj,basic,trigger_true(enumerate_basic_type),no_wf_available).
509 %(ground(Obj) -> true ; enumerate_basic_type3(Type,Obj,basic)).
510
511 :- block enumerate_basic_type(?,-,-).
512 enumerate_basic_type(Obj,Type,EnumWarning) :-
513 enumerate_basic_type4(Type,Obj,basic,EnumWarning,no_wf_available).
514
515
516 :- block enumerate_type(?,-,?). % last argument: basic or tight
517 enumerate_type(Obj,Type,Tight) :-
518 %enumerate_basic_type2(Obj,Type).
519 ? enumerate_basic_type4(Type,Obj,Tight,trigger_true(enumerate_type_3),no_wf_available).
520
521 :- block enumerate_type(?,-,?,?), enumerate_type(?,?,?,-).
522 enumerate_type(Obj,Type,Tight,EnumWarning) :-
523 enumerate_basic_type4(Type,Obj,Tight,EnumWarning,no_wf_available).
524
525 enumerate_type_wf(Obj,Type,Tight,WF) :-
526 ? enumerate_type_wf(Obj,Type,Tight,trigger_true(enumerate_type_wf),WF).
527
528 :- block enumerate_type_wf(?,-,?,?,?), enumerate_type_wf(?,?,?,-,?).
529 enumerate_type_wf(Obj,Type,Tight,EnumWarning,WF) :-
530 ? enumerate_basic_type4(Type,Obj,Tight,EnumWarning,WF).
531
532 %enumerate_basic_type2(X,Type) :-
533 % (ground(X) -> (basic_type(X,Type) -> true
534 % ; add_internal_error('Type error: ',enumerate_basic_type2(X,Type)))
535 % ; enumerate_basic_type3(Type,X)).
536
537
538 :- use_module(kernel_reals,[enumerate_real_wf/3]).
539
540 enumerate_basic_type4(global(T),R,_Tight,EnumWarning,WF) :-
541 ? enumerate_global_type_with_enum_warning(R,T,EnumWarning,WF).
542 enumerate_basic_type4(set(X),Set,Tight,EnumWarning,WF) :-
543 ? enumerate_basic_type_set(Set,X,Tight,EnumWarning,WF).
544 enumerate_basic_type4(seq(SeqRanType),Seq,Tight,EnumWarning,WF) :-
545 ? (Tight = tight -> enumerate_seq_type_wf(Seq,SeqRanType,EnumWarning,WF) % might trigger warning. push flag.
546 ? ; enumerate_basic_type4(set(couple(integer,SeqRanType)),Seq,basic,EnumWarning,WF)).
547 enumerate_basic_type4(couple(XT,YT),(X,Y),Tight,EnumWarning,WF) :-
548 ? enumerate_type_wf(X,XT,Tight,EnumWarning,WF),
549 ? enumerate_type_wf(Y,YT,Tight,EnumWarning,WF).
550 ?enumerate_basic_type4(boolean,B,_Tight,_EnumWarning,_WF) :- enumerate_bool(B).
551 enumerate_basic_type4(real,R,_Tight,EnumWarning,WF) :- enumerate_real_wf(R,EnumWarning,WF).
552 enumerate_basic_type4(string,string(S),_Tight,EnumWarning,WF) :- enumerate_string_wf(S,EnumWarning,WF).
553 enumerate_basic_type4(constant([V]),term(V),_Tight,_EnumWarning,_WF).
554 enumerate_basic_type4(record(FT),rec(F),Tight,EnumWarning,WF) :-
555 ? enumerate_basic_field_types(F,FT,Tight,EnumWarning,WF).
556 enumerate_basic_type4(freetype(Id),freeval(Id2,C,Value),Tight,EnumWarning,WF) :-
557 (Id=Id2 -> true
558 ; add_internal_error('Freetypes do not match:',enumerate_basic_type4(freetype(Id),freeval(Id2,C,Value),Tight,_,_))),
559 (ground_value(freeval(Id2,C,Value)) -> true
560 ; (is_recursive_freetype(Id),
561 max_freetype_enum_depth(Depth)
562 -> gen_enum_warning_wf(Id,0:inf,0:Depth,EnumWarning,unknown,WF)
563 ; true),
564 ? enumerate_freetype_wf(Tight,freeval(Id,C,Value),freetype(Id),WF)
565 ).
566 enumerate_basic_type4(freetype_lim_depth(Id,Depth),freeval(Id2,C,Value),Tight,_EnumWarning,WF) :-
567 (Id=Id2 -> true
568 ; add_internal_error('Freetypes do not match:',enumerate_basic_type4(freetype_lim_depth(Id,Depth),freeval(Id2,C,Value),Tight,_,_))),
569 % freetype_lim_depth is created artificially by enumerate_freetype
570 ? enumerate_freetype_wf(Tight,freeval(Id,C,Value),freetype_lim_depth(Id,Depth),WF).
571 enumerate_basic_type4(integer,int(N),Tight,EnumWarning,WF) :-
572 (nonvar(N)
573 -> (integer(N) -> true
574 ; add_internal_error('Illegal value:',enumerate_basic_type4(integer,int(N),Tight,EnumWarning,WF))
575 )
576 ? ; enumerate_int_with_span(N,EnumWarning,unknown,WF)).
577 enumerate_basic_type4(abort,V,Tight,EnumWarning,WF) :-
578 add_internal_error(deprecated_abort_type,enumerate_basic_type4(abort,V,Tight,EnumWarning,WF)).
579 enumerate_basic_type4(constant,V,Tight,EnumWarning,WF) :-
580 add_internal_error(deprecated_abort_type,enumerate_basic_type4(constant,V,Tight,EnumWarning,WF)).
581 enumerate_basic_type4(any,Obj,_Tight,EnumWarning,WF) :- enumerate_any_wf(Obj,EnumWarning,WF).
582
583 :- use_module(library(random),[random/3]).
584 enumerate_bool(X) :- preferences:preference(randomise_enumeration_order,true),
585 random(1,3,1),!,
586 (X=pred_false ; X=pred_true).
587 enumerate_bool(pred_true). /* was bool_true */
588 enumerate_bool(pred_false).
589
590 max_cardinality_string(inf). % was 2
591 all_strings_wf(AS,WF) :- findall(string(S),enumerate_string_wf(S,trigger_throw(all_strings),WF),AS).
592 :- use_module(btypechecker,[machine_string/1]).
593 enumerate_string_wf(S,_EnumWarning,_WF) :- atomic(S),!.
594 enumerate_string_wf(S,EnumWarning,WF) :- %print('### WARNING, Enumerating STRING'),nl,
595 % frozen(S,Goal), print(enum(S,Goal)),nl,
596 % MAYBE TO DO: we could check if prolog:dif(S,'"STR1"') are in frozen Goal and then enumerate more?
597 % if we do this we need to adapt dont_expand(global('STRING')) :- ... further below
598 gen_enum_warning_wf('STRING',inf,'"STRING1","STRING2",...',EnumWarning,unknown,WF),
599 (S = 'STRING1', \+ machine_string(S) % used to be '"STR1"'
600 ; S = 'STRING2', \+ machine_string(S) % used to be '"STR2"'
601 ; machine_string(S)).
602
603 is_string(string(_),_WF).
604 is_not_string(X) :- top_level_dif(X,string).
605
606
607
608 :- block enumerate_any_wf(-,?,?).
609 enumerate_any_wf(fd(X,T),EnumWarning,WF) :- !,
610 when(nonvar(T),enumerate_global_type_with_enum_warning(fd(X,T),T,EnumWarning,WF)).
611 enumerate_any_wf(int(N),EnumWarning,WF) :- !,enumerate_basic_type4(integer,int(N),basic,EnumWarning,WF).
612 enumerate_any_wf(term(X),EnumWarning,WF) :- !,
613 (nonvar(X), X = floating(R) -> enumerate_real_wf(R,EnumWarning,WF)
614 ; print_message(could_not_enumerate_term(X))).
615 enumerate_any_wf(string(S),EnumWarning,WF) :- !, enumerate_string_wf(S,EnumWarning,WF).
616 enumerate_any_wf(pred_true /* bool_true */,_EnumWarning,_WF) :- !.
617 enumerate_any_wf(pred_false /* bool_false */,_EnumWarning,_WF) :- !.
618 enumerate_any_wf([],_EnumWarning,_WF) :- !.
619 enumerate_any_wf([H|T],EnumWarning,WF) :- !, enumerate_any_wf(H,EnumWarning,WF), enumerate_any_wf(T,EnumWarning,WF).
620 enumerate_any_wf(avl_set(_),_EnumWarning,_WF) :- !.
621 enumerate_any_wf(global_set(_),_EnumWarning,_WF) :- !.
622 enumerate_any_wf((H,T),EnumWarning,WF) :- !, enumerate_any_wf(H,EnumWarning,WF), enumerate_any_wf(T,EnumWarning,WF).
623 enumerate_any_wf(rec(Fields),EnumWarning,WF) :- !, enumerate_any_wf(Fields,EnumWarning,WF).
624 enumerate_any_wf(field(_,V),EnumWarning,WF) :- !, enumerate_any_wf(V,EnumWarning,WF).
625 % we could support: closure values...
626 enumerate_any_wf(T,_EnumWarning,_WF) :- add_message(enumerate_any_wf,'Could_not_enumerate value: ',T).
627
628
629 :- use_module(preferences,[preference/2]).
630
631 % enumerate an INTEGER variable
632 enumerate_int_with_span(N,EnumWarning,Span,WF) :-
633 clpfd_domain(N,FDLow,FDUp), % print(enum(N,FDLow,FDUp)),nl,
634 (finite_domain(FDLow,FDUp)
635 ? -> label(N,FDLow,FDUp)
636 ? ; enum_unbounded(FDLow,FDUp,N,EnumWarning,Span,WF)
637 ).
638 label(N,FDLow,FDUp) :-
639 gen_enum_warning_if_large(N,FDLow,FDUp),
640 ? clpfd_interface:clpfd_in_domain(N).
641
642 % when in CLP(FD) mode; try and do a case-split and see if that narrows down the possible ranges
643 enum_unbounded(X,Y,N,EnumWarning,Span,WF) :- preferences:preference(use_clpfd_solver,true),!,
644 ? enum_unbounded_clp(X,Y,N,EnumWarning,Span,WF).
645 enum_unbounded(X,Y,N,EnumWarning,Span,WF) :- %frozen(N,G), print(frozen(N,G,X,Y,EnumWarning)),nl,
646 clpfd_off_domain(N,X,Y,NX,NY),
647 (finite_domain(NX,NY) -> enumerate_int1(N,NX,NY)
648 ? ; enum_unbounded_clpfd_off(NX,NY,N,EnumWarning,Span,WF)).
649
650 enum_unbounded_clpfd_off(_FDLow,_FDUp,N,_EnumWarning,_,_WF) :- is_wd_guarded_result_variable(N),!.
651 enum_unbounded_clpfd_off(FDLow,FDUp,N,EnumWarning,Span,WF) :-
652 make_domain_finite(FDLow,FDUp,Min,Max),
653 gen_enum_warning_wf('INTEGER',FDLow:FDUp,Min:Max,EnumWarning,Span,WF),
654 ? enumerate_int1(N,Min,Max). % will also do a case split, but without posting constraints
655
656 % try to determine integer variable bounds from pending co-routines for CLPFD off mode
657 clpfd_off_domain(Var,Low,Up,NewLow,NewUp) :-
658 frozen(Var,Goal), narrow_down_interval(Goal,Var,Low,Up,NewLow,NewUp).
659 % ((Lowx,Up)==(NewLow,NewUp) -> true ; print(narrowed_down(Var,Low,Up,NewLow,NewUp)),nl).
660 narrow_down_interval((A,B),Var,Low,Up,NewLow,NewUp) :- !,
661 narrow_down_interval(A,Var,Low,Up,Low1,Up1),
662 narrow_down_interval(B,Var,Low1,Up1,NewLow,NewUp).
663 narrow_down_interval(kernel_objects:safe_less_than_equal(_,V1,V2),Var,Low,Up,NewLow,NewUp) :- !,
664 (V1==Var,number(V2) -> NewLow=Low,fd_min(Up,V2,NewUp)
665 ; V2==Var,number(V1) -> fd_max(Low,V1,NewLow),NewUp=Up
666 ; NewLow=Low,NewUp=Up).
667 narrow_down_interval(kernel_objects:safe_less_than(V1,V2),Var,Low,Up,NewLow,NewUp) :- !,
668 (V1==Var,number(V2) -> NewLow=Low,V2m1 is V2-1, fd_min(Up,V2m1,NewUp)
669 ; V2==Var,number(V1) -> V1p1 is V1+1, fd_max(Low,V1p1,NewLow),NewUp=Up
670 ; NewLow=Low,NewUp=Up).
671 narrow_down_interval(_,_,L,U,L,U).
672
673 % check if this variable is marked as being assigned to by currently not-well-defined construct such as min,max,...:
674 is_wd_guarded_result_variable(N) :- % write('-WDG-'),
675 frozen(N,FrozenGoal), % TO DO: use attribute rather than frozen
676 is_wd_guarded_result_variable_aux(FrozenGoal,N).
677 is_wd_guarded_result_variable_aux(kernel_waitflags:is_wd_guarded_result(V),N) :- !, N==V.
678 is_wd_guarded_result_variable_aux((A,B),N) :-
679 is_wd_guarded_result_variable_aux(A,N) ; is_wd_guarded_result_variable_aux(B,N).
680
681 % enumerate unbounded integer variable N in a CLP(FD) fashion:
682 enum_unbounded_clp(0,Y,N,EnumWarning,Span,WF) :- (Y=sup ; Y>0),
683 % we span 0 and positive numbers
684 !,
685 (N=0
686 % for division/modulo... 0 is often a special case
687 ; try_post_constraint(N #>0),
688 force_enumerate_int_wo_case_split(N,'INTEGER',EnumWarning,Span,WF)
689 ).
690 enum_unbounded_clp(X,Y,N,EnumWarning,Span,WF) :-
691 (is_inf_or_overflow_card(X) -> true ; X<0), (Y=sup ; Y>0),
692 % we span both negative and positive numbers
693 !,
694 % do a case split
695 (N=0
696 % Instead of doing a case-split on 0; we could try and detect other relevant values (e.g., what if we have x / (y-1)
697 ; try_post_constraint(N #>0), % TO DO: use clpfd_lt_expr(0,N), ?and in other calls; this is an area where time-outs are more likely, but we cannot do anything about them anyway
698 ? force_enumerate_int_wo_case_split(N,'INTEGER',EnumWarning,Span,WF)
699 ; try_post_constraint(N #<0),
700 ? force_enumerate_int_wo_case_split(N,'INTEGER',EnumWarning,Span,WF)
701 ).
702 enum_unbounded_clp(FDLow,FDUp,N,EnumWarning,Span,WF) :-
703 % we cover only negative or only positive numbers
704 ? force_enumerate_with_warning(N,FDLow,FDUp,'INTEGER',EnumWarning,Span,WF).
705
706 % force enumeration without case split:
707 force_enumerate_int_wo_case_split(N,Msg,EnumWarning,Span,WF) :-
708 clpfd_domain(N,FDLow,FDUp), % print(enum(N,FDLow,FDUp)),nl,
709 (finite_domain(FDLow,FDUp)
710 -> label(N,FDLow,FDUp)
711 ; %print(force_enumerate_int_wo_case_split(FDLow,FDUp)),nl,
712 ? force_enumerate_with_warning(N,FDLow,FDUp,Msg,EnumWarning,Span,WF)
713 ).
714
715 force_enumerate_with_warning(N,_FDLow,_FDUp,_Msg,_EnumWarning,_Span,_WF) :- % check if we should enumerate at all
716 is_wd_guarded_result_variable(N),!. % affects tests 1825, 2017
717 force_enumerate_with_warning(N,FDLow,FDUp,Msg,EnumWarning,Span,WF) :-
718 make_domain_finite(FDLow,FDUp,Min,Max),
719 gen_enum_warning_wf(Msg,FDLow:FDUp,Min:Max,EnumWarning,Span,WF),
720 %try_post_constraint(N in Min..Max), % I am not sure whether this is useful or not
721 ? enumerate_int2(N,Min,Max).
722
723
724 % generate enumeration warning:
725 gen_enum_warning_wf(TYPE,RANGE,RESTRICTED_RANGE,Trigger,Span,WF) :-
726 Warning = enumeration_warning(enumerating(Info),TYPE,RANGE,RESTRICTED_RANGE,critical),
727 (get_trigger_info(Trigger,Info)
728 -> (Span=unknown,Info=b(_,_,_),get_texpr_pos(Info,Span2) -> true ; Span2=Span)
729 ; Info=unknown, Span2=Span
730 ),
731 (add_new_event_in_error_scope(Warning,
732 print_enum_warning(Trigger,TYPE,RANGE,RESTRICTED_RANGE,Span2,WF))
733 % may also throw(Warning)
734 ->
735 (preference(allow_enumeration_of_infinite_types,false)
736 -> formatsilent('### VIRTUAL TIME-OUT generated because ENUMERATE_INFINITE_TYPES=false~n',[]),
737 % print_pending_abort_error(WF),
738 (silent_mode(on) -> true ; print_span_nl(Span2)),
739 throw(Warning)
740 ; Trigger = trigger_throw(Source)
741 -> (silent_mode(on) -> true
742 ; Source=b(identifier(ID),_,_) ->
743 format('### VIRTUAL TIME-OUT generated for ~w ',[ID]),
744 print_span_nl(Span2)
745 ; format('### VIRTUAL TIME-OUT generated for ~w ',[Source]),
746 print_span_nl(Span2)
747 ),
748 throw(Warning)
749 ; true)
750 ; true).
751
752 %get_trigger_info(trigger_false(I),Info) :- get_trigger_info2(I,Info). % was non_critical ; no longer used
753 get_trigger_info(trigger_true(I),Info) :- get_trigger_info2(I,Info).
754 get_trigger_info(trigger_throw(I),Info) :- get_trigger_info2(I,Info).
755 %get_trigger_info2(enum_wf_context(_,Info),Res) :- !,Res=Info. % no longer used; WF now passed
756 get_trigger_info2(Info,Info).
757
758
759 % TO DO: pass WF explicitly rather than extracting it from enumeration warning terms
760 :- use_module(translate,[translate_span/2, translate_error_term/3]).
761 print_pending_abort_error(WF) :-
762 pending_abort_error(WF,Msg,ErrTerm,Span),
763 !, % just print one error
764 translate_span(Span,TSpan),
765 translate_error_term(ErrTerm,Span,TT),
766 (is_wait_flag_info(WF,expect_explicit_value)
767 -> ajoin(['Potential WD-Error: ',Msg],WDMsg),
768 add_warning(eval_expr_command,WDMsg,TT,Span)
769 ; format_with_colour(user_output,[bold],' (could be due to WD-Error ~w: ~w ~w)~n',[TSpan,Msg,TT])).
770 print_pending_abort_error(_).
771
772 % try and get get_pending_abort_error_for_trigger
773 get_pending_abort_error_for_info(WF,Span,FullMsg,ErrTerm) :-
774 pending_abort_error(WF,Msg,ErrTerm,Span),
775 ajoin(['Enumeration warning occured, probably caused by WD-Error: ',Msg],FullMsg).
776
777 :- use_module(translate,[print_span/1, print_span_nl/1]).
778 % THROWING,OuterSpan added by add_new_event_in_error_scope
779 print_enum_warning(_,_,_,_,_,WF,_THROWING,_) :-
780 \+ show_enumeration_warnings(WF),!.
781 print_enum_warning(_,_,_,_,_,_WF,THROWING,_) :-
782 silent_mode(on), % we could also check: performance_monitoring_on,
783 \+ will_throw_enum_warning(THROWING), % maybe we should also be silent if THROWING=throwing; see test 1522,
784 % see also test 2554 (if run with STRICT_RAISE_ENUM_WARNINGS = TRUE)
785 !. % do not print
786 print_enum_warning(Trigger,_,_,_,_LocalSpan,WF,THROWING,OuterThrowSpan) :-
787 will_throw_enum_warning(THROWING),
788 debug_mode(off),
789 !, % do not print detailed enumeration warning with reduced scopes; we print another message instead
790 print_throwing_wf(THROWING,Trigger,OuterThrowSpan,WF).
791 print_enum_warning(_,_,_,_,_,_WF,THROWING,_) :- THROWING \= throwing,
792 inc_counter(non_critical_enum_warnings,Nr), Nr>50,!, % do not print anymore
793 (Nr=51 -> write('### No longer printing non-critical enumeration warnings; limit exceeded.'),nl
794 ; true).
795 print_enum_warning(Trigger,TYPE,RANGE,RESTRICTED_RANGE,LocalSpan,WF,THROWING,OuterThrowSpan) :-
796 write('### Unbounded enumeration of '), % error_manager:trace_if_user_wants_it,
797 print_trigger_var(Trigger),
798 format('~w : ~w ---> ~w ',[TYPE,RANGE,RESTRICTED_RANGE]),
799 print_wf_context(WF),
800 print_span(LocalSpan),nl,
801 print_throwing_wf(THROWING,Trigger,OuterThrowSpan,WF).
802
803 % just count number of enum warnings
804 :- use_module(extension('counter/counter'),
805 [counter_init/0, new_counter/1, inc_counter/2, reset_counter/1]).
806 kernel_objects_startup :- % call once at startup to ensure all counters exist
807 counter_init,
808 new_counter(non_critical_enum_warnings).
809 kernel_objects_reset :- reset_counter(non_critical_enum_warnings).
810
811 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
812 :- register_event_listener(startup_prob,kernel_objects_startup,
813 'Initialise kernel_objects counters.').
814 :- register_event_listener(clear_specification,kernel_objects_reset,
815 'Reset kernel_objects counters.').
816
817 % -----------
818
819 will_throw_enum_warning(THROWING) :-
820 (THROWING=throwing -> true ; preference(strict_raise_enum_warnings,true)).
821
822 :- use_module(tools_printing,[format_with_colour/4]).
823 print_throwing(THROWING,Span) :- print_throwing_wf(THROWING,unknown_info,Span,no_wf_available).
824 print_throwing_wf(THROWING,TriggerInfo,ThrowSpan,WF) :-
825 peel_trigger(TriggerInfo,Info),
826 (preference(strict_raise_enum_warnings,true)
827 -> (get_pending_abort_error_for_info(WF,Span,Msg,ErrTerm)
828 -> add_error(strict_raise_enum_warnings,Msg,ErrTerm,Span)
829 ; (get_trigger_info_variable(Info,VID) -> true ; VID='?'),
830 add_error(strict_raise_enum_warnings,'Enumeration warning occured for ',VID,ThrowSpan)
831 )
832 ; true
833 ),
834 (THROWING=throwing
835 ->
836 (get_trigger_info_variable(Info,VarID)
837 -> format_with_colour(user_output,[bold],'Generating VIRTUAL TIME-OUT for unbounded enumeration of ~w!~n',[VarID])
838 ; format_with_colour(user_output,[bold],'Generating VIRTUAL TIME-OUT for unbounded enumeration warning!~n',[])
839 ),
840 print_pending_abort_error(WF),
841 (get_wait_flags_context_msg(WF,Msg) % % get call stack or other context message from WF
842 -> format_with_colour(user_output,[bold],' ~w~n',[Msg]) ; true),
843 (extract_span_description(ThrowSpan,PosMsg) -> format_with_colour(user_output,[bold],' ~w~n',[PosMsg]) ; true)
844 ; true).
845
846 peel_trigger(trigger_true(Info),Info) :- !.
847 peel_trigger(trigger_throw(Info),Info) :- !.
848 peel_trigger(Info,Info).
849
850 print_trigger_var(trigger_true(Info)) :- !, print_trigger_var_info(Info), write(' : ').
851 print_trigger_var(trigger_throw(Info)) :- !, print_trigger_var_info(Info), write(' : (all_solutions) : ').
852 %print_trigger_var(trigger_false(Info)) :- !, print_trigger_var_info(Info), print(' (not critical [unless failure]) : '). % no longer used
853 print_trigger_var(X) :- write(' UNKNOWN TRIGGER: '), print(X), write(' : ').
854
855 print_wf_context(WF) :-
856 (get_wait_flags_context_msg(WF,Msg)
857 -> format('~n### ~w~n ',[Msg]) %format(' : (~w)',[Msg])
858 ; true).
859 :- use_module(translate,[print_bexpr/1]).
860 print_trigger_var_info(b(E,T,I)) :- !, print_bexpr(b(E,T,I)), write(' '), print_span(I).
861 print_trigger_var_info(VarID) :- print(VarID).
862
863 % get variable name from trigger info field
864 get_trigger_info_variable(b(identifier(ID),_,_),VarID) :- !, VarID=ID.
865 get_trigger_info_variable(ID,VarID) :- atom(ID), VarID=ID.
866
867
868 % generate a warning if a large range is enumerated
869 gen_enum_warning_if_large(Var,FDLow,FDUp) :-
870 (FDUp>FDLow+8388608 /* 2**23 ; {x|x:1..2**23 & x mod 2 = x mod 1001} takes about 2 minutes */
871 % however the domain itself could be very small, we also check clpfd_size instead
872 -> fd_size(Var,Size), % no need to call clpfd_size; we know we are in CLP(FD) mode
873 (Size =< 8388608 -> true
874 ; enum_warning_large(Var,'INTEGER',FDLow:FDUp)
875 )
876 ; true).
877 enum_warning_large(_Var,TYPE,RANGE) :-
878 Warning = enumeration_warning(enumerating,TYPE,RANGE,RANGE,non_critical),
879 (add_new_event_in_error_scope(Warning,print_enum_warning_large(TYPE,RANGE))
880 -> true
881 ; true).
882
883 print_enum_warning_large(TYPE,RANGE,THROWING,Span) :-
884 print('### Warning: enumerating large range '),
885 print(TYPE), print(' : '),
886 print(RANGE),nl,
887 print_throwing(THROWING,Span).
888
889 :- block finite_warning(-,?,?,?,?).
890 finite_warning(_,Par,Types,Body,Source) :-
891 add_new_event_in_error_scope(enumeration_warning(checking_finite_closure,Par,Types,finite,critical),
892 print_finite_warning(Par,Types,Body,Source) ),
893 fail. % WITH NEW SEMANTICS OF ENUMERATION WARNING WE SHOULD PROBABLY ALWAYS FAIL HERE !
894 print_finite_warning(Par,Types,Body,Source,THROWING,Span) :-
895 print('### Warning: could not determine set comprehension to be finite: '),
896 translate:print_bvalue(closure(Par,Types,Body)),nl,
897 print('### Source: '), print(Source),nl,
898 print_throwing(THROWING,Span).
899
900 :- block enumerate_natural(-,?,-,?,?).
901 ?enumerate_natural(N,From,_,Span,WF) :- nonvar(N) -> true ; enumerate_natural(N,From,Span,WF).
902 enumerate_natural(N,From,Span,WF) :- preference(use_clpfd_solver,false),!,
903 clpfd_off_domain(N,From,sup,NewLow,NewUp), % try narrow down domain using co-routines
904 (finite_domain(NewLow,NewUp) -> enumerate_int1(N,NewLow,NewUp)
905 ? ; force_enumerate_with_warning(N,NewLow,NewUp,'NATURAL(1)',trigger_true('NATURAL(1)'),Span,WF)).
906 enumerate_natural(N,From,Span,WF) :- clpfd_domain(N,FDLow,FDUp),
907 fd_max(FDLow,From,Low),
908 (finite_domain(Low,FDUp)
909 ? -> label(N,Low,FDUp)
910 ? ; enumerate_natural_unbounded(N,Low,FDUp,Span,WF)
911 ).
912 enumerate_natural_unbounded(N,FDLow1,FDUp,Span,WF) :-
913 (FDLow1=0
914 -> (N=0 ; /* do a case split */
915 try_post_constraint(N #>0), % this can sometimes make the domain finite
916 ? force_enumerate_int_wo_case_split(N,'NATURAL',trigger_true('NATURAL'),Span,WF)
917 )
918 ; force_enumerate_with_warning(N,FDLow1,FDUp,'NATURAL(1)',trigger_true('NATURAL(1)'),Span,WF)
919 ).
920
921
922 % assumes one of FDLow and FDUp is not a number
923 make_domain_finite(FDLow,_FDUp,Min,Max) :- number(FDLow),!,Min=FDLow,
924 preferences:preference(maxint,MaxInt),
925 (MaxInt>=FDLow -> Max=MaxInt ; Max=FDLow). % ensure that we try at least one number
926 make_domain_finite(_FDLow,FDUp,Min,Max) :- number(FDUp),!,Max=FDUp,
927 preferences:preference(minint,MinInt),
928 (MinInt=<FDUp -> Min=MinInt ; Min=FDUp).
929 make_domain_finite(_FDLow,_FDUp,Min,Max) :-
930 ((preferences:preference(maxint,Max),
931 preferences:get_preference(minint,Min))->true). % ensure that we try at least one number
932
933 enumerate_int1(N,Min,Max) :-
934 (Min<0 /* enumerate positive numbers first; many specs only use NAT/NATURAL */
935 ? -> (enumerate_int2(N,0,Max) ; enumerate_int2(N,Min,-1))
936 ? ; enumerate_int2(N,Min,Max)
937 ).
938 enumerate_int(X,Low,Up) :- get_int_domain(X,Low,Up,RL,RU),
939 %% print(enumerate_int(X,Low,Up, RL,RU)),nl, %%
940 ? enumerate_int2(X,RL,RU).
941
942 get_int_domain(X,Low,Up,RL,RU) :- clpfd_domain(X,FDLow,FDUp),
943 fd_max(FDLow,Low,RL),fd_min(FDUp,Up,RU).
944
945 finite_domain(Low,Up) :- \+ infinite_domain(Low,Up).
946 infinite_domain(inf,_) :- !.
947 infinite_domain(_,sup).
948
949 % second arg should always be a number
950 fd_max(inf,L,R) :- !,R=L.
951 fd_max(FDX,Y,R) :- (nonvar(FDX),nonvar(Y),FDX>Y -> R=FDX ; R=Y).
952 fd_min(sup,L,R) :- !,R=L.
953 fd_min(FDX,Y,R) :- (nonvar(FDX),nonvar(Y),FDX<Y -> R=FDX ; R=Y).
954
955 :- use_module(clpfd_interface,[clpfd_randomised_enum/3]).
956
957 enumerate_int2(N,X,Y) :- % mainly called when CLPFD false
958 (preferences:get_preference(randomise_enumeration_order,true)
959 ? -> clpfd_randomised_enum(N,X,Y) ; enumerate_int2_linear(N,X,Y)).
960
961 enumerate_int2_linear(N,X,Y) :- X=<Y,
962 ? (N=X ; X1 is X+1, enumerate_int2_linear(N,X1,Y)).
963
964
965 enumerate_basic_type_set(X,Type,Tight,EnumWarning,WF) :- var(X),!,
966 max_cardinality_with_check(Type,Card),
967 ? enumerate_basic_type_set2(X,[],Card,Type,none,Tight,EnumWarning,WF).
968 enumerate_basic_type_set([],_,_,_EnumWarning,_WF) :- !.
969 enumerate_basic_type_set(avl_set(_),_,_,_EnumWarning,_WF) :- !.
970 enumerate_basic_type_set(freetype(_),_,_,_EnumWarning,_WF) :- !.
971 enumerate_basic_type_set(global_set(GS),Type,_Tight,_EnumWarning,_WF) :- !,
972 (Type = global(GT)
973 -> (GS = GT -> true
974 ; nonvar(GS), add_error_and_fail(enumerate_basic_type_set,'Type error in global set: ',GS:GT))
975 ; Type = integer,integer_global_set(GS)
976 ; Type = string, string_global_set(GS)
977 ; Type = real, real_global_set(GS)
978 ).
979 enumerate_basic_type_set(closure(Parameters, PT, Body),_Type,_Tight,_EnumWarning,WF) :- !,
980 (ground(Body) -> true
981 ; add_message_wf(kernel_objects,'Enumerating non-ground closure body: ',closure(Parameters, PT, Body),Body,WF),
982 % this did happen for symbolic total function closures set up for f : NATURAL1 --> ..., see test 2022
983 %term_variables(Body,Vars), print('### Variables: '), print(Vars),nl,
984 enumerate_values_inside_expression(Body,WF)
985 ).
986 enumerate_basic_type_set([H|T],Type,Tight,EnumWarning,WF) :- !,
987 % collect bound elements; avoid enumerating initial elements with elements that already appear later
988 collect_bound_elements([H|T], SoFar,Unbound,Closed),
989 (Closed=false -> max_cardinality_with_check(Type,Card)
990 ; Card = Closed),
991 % print(enum(Card,Unbound,SoFar,[H|T],Closed)),nl,
992 ? enumerate_basic_type_set2(Unbound,SoFar,Card,Type,none,Tight,EnumWarning,WF).
993 %enumerate_basic_type_set([H|T],Type,Tight,WF) :- !,
994 % (is_list_skeleton([H|T],Card) -> true
995 % ; max_cardinality_with_check(Type,Card)
996 % ),
997 % enumerate_basic_type_set2([H|T],[],Card,Type,none,Tight,WF).
998 enumerate_basic_type_set(S,Type,Tight,EnumWarning,WF) :-
999 add_internal_error('Illegal set: ',enumerate_basic_type_set(S,Type,Tight,EnumWarning,WF)).
1000
1001 enumerate_basic_type_set2(HT,ElementsSoFar,_Card,_Type,_Last,_Tight,_EnumWarning,_WF) :- nonvar(HT),
1002 is_custom_explicit_set(HT,enumerate_basic_type),!,
1003 disjoint_sets(HT,ElementsSoFar). % I am not sure this is necessary; probably other constraints already ensure this holds
1004 enumerate_basic_type_set2(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF) :- var(HT),
1005 preferences:preference(randomise_enumeration_order,true),!,
1006 (random(1,3,1)
1007 ? -> (enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF)
1008 ; HT = [])
1009 ; (HT = [] ;
1010 ? enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF))
1011 ).
1012 enumerate_basic_type_set2([],_,_,_,_,_Tight,_EnumWarning,_WF).
1013 enumerate_basic_type_set2(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF) :-
1014 ? enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF).
1015
1016 enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF) :- positive_card(Card),
1017 %debug:trace_point(enum(HT,ElementsSoFar,Card,Type,Last,Tight)),
1018 (var(HT) -> HT=[H|T], NewLast=NormH /* the enumerator has completely determined H */
1019 % Note: HT=[H|T] may wake up co-routines and then attach infos to H; but these should hold indpendently for all elements
1020 ; HT=[H|T],
1021 (unbound_value(H)
1022 -> NewLast=NormH /* the enumerator has completely determined H */
1023 ; NewLast=Last) /* H was not freely chosen by the enumerator */
1024 ),
1025 ? not_element_of(H,ElementsSoFar), % this is only needed for elements generated by the enumerator itself
1026 % if we pass WF to not_element_of then test 479 fails due to different enumeration order
1027 ? enumerate_type_wf(H,Type,Tight,EnumWarning,WF),
1028 % TO DO: extract normal form from add_new_element
1029 % Note: if H is_wd_guarded_result_variable then H may not be ground !!
1030 (ground_value(H)
1031 -> val_greater_than(H,NormH,Last),
1032 add_new_element(NormH,ElementsSoFar,SoFar2) % TODO : use add_new_element_wf ?
1033 ; add_new_element(H,ElementsSoFar,SoFar2),
1034 NormH=none
1035 ),
1036 C1 is Card-1,
1037 ? enumerate_basic_type_set2(T,SoFar2,C1,Type,NewLast,Tight,EnumWarning,WF).
1038
1039 :- assert_must_succeed((collect_bound_elements([int(1),int(2),int(4),X,int(5)|T],_,U,C),U==[X|T],C==false)).
1040 :- assert_must_succeed((collect_bound_elements([int(1),int(2),int(4),X,int(5)],_,U,C),U==[X],C==1)).
1041 :- assert_must_succeed(exhaustive_kernel_succeed_check(collect_bound_elements([int(1),int(2),int(4),int(5)],_,_,_))).
1042
1043 % collect the bound and unbound elements in a list; also return if the list is closed (then return length) or return false
1044 collect_bound_elements(T, SoFar,Unbound,Closed) :- var(T),!, SoFar=[],Unbound=T,Closed=false.
1045 collect_bound_elements([],[],[],0).
1046 collect_bound_elements(avl_set(A),avl_set(A),[],0).
1047 collect_bound_elements(global_set(GS),SoFar,Unbound,Closed) :- expand_custom_set(global_set(GS),ES),
1048 collect_bound_elements(ES,SoFar,Unbound,Closed).
1049 collect_bound_elements(freetype(FS),SoFar,Unbound,Closed) :- expand_custom_set(freetype(FS),ES),
1050 collect_bound_elements(ES,SoFar,Unbound,Closed).
1051 collect_bound_elements(closure(P,T,B),SoFar,Unbound,Closed) :- expand_custom_set(closure(P,T,B),ES),
1052 collect_bound_elements(ES,SoFar,Unbound,Closed).
1053 collect_bound_elements([H|T],SoFar,Unbound,Closed) :-
1054 collect_bound_elements(T,TSoFar,TUnbound,TClosed),
1055 (ground(H) -> add_new_element(H,TSoFar,SoFar), Unbound=TUnbound, TClosed=Closed
1056 ; SoFar = TSoFar, Unbound = [H|TUnbound],
1057 (TClosed=false -> Closed=false ; Closed is TClosed+1)
1058 ).
1059
1060
1061 % perform order checking on terms, normalising them first
1062 % val_greater_than(A,NormA,NormB)
1063 val_greater_than(A,NormA,NormB) :- !,
1064 (nonvar(A),custom_explicit_sets:convert_to_avl_inside_set(A,NormA)
1065 -> (NormB==none -> true ; NormA @> NormB)
1066 ; add_internal_error('Call failed: ',custom_explicit_sets:convert_to_avl_inside_set(A,NormA)),
1067 NormA = A).
1068
1069 positive_card(inf) :- !.
1070 positive_card(C) :- (integer(C) -> C>0
1071 ; add_internal_error('Not an integer: ',positive_card(C)),fail).
1072
1073
1074
1075 :- block enumerate_basic_field_types(?,-,?,-,?).
1076 enumerate_basic_field_types([],[],_Tight,_EnumWarning,_).
1077 enumerate_basic_field_types(Fields,[field(Name,VT)|TT],Tight,EnumWarning,WF) :-
1078 ? enumerate_basic_field_types2(Fields,Name,VT,TT,Tight,EnumWarning,WF).
1079
1080 :- block enumerate_basic_field_types2(?,-,?,?,?,?,?).
1081 enumerate_basic_field_types2([field(Name1,V)|T], Name2,VT,TT,Tight,EnumWarning,WF) :-
1082 check_field_name_compatibility(Name1,Name2,enumerate_basic_field_types2),
1083 ? enumerate_type_wf(V,VT,Tight,EnumWarning,WF),
1084 ? enumerate_basic_field_types(T,TT,Tight,EnumWarning,WF).
1085
1086
1087 :- block all_objects_of_type(-,?).
1088 all_objects_of_type(Type,Res) :-
1089 findall(O,enumerate_basic_type(O,Type),Res).
1090
1091 :- use_module(library(avl),[avl_size/2]).
1092 :- use_module(kernel_cardinality_attr,[clpfd_card_domain_for_var/3]).
1093 % obtain info for enumerating sequence lists: length of list skeleton and maximum index inferred to be in the list
1094 % (MaxIndex is not the maximum index that can appear in the full sequence !)
1095 list_length_info(X,LenSoFar,Len,Type,MaxIndex) :- var(X),!,
1096 Len=0,
1097 clpfd_card_domain_for_var(X,MinCard,MaxCard),
1098 ( number(MinCard)
1099 -> MaxIndex is MinCard+LenSoFar % we know a valid list must be at least LenSoFar+MinCard long
1100 ; MaxIndex=0),
1101 ( number(MaxCard)
1102 -> Max1 is MaxCard+LenSoFar, % MaxCard is the bound for the tail X only; add length of skeleton so far
1103 Type = open_bounded(Max1)
1104 ; Type = open).
1105 list_length_info([],_,0,closed,0).
1106 list_length_info([H|T],LenSoFar,C1,Type,MaxIndex1) :- Len1 is LenSoFar+1,
1107 list_length_info(T,Len1,C,Type,MaxIndex),
1108 C1 is C+1,
1109 (nonvar(H),H=(I,_),nonvar(I),I=int(Idx),number(Idx),Idx>MaxIndex
1110 -> MaxIndex1 = Idx ; MaxIndex1 = MaxIndex).
1111 list_length_info(avl_set(A),LenSoFar,Size,closed,0) :- % case arises e.g. in private_examples/ClearSy/2019_Dec/well_def
1112 (LenSoFar=0 -> Size=1000000 % then length not used anyway
1113 ; avl_size(A,Size)). % we could check that this is a sequence tail!
1114 list_length_info(closure(_,_,_),_,0,open,0).
1115
1116 :- assert_must_succeed((max_cardinality(set(couple(global('Name'),global('Code'))),64))).
1117 :- assert_must_succeed((max_cardinality(set(set(set(couple(global('Name'),global('Code'))))),_))).
1118 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc4,[case(a,boolean),case(b,couple(boolean,boolean))]),
1119 max_cardinality(freetype(selfc4),6),
1120 kernel_freetypes:reset_freetypes)).
1121 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc6,[case(a,boolean),case(b,freetype(selfc6)),case(c,constant([c]))]),
1122 kernel_freetypes:set_freetype_depth(3),
1123 findall(X,enumerate_tight_type(X,freetype(selfc6)),Solutions),
1124 length(Solutions,NumberOfSolutions),
1125 max_cardinality(freetype(selfc6),NumberOfSolutions),
1126 kernel_freetypes:reset_freetypes)).
1127
1128 :- use_module(tools_printing,[print_error/1]).
1129 max_cardinality_with_check(Set,CCard) :-
1130 ? (max_cardinality(Set,Card) ->
1131 (is_inf_or_overflow_card(Card)
1132 -> debug_println(9,very_large_cardinality(Set,Card)),
1133 CCard = 20000000
1134 ; CCard=Card,
1135 (Card>100 -> debug_println(9,large_cardinality(Set,Card)) ; true)
1136 )
1137 ; print_error(failed(max_cardinality(Set,CCard))), CCard = 10
1138 ).
1139 max_cardinality(global(T),Card) :- b_global_set_cardinality(T,Card).
1140 max_cardinality(boolean,2).
1141 max_cardinality(constant([_V]),1).
1142 max_cardinality(any,inf). % :- print_message(dont_know_card_of_any). /* TODO: what should we do here ? */
1143 max_cardinality(string,MC) :- max_cardinality_string(MC). % is inf now
1144 %max_cardinality(abort,1).
1145 max_cardinality(integer,Card) :- Card=inf. %b_global_set_cardinality('INTEGER',Card).
1146 max_cardinality(real,Card) :- Card=inf.
1147 max_cardinality(seq(X),Card) :- % Card=inf, unless a freetype can be of cardinality 0
1148 max_cardinality(set(couple(integer,X)),Card).
1149 max_cardinality(couple(X,Y),Card) :-
1150 ? max_cardinality(X,CX), max_cardinality(Y,CY), safe_mul(CX,CY,Card).
1151 max_cardinality(record([]),1).
1152 max_cardinality(record([field(_,T1)|RF]),Card) :-
1153 ? max_cardinality(record(RF),RC),
1154 max_cardinality(T1,C1),
1155 safe_mul(C1,RC,Card).
1156 ?max_cardinality(set(X),Card) :- max_cardinality(X,CX),
1157 safe_pow2(CX,Card).
1158 max_cardinality(freetype(Id),Card) :- max_cardinality_freetype(freetype(Id),Card).
1159 max_cardinality(freetype_lim_depth(Id,Depth),Card) :- max_cardinality_freetype(freetype_lim_depth(Id,Depth),Card).
1160
1161
1162
1163 /* ---------------------------- */
1164
1165
1166 /* use a cleverer, better enumeration than enumerate_basic_type */
1167 /* can only be used in certain circumstances: operation preconditions,
1168 properties,... but not for VARIABLES as there is no guarantee that
1169 something declared as a sequence will actually turn out to be a sequence */
1170
1171 :- assert_pre(kernel_objects:enumerate_tight_type(Obj,Type),
1172 (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
1173 :- assert_post(kernel_objects:enumerate_tight_type(Obj,_), (type_check(Obj,bsets_object),ground_check(Obj))).
1174 :- assert_pre(kernel_objects:enumerate_tight_type(Obj,Type,_),
1175 (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
1176 :- assert_post(kernel_objects:enumerate_tight_type(Obj,_,_), (type_check(Obj,bsets_object),ground_check(Obj))).
1177
1178 :- assert_must_succeed(enumerate_tight_type([(int(1),int(2)),(int(2),int(4))],
1179 seq(integer) )).
1180 :- assert_must_succeed(enumerate_tight_type([(int(1),int(2))],seq(integer) )).
1181 :- assert_must_succeed(enumerate_tight_type([],seq(integer) )).
1182 :- assert_must_succeed((enumerate_tight_type(X,record([field(a,integer),field(b,global('Name'))])),
1183 equal_object(X,rec([field(a,int(1)),field(b,fd(1,'Name'))])) )).
1184 :- assert_must_fail(enumerate_tight_type([(int(1),int(2)),(int(3),int(_))],
1185 seq(integer) )).
1186 :- assert_must_fail(enumerate_tight_type([(int(3),int(_))],seq(integer) )).
1187 :- assert_must_succeed((kernel_relations:is_sequence(X,global_set('Name')),
1188 enumerate_tight_type(X,seq(global('Name')) ),
1189 X = [(int(1),fd(2,'Name'))] )).
1190 :- assert_must_succeed(( enumerate_tight_type(XX, record([field(balance,integer),field(name,global('Name'))])) ,
1191 XX = rec([field(balance,int(1)),field(name,fd(3,'Name'))]) )).
1192 :- assert_must_succeed(( enumerate_tight_type(XX, set(record([field(balance,global('Name')),field(name,global('Name'))]))) , /* STILL TAKES VERY LONG !! */
1193 XX = [rec([field(balance,fd(3,'Name')),field(name,fd(3,'Name'))])] )).
1194 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(balance,global('Name')),field(name,global('Name'))]))) ,S),
1195 length(S,Len), Len = 512 )).
1196 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(name,global('Code'))]))) ,S),
1197 length(S,Len), Len = 4 )).
1198 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(fname,global('Code')),field(name,global('Code'))]))) ,S),
1199 length(S,Len), Len = 16 )).
1200 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(fname,global('Code')),field(name,global('Name'))]))) ,S),
1201 length(S,Len), Len = 64 )).
1202 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(global('Name'))) ,S),
1203 length(S,Len), Len = 8 )).
1204 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(boolean))) ,S),
1205 length(S,Len), Len = 16 )).
1206 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(global('Name')))) ,S),
1207 length(S,Len), Len = 256 )).
1208 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(global('Code')))) ,S),
1209 length(S,Len), Len = 16 )).
1210 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(boolean))) ,S),
1211 length(S,Len), Len = 16 )).
1212 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(couple(global('Code'),global('Name')))) ,S),
1213 length(S,Len), Len = 64 )).
1214 %:- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(couple(global('Code'),integer))) ,S),
1215 % length(S,Len), Len = 64 )).
1216 :- assert_must_succeed(( enumerate_tight_type(XX, set(record([field(balance,integer)]))) ,
1217 XX = [rec([field(balance,int(1))])] )).
1218 :- assert_must_succeed(( enumerate_tight_type(global_set('Code'),set(global('Code'))) )).
1219
1220 enumerate_tight_type(Obj,Type) :-
1221 ? enumerate_tight_type_wf(Obj,Type,no_wf_available).
1222
1223 enumerate_tight_type_wf(Obj,Type,WF) :-
1224 ? enumerate_tight_type_wf(Obj,Type,trigger_true(enumerate_tight_type),WF).
1225
1226 enumerate_tight_type(Obj,Type,EnumWarning) :- %enumerate_tight_type2(Type,Obj).
1227 enumerate_tight_type_wf(Obj,Type,EnumWarning,no_wf_available).
1228
1229 :- block enumerate_tight_type_wf(?,-,?,?), enumerate_tight_type_wf(?,?,-,?).
1230 enumerate_tight_type_wf(Obj,Type,EnumWarning,WF) :- %enumerate_tight_type2(Type,Obj).
1231 (ground_value(Obj) -> true ; % print(enumerate_tight_type(Obj,Type)),nl,
1232 ? enumerate_basic_type4(Type,Obj,tight,EnumWarning,WF)
1233 ).
1234
1235 /* TO DO: provide tight enumerators for nat, functions, ... ?? */
1236
1237
1238
1239 :- assert_must_succeed((X=[(int(I1),pred_true /* bool_true */),Y], dif(I1,1),
1240 kernel_objects:enumerate_seq_type(X,boolean,true),I1==2,Y=(int(1),pred_false /* bool_false */))).
1241
1242 ?enumerate_seq_type(X,Type,EnumWarning) :- enumerate_seq_type_wf(X,Type,EnumWarning,no_wf_available).
1243
1244 enumerate_seq_type_wf(X,Type,EnumWarning,WF) :-
1245 list_length_info(X,0,Len,ListType,MaxIndex), % ListType can be open or closed
1246 % determine MaxIndexForEnum:
1247 (ListType=closed
1248 -> MaxIndexForEnum=Len, EW = no_enum_warning,
1249 MaxIndex =< Len % otherwise this is obviously not a sequence (Index in set which is larger than size)
1250 ; ListType=open_bounded(MaxSize)
1251 -> MaxIndexForEnum=MaxSize, EW = no_enum_warning,
1252 MaxIndex =< MaxSize % otherwise cannot be a sequence
1253 % TO DO: use MinSize?
1254 ; (MaxIndex>Len -> Card = MaxIndex ; Card=Len), % in case we already have an explicit index which is higher than the length we use that as index
1255 b_global_set_cardinality('NAT1',NatCard),
1256 (NatCard<Card -> Max1=Card ; Max1=NatCard),
1257 (Max1<1 -> MaxIndexForEnum = 1 ; MaxIndexForEnum=Max1), % ensure that we generate enumeration warning
1258 EW = EnumWarning
1259 ),
1260 ? enumerate_seq(X,range(1,MaxIndexForEnum),MaxIndexForEnum,Type,EW,WF).
1261
1262 enumerate_seq([],_,_,_,_,_WF).
1263 enumerate_seq(V,_,_,_,_,_WF) :- nonvar(V),V=avl_set(_),!.
1264 enumerate_seq(V,_,_,Type,EnumWarning,WF) :- nonvar(V),V=closure(_,_,_),!,
1265 enumerate_basic_type_set(V,Type,not_tight,EnumWarning,WF).
1266 enumerate_seq(Seq,_,_,_,_,_WF) :- nonvar(Seq),
1267 is_custom_explicit_set(Seq,enumerate_seq),!.
1268 enumerate_seq(Seq,Indexes,Card,Type,EnumWarning,WF) :-
1269 (unbound_variable_for_cons(Seq)
1270 -> positive_card(Card),
1271 get_next_index(Indexes,Index,RemIndexes), % force next index
1272 Seq = [(int(Index),Element)|TSeq], VarEl=true
1273 ; Seq = [El|TSeq],
1274 (unbound_variable(El)
1275 -> VarEl=true, get_next_index(Indexes,Index,RemIndexes) % force next index
1276 ; VarEl=false),
1277 El = (int(Index),Element)
1278 ),
1279 (VarEl=true
1280 -> true % index already forced above
1281 ; number(Index) -> remove_index_ground(Indexes,Index,RemIndexes) % this can fail if Index > MaxIndex found above ! but not first time around, i.e., we will generate enum warning anyway
1282 ? ; remove_index(Indexes,Index,RemIndexes)
1283 ),
1284 (EnumWarning==no_enum_warning -> true
1285 ; gen_enum_warning_wf('seq (length)',inf,Card,EnumWarning,unknown,WF)), % delay enum_warning until we have made the first case-split (sometimes instantiating the sequence to at least one element will trigger an inconsistency)
1286 ? enumerate_tight_type_wf(Element,Type,WF),
1287 C1 is Card-1,
1288 ? enumerate_seq(TSeq,RemIndexes,C1,Type,no_enum_warning,WF).
1289
1290 get_next_index([Index1|RestIndexes],Index1,RestIndexes).
1291 get_next_index(range(I1,I2),I1,Res) :-
1292 I11 is I1+1,
1293 (I11>I2 -> Res=[] ; Res=range(I11,I2)).
1294
1295 remove_index_ground(Indexes,X,Res) :- get_next_index(Indexes,H,T),
1296 (X=H -> Res=T ; Res=[H|R2], remove_index_ground(T,X,R2)).
1297
1298 remove_index(Indexes,X,Res) :- get_next_index(Indexes,H,T),
1299 ? (X=H,Res=T ; X\==H, Res=[H|R2], remove_index(T,X,R2)).
1300
1301
1302
1303 /* a few more unit tests: */
1304
1305 :- assert_must_succeed(( findall(X,enumerate_type(X,set(couple(boolean,boolean)),tight) ,L), length(L,16) )).
1306 :- assert_must_succeed(( findall(X,enumerate_type(X,set(couple(boolean,boolean)),basic) ,L), length(L,16) )).
1307
1308 :- assert_must_succeed(( enumerate_tight_type(
1309 [rec([field(balance,int(0)),field(name,fd(2,'Name'))])],[
1310 rec([field(balance,int(1)),field(name,fd(3,'Name'))]),
1311 rec([field(balance,int(1)),field(name,fd(2,'Name'))]),
1312 rec([field(balance,int(0)),field(name,fd(1,'Name'))]),
1313 rec([field(balance,int(-1)),field(name,fd(1,'Name'))])],
1314 set(record([field(balance,integer),field(name,global('Name'))]))) )).
1315 :- assert_must_succeed(( enumerate_tight_type([
1316 rec([field(balance,int(1)),field(name,fd(2,'Name'))]),
1317 rec([field(balance,int(1)),field(name,fd(1,'Name'))]),
1318 rec([field(balance,int(0)),field(name,fd(1,'Name'))]),
1319 rec([field(balance,int(-1)),field(name,fd(1,'Name'))])|X],
1320 set(record([field(balance,integer),field(name,global('Name'))]))) ,
1321 X = [rec([field(balance,int(1)),field(name,fd(3,'Name'))])] )).
1322
1323 :- assert_must_succeed((not_element_of(X,[(pred_true /* bool_true */,pred_true /* bool_true */),
1324 (pred_true /* bool_true */,pred_false /* bool_false */),(pred_false /* bool_false */,pred_false /* bool_false */)]),
1325 enumerate_tight_type(X,couple(boolean,boolean)))).
1326
1327 :- assert_must_succeed(( not_equal_object(X,(pred_true /* bool_true */,pred_false /* bool_false */)),
1328 not_equal_object(X,(pred_false /* bool_false */,pred_false /* bool_false */)),
1329 not_equal_object(X,(pred_true /* bool_true */,pred_true /* bool_true */)),
1330 enumerate_tight_type(X,couple(boolean,boolean)))).
1331
1332 :- assert_must_succeed(( X = [fd(3,'Name')|T],enumerate_tight_type(X,set(global('Name'))),
1333 T == [fd(1,'Name'),fd(2,'Name')] )).
1334
1335
1336
1337 unbound_value(V) :-
1338 (var(V) -> unbound_variable(V)
1339 ; V = (V1,W1),unbound_value(V1), unbound_value(W1)).
1340
1341 :- use_module(bsyntaxtree,[syntaxtraversion/6]).
1342 enumerate_values_inside_expression(TExpr,WF) :-
1343 syntaxtraversion(TExpr,Expr,Type,_Infos,Subs,_),
1344 nonvar(Expr),!,
1345 enumerate_expr(Expr,Type,Subs,WF).
1346 enumerate_values_inside_expression(X,WF) :-
1347 add_internal_error('Unexpected B expression: ',enumerate_values_inside_expression(X,WF)).
1348
1349 %:- block enumerate_expr(-,?,?,?).
1350 enumerate_expr(value(X),Type,Subs,WF) :- !,
1351 (ground(Type) -> enumerate_value(X,Type,WF)
1352 ; add_internal_error('Value type not ground: ',enumerate_expr(value(X),Type,Subs,WF))).
1353 enumerate_expr(_,_,Subs,WF) :- l_enumerate_values_inside_expression(Subs,WF).
1354
1355 :- use_module(bsyntaxtree,[is_set_type/2]).
1356 % catch a few type errors:
1357 enumerate_value(X,Type,_) :- X==[], !,
1358 (is_set_type(Type,_) -> true ; add_internal_error('Illegal type: ',enumerate_value(X,Type,_))).
1359 enumerate_value(X,Type,WF) :- enumerate_basic_type_wf(X,Type,WF).
1360
1361 :- block l_enumerate_values_inside_expression(-,?).
1362 l_enumerate_values_inside_expression([],_WF).
1363 l_enumerate_values_inside_expression([H|T],WF) :-
1364 enumerate_values_inside_expression(H,WF),
1365 l_enumerate_values_inside_expression(T,WF).
1366
1367
1368 /* --------------- */
1369 /* top_level_dif/2 */
1370 /* --------------- */
1371 /* checks whether two terms have a different top-level functor */
1372
1373 :- assert_must_succeed(top_level_dif(a,b)).
1374 :- assert_must_succeed(top_level_dif(f(_X),g(_Z))).
1375 :- assert_must_fail(top_level_dif(f(a),f(_Z))).
1376 :- assert_must_fail(top_level_dif(f(a),f(b))).
1377
1378 :- block top_level_dif(-,?),top_level_dif(?,-).
1379 top_level_dif(X,Y) :-
1380 functor(X,FX,_),functor(Y,FY,_), FX\=FY. /* check arities ? */
1381
1382
1383 /* ------------------------------------------------------------------- */
1384 /* EQUAL OBJECT */
1385 /* ------------------------------------------------------------------- */
1386
1387 sample_closure(C) :-
1388 construct_closure([xx],[integer],Body,C),
1389 Body = b(conjunct(b(conjunct(
1390 b(member(b(identifier(xx),integer,[]),b(integer_set('NAT'),set(identifier(xx)),[])),pred,[]),
1391 b(greater(b(identifier(xx),integer,[]),b(integer(0),integer,[])),pred,[])),pred,[]),
1392 b(less(b(identifier(xx),integer,[]),b(integer(3),integer,[])),pred,[])),pred,[]).
1393
1394 :- assert_must_succeed(equal_object([int(3),int(1)],
1395 closure([zz],[integer],b(member(b(identifier(zz),integer,[]),b(value([int(1),int(3)]),set(integer),[])),pred,[])))).
1396 :- assert_must_succeed(( equal_object( (fd(1,'Name'),fd(1,'Name')) , (fd(1,'Name'),fd(1,'Name')) ) )).
1397 :- assert_must_succeed(( equal_object( (X,Y) , (fd(2,'Name'),fd(2,'Name')) ) , X = fd(2,'Name'), Y=fd(2,'Name') )).
1398 :- assert_must_fail(equal_object(term(a),term(b))).
1399 :- assert_must_fail(equal_object(int(1),int(2))).
1400 :- assert_must_fail(equal_object([term(a),term(b)],[term(a),term(c)])).
1401 :- assert_must_fail(equal_object([term(floating(1.0)),term(floating(1.001))],[term(floating(1.0)),term(floating(1.00001))])).
1402 :- assert_must_fail((equal_object([(int(1),[Y])],[(int(X),[Z])]),
1403 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[int(2)])).
1404 :- assert_must_fail(equal_object(rec([field(a,int(1))]),rec([field(a,int(2))]))).
1405 :- assert_must_fail(equal_object(rec([field(a,int(2)),field(b,int(3))]),
1406 rec([field(a,int(2)),field(b,int(4))]))).
1407 :- assert_must_succeed(equal_object(rec([field(a,int(2))]),rec([field(a,int(2))]))).
1408 :- assert_must_succeed(equal_object(rec([field(a,int(2)),field(b,[int(3),int(2)])]),
1409 rec([field(a,int(2)),field(b,[int(2),int(3)])]) )).
1410 :- assert_must_succeed(equal_object([(term(a),[])],[(term(a),[])])).
1411 :- assert_must_succeed(equal_object(_X,[int(1),int(2)])).
1412 :- assert_must_succeed(equal_object([int(1),int(2)],_X)).
1413 :- assert_must_succeed((equal_object([(int(1),[Y])],[(int(X),[Z])]),
1414 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[])).
1415 :- assert_must_succeed(equal_object([int(1),int(2)],[int(2),int(1)])).
1416 :- assert_must_succeed(equal_object(global_set('Name'),[fd(2,'Name'),fd(3,'Name'),fd(1,'Name')])).
1417 :- assert_must_succeed(equal_object(global_set('Name'),[fd(1,'Name'),fd(3,'Name'),fd(2,'Name')])).
1418 :- assert_must_succeed((equal_object([fd(3,'Name'),fd(2,'Name'),fd(1,'Name')],global_set('Name')))).
1419 %:- assert_must_succeed((equal_object([fd(3,'Name'),fd(2,'Name'),fd(1,'Name')],X),X=global_set('Name'))).
1420 :- assert_must_succeed((equal_object(Y,X),X=global_set('Name'),equal_object(Y,[fd(3,'Name'),fd(2,'Name'),fd(1,'Name')]))).
1421 :- assert_must_succeed((equal_object(X,X),X=global_set('Name'))).
1422 :- assert_must_succeed((equal_object(_,X),X=global_set('Name'))).
1423 :- assert_must_succeed((equal_object(X,global_set('Name')),X=global_set('Name'))).
1424 :- assert_must_succeed((equal_object([_A,_B],[int(2),int(1)]))).
1425 :- assert_must_fail((equal_object(X,global_set('Code')),X=global_set('Name'))).
1426 :- assert_must_fail((equal_object(Y,global_set('Name')),Y=[fd(3,'Name'),fd(1,'Name')])).
1427 :- assert_must_fail((equal_object(Y,global_set('Name')),Y=[_,_])).
1428 :- assert_must_succeed((equal_object(X,closure([xx],[integer],b(truth,pred,[]))),X==closure([xx],[integer],b(truth,pred,[])))).
1429 :- assert_must_succeed((sample_closure(C), equal_object([int(1),int(2)],C))).
1430 :- assert_must_succeed((sample_closure(C), equal_object(C,[int(1),int(2)]))).
1431 :- assert_must_fail((sample_closure(C), equal_object(C,[int(1),int(0)]))).
1432 :- assert_must_fail((sample_closure(C), equal_object(C,global_set('NAT')))).
1433 :- assert_must_succeed((equal_object(freeval(selfcx,a,int(5)),freeval(selfcx,a,int(5))))).
1434 :- assert_must_fail((equal_object([int(1),int(2),int(3)],global_set('NATURAL1')))).
1435 :- assert_must_fail((equal_object(X,global_set('NATURAL1')),equal_object(X,[int(1),int(2),int(3)]))).
1436 :- assert_must_fail((equal_object(X,[int(1),int(2),int(3)]),equal_object(X,global_set('NATURAL1')))).
1437 :- assert_must_fail((equal_object(X,global_set('NATURAL')),equal_object(X,global_set('NATURAL1')))).
1438 :- assert_must_succeed((equal_object(X,global_set('NATURAL')),equal_object(X,global_set('NATURAL')))).
1439 % :- assert_must_fail((equal_object(freeval(selfcx,a,int(5)),freeval(selfcy,a,int(5))))). % is a type error
1440 :- assert_must_fail((equal_object(freeval(selfcx,b,int(5)),freeval(selfcx,a,int(5))))).
1441 :- assert_must_fail((equal_object(freeval(selfcx,a,int(5)),freeval(selfcx,a,int(6))))).
1442 :- assert_must_succeed((equal_object(
1443 [[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
1444 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(3,'Name'),fd(2,'Name')]]
1445 ,[[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
1446 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(2,'Name'),fd(3,'Name')]])
1447 )).
1448 :- assert_must_succeed(exhaustive_kernel_check( (equal_object([int(3),int(2),int(1)],[int(2)|T]),
1449 equal_object(T,[int(1),int(3)])))).
1450 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object([int(3),int(1)],[int(1),int(3)]))).
1451 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object([string(three),string(one)],[string(one),string(three)]))).
1452 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object([term(floating(3.0)),term(floating(1.0))],[term(floating(1.0)),term(floating(3.0))]))).
1453 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object(
1454 [(string(three),term(floating(3.0))),(string(one),term(floating(1.0)))],
1455 [(string(one),term(floating(1.0))), (string(three),term(floating(3.0)))]))).
1456 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object(
1457 [(string(three),term(floating(3.0))),(string(one),term(floating(1.0))), (string(three),term(floating(1.0)))],
1458 [(string(three),term(floating(1.0))),(string(one),term(floating(1.0))), (string(three),term(floating(3.0)))]))).
1459 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object([int(3),int(4),int(1)],[int(4),int(1),int(3)]))).
1460
1461 %:- assert_must_succeed(exhaustive_kernel_fail_check([commutative],equal_object([int(1),int(2),int(3)],global_set('NATURAL1')))).
1462 :- assert_must_succeed(( equal_object([int(0),int(5)|T],avl_set(node(int(1),true,1,node(int(0),true,0,empty,empty),node(int(3),true,1,empty,node(int(5),true,0,empty,empty))))), nonvar(T),equal_object(T,[int(_A),int(_B)]) )).
1463 % NOTE: had multiple solutions; after solving Ticket #227 it no longer has :-)
1464 :- assert_must_succeed(( equal_object([int(0),int(5)|T],avl_set(node(int(1),true,1,node(int(0),true,0,empty,empty),node(int(3),true,1,empty,node(int(5),true,0,empty,empty))))), nonvar(T),equal_object(T,[_A,_B]) )).
1465
1466 :- assert_must_succeed((equal_object([_X,_Y],[int(1),int(2)]))).
1467 :- assert_must_succeed((equal_object([(int(1),X),(int(2),Y),(int(3),Z),(int(4),A),(int(5),B),(int(6),C),(int(7),D),(int(8),E),(int(9),F),(int(10),G)],avl_set(node((int(5),int(25)),true,0,node((int(2),int(4)),true,1,node((int(1),int(1)),true,0,empty,empty),node((int(3),int(9)),true,1,empty,node((int(4),int(16)),true,0,empty,empty))),node((int(8),int(64)),true,0,node((int(6),int(36)),true,1,empty,node((int(7),int(49)),true,0,empty,empty)),node((int(9),int(81)),true,1,empty,node((int(10),int(100)),true,0,empty,empty)))))),
1468 A == int(16), B == int(25),C == int(36),D == int(49),E == int(64),F == int(81),G == int(100),X == int(1),Y == int(4), Z == int(9))).
1469
1470 :- use_module(bool_pred).
1471
1472 ?equal_object(V1,V2) :- equal_object_wf(V1,V2,no_wf_available).
1473 ?equal_object(V1,V2,Origin) :- equal_object_wf(V1,V2,Origin,no_wf_available).
1474 ?equal_object_optimized(V1,V2,Origin) :- equal_object_optimized_wf(V1,V2,Origin,no_wf_available).
1475 ?equal_object_optimized(V1,V2) :- equal_object_optimized(V1,V2,unknown).
1476
1477 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
1478 :- if(environ(prob_safe_mode,true)).
1479 /* a version of equal_object which will convert lists to avl if possible */
1480 equal_object_optimized_wf(V1,V2,Origin,WF) :-
1481 ( var(V1) -> (var(V2) -> V1=V2 ; equal_object_opt3(V2,V1,WF))
1482 ; equal_object_opt3(V1,V2,WF)),
1483 check_value(V1,Origin), check_value(V2,Origin).
1484 equal_object_wf(V1,V2,Origin,WF) :- ( (var(V1);var(V2)) -> V1=V2
1485 ; nonvar(V1) -> equal_object3(V1,V2,WF)
1486 ; equal_object3(V2,V1,WF)),
1487 check_value(V1,val1(Origin)), check_value(V2,val2(Origin)).
1488 equal_object_wf(V1,V2,WF) :- ( (var(V1);var(V2)) -> V1=V2
1489 ; nonvar(V1) -> equal_object3(V1,V2,WF)
1490 ; equal_object3(V2,V1,WF)),
1491 check_value(V1,equal_object1), check_value(V2,equal_object2).
1492 check_value(X,Origin) :- nonvar(X) -> check_value_aux(X,Origin) ; true.
1493 check_value_aux((A,B),Origin) :- !, check_value(A,pair1(Origin)), check_value(B,pair2(Origin)).
1494 check_value_aux([H|T],Origin) :- !, check_value(H,head(Origin)), check_value(T,tail(Origin)).
1495 check_value_aux(avl_set(X),Origin) :- !,
1496 (var(X) -> add_warning(Origin,'Variable avl_set')
1497 ; X=empty -> add_warning(Origin,'Empty avl_set') ; true).
1498 check_value_aux(closure(P,T,B),Origin) :- !,
1499 (ground(P),ground(T),nonvar(B) -> true
1500 ; add_warning(Origin,illegal_closure(P,T,B))).
1501 check_value_aux(_,_Origin).
1502 :- else.
1503 /* a version of equal_object which will convert lists to avl if possible */
1504 equal_object_optimized_wf(V1,V2,_Origin,WF) :-
1505 ? ( var(V1) -> (var(V2) -> V1=V2 ; equal_object_opt3(V2,V1,WF))
1506 ? ; equal_object_opt3(V1,V2,WF)).
1507
1508 equal_object_wf(V1,V2,_Origin,WF) :- ( (var(V1);var(V2)) -> V1=V2
1509 ? ; nonvar(V1) -> equal_object3(V1,V2,WF)
1510 ; equal_object3(V2,V1,WF)).
1511 equal_object_wf(V1,V2,WF) :- ( (var(V1);var(V2)) -> V1=V2
1512 ? ; nonvar(V1) -> equal_object3(V1,V2,WF)
1513 ; equal_object3(V2,V1,WF)).
1514 :- endif.
1515
1516
1517 equal_object_opt3(int(X),Y,_WF) :- !, Y=int(X).
1518 equal_object_opt3(fd(X,T),Y,_WF) :- !, Y=fd(X,T).
1519 equal_object_opt3(string(X),Y,_WF) :- !, Y=string(X).
1520 equal_object_opt3(pred_false,Y,_WF) :- !, Y=pred_false.
1521 equal_object_opt3(pred_true,Y,_WF) :- !, Y=pred_true.
1522 equal_object_opt3(X,S2,WF) :- var(S2), %unbound_variable(S2), % is it ok to assing an AVL set in one go ?!
1523 should_be_converted_to_avl_from_lists(X), !, % does a ground(X) check
1524 ? construct_avl_from_lists_wf(X,S2,WF).
1525 %equal_object_opt3([H|T],S2) :- var(S2),ground(H),ground(T), !, construct_avl_from_lists([H|T],S2).
1526 ?equal_object_opt3(X,Y,WF) :- equal_object3(X,Y,WF).
1527
1528
1529 %%equal_object3c(X,Y) :- if(equal_object3(X,Y),true,
1530 %% (print_message(equal_object3_failed(X,Y)),equal_object3(X,Y),fail)). %%
1531 :- if(environ(prob_safe_mode,true)).
1532 equal_object3(X,Y,_WF) :- (nonvar(Y) -> type_error(X,Y) ; illegal_value(X)),
1533 add_internal_error('Internal Typing Error (please report as bug !) : ',equal_object(X,Y)),fail.
1534 :- endif.
1535 equal_object3(closure(Par,ParTypes,Clo),Y,WF) :- var(Y),!,
1536 ( closure_occurs_check(Y,Par,ParTypes,Clo)
1537 -> debug_println(29,occurs_check(Y,Par)),
1538 expand_custom_set_wf(closure(Par,ParTypes,Clo),Expansion,equal_object3,WF),
1539 equal_object_optimized_wf(Y,Expansion,equal_object3,WF)
1540 ; Y = closure(Par,ParTypes,Clo)).
1541 equal_object3(closure(Parameters,PT,Cond),Y,WF) :-
1542 ? equal_object_custom_explicit_set(closure(Parameters,PT,Cond),Y,WF).
1543 %equal_object3(Obj,Y) :- is_custom_explicit_set(Obj,equal_object3_Obj),
1544 % equal_object_custom_explicit_set(Obj,Y,WF). % inlined below for performance
1545 equal_object3(global_set(X),Y,WF) :- equal_object_custom_explicit_set(global_set(X),Y,WF).
1546 equal_object3(freetype(X),Y,WF) :- equal_object_custom_explicit_set(freetype(X),Y,WF).
1547 ?equal_object3(avl_set(X),Y,WF) :- equal_object_custom_explicit_set(avl_set(X),Y,WF).
1548 equal_object3(pred_true /* bool_true */,pred_true /* bool_true */,_WF).
1549 equal_object3(pred_false /* bool_false */,pred_false /* bool_false */,_WF).
1550 equal_object3(term(X),term(X),_WF).
1551 equal_object3(string(X),string(X),_WF).
1552 ?equal_object3(rec(F1),rec(F2),WF) :- equal_fields_wf(F1,F2,WF).
1553 equal_object3(freeval(Id,C,F1),freeval(Id,C,F2),WF) :-
1554 ? instantiate_freetype_case(Id,C,C),
1555 ? equal_object_wf(F1,F2,WF).
1556 equal_object3(int(X),int(X),_WF).
1557 ?equal_object3(fd(X,Type),fd(Y,Type),_WF) :- eq_fd(X,Y).
1558 equal_object3((X,Y),(X2,Y2),WF) :- %write(eq(X,Y,X2,Y2)),nl,
1559 (check_if_can_unify(Y,Y2)
1560 -> true %before unifying X/X2 quickly check if Y/Y2 definitely not_equal
1561 ; %write(no_unify((X,Y),(X2,Y2))),nl,
1562 fail), %
1563 ? equal_object_wf(X,X2,WF),
1564 ? equal_object_wf(Y,Y2,WF). % initially order was reversed; but this can lead to issues in e.g. g(f("f2")), for f = {"f0"|->0, "f2"|->2} where g gets called for 0 before "f2"="f0" fails
1565 equal_object3([],X,WF) :- empty_set_wf(X,WF).
1566 equal_object3([H|T],S2,WF) :- nonvar(S2), is_custom_explicit_set_nonvar(S2),!,
1567 ? equal_custom_explicit_set_cons_wf(S2,H,T,WF).
1568 %equal_object3([H|T],S2,WF) :- equal_cons_wf(S2,H,T,WF). % leads to time-out for test 1270 : TODO investigate
1569 ?equal_object3([H|T],S2,_WF) :- equal_cons(S2,H,T).
1570
1571 % relevant for test 1419 for SICStus 4.10 for formula
1572 % card(x)=1 & !(y).(y:x & prj1(INTEGER,BOOL)(y)<50 => (prj1(INTEGER,BOOL)(y)+1,TRUE):x) & x<:(1..50)*BOOL
1573 % due to issue SPRM-21542 indomain/labeling triggers reifications without labeled value being visible to triggered code
1574 % triggered also in tests 654, 659, 995, 1079, 2142, 2341 or for !x.(x:1..10 => (x,TRUE) = (f(x),FALSE)) & f: 1..10 --> 1..10
1575 check_if_can_unify(X,Y) :- nonvar(X), nonvar(Y),!, check_if_can_unify_nv(X,Y).
1576 % should we do more checks ground string(.), ground integers, nested couple (X1,X2)
1577 check_if_can_unify(_,_).
1578 check_if_can_unify_nv(pred_true,R) :- !, R=pred_true.
1579 check_if_can_unify_nv(pred_false,R) :- !, R=pred_false.
1580 check_if_can_unify_nv(int(X),int(Y)) :- !,check_if_can_unify_atomic(X,Y).
1581 check_if_can_unify_nv(string(X),string(Y)) :- !,check_if_can_unify_atomic(X,Y).
1582 check_if_can_unify_nv(fd(X,T),fd(Y,T)) :- !,check_if_can_unify_atomic(X,Y).
1583 check_if_can_unify_nv(_,_).
1584
1585 check_if_can_unify_atomic(X,Y) :- nonvar(X),nonvar(Y),!,X=Y.
1586 check_if_can_unify_atomic(_,_).
1587
1588 equal_object_custom_explicit_set(Obj,Y,WF) :-
1589 (var(Y) -> Y = Obj
1590 ? ; (is_custom_explicit_set_nonvar(Y) -> equal_explicit_sets_wf(Obj,Y,WF)
1591 ; (Y=[] -> is_empty_explicit_set_wf(Obj,WF)
1592 ? ; Y=[H|T] -> equal_custom_explicit_set_cons_wf(Obj,H,T,WF)
1593 ; add_internal_error('Illegal set: ',equal_object_custom_explicit_set(Obj,Y,WF)),fail
1594 )
1595 )).
1596
1597 equal_custom_explicit_set_cons_wf(CS,H,T,_WF) :- CS \= avl_set(_),
1598 var(H),var(T), % TO DO: should we move this treatment below ? to equal_cons_lwf
1599 % YES, I THINK WE CAN DELETE THIS NOW for avl_sets; but not yet for global_set,...
1600 % print_term_summary(equal_custom_explicit_set_cons(CS,H,T)),nl, (debug_mode(on) -> trace ; true),
1601 unbound_variable(H),
1602 unbound_variable_for_cons(T),
1603 !,
1604 remove_minimum_element_custom_set(CS,Min,NewCS),
1605 (H,T) = (Min,NewCS).
1606 equal_custom_explicit_set_cons_wf(avl_set(AVL),H,T,_WF) :- var(H),
1607 is_unbound_ordered_list_skeleton(H,T),!, % TO DO: provide this also for global_set(_)
1608 % below we check if H can be removed from AVL and remove it
1609 remove_minimal_elements([H|T],avl_set(AVL),SkeletonToUnify),
1610 [H|T] = SkeletonToUnify.
1611 equal_custom_explicit_set_cons_wf(Obj,H,T,WF) :-
1612 ? equal_cons_lwf(Obj,H,T,2,WF).
1613 %equal_cons_wf(Obj,H,T,WF). % equal_cons_wf causes issues to tests 799, (but not anymore 1751, 1642, 1708)
1614
1615
1616 :- block equal_fields_wf(-,-,?).
1617 equal_fields_wf([],[],_).
1618 equal_fields_wf([field(Name1,V1)|T1],[field(Name2,V2)|T2],WF) :-
1619 check_field_name_compatibility(Name1,Name2,equal_fields_wf),
1620 % TODO: check check_if_can_unify applied to T1/T2?
1621 ? equal_object_wf(V1,V2,field,WF),
1622 ? equal_fields_wf(T1,T2,WF).
1623
1624
1625 % is just like equal_cons, but H and T are guaranteed by the caller to be free
1626 % this just gives one next element of the set; can be used to iterate over sets.
1627 get_next_element(R,H,T) :- var(R),!,R=[H|T].
1628 get_next_element([H1|T1],H,T) :- !,(H1,T1)=(H,T).
1629 get_next_element(R,H,T) :- equal_cons(R,H,T).
1630
1631
1632 ?equal_cons_wf(R,H,T,WF) :- WF == no_wf_available,!, equal_cons_lwf(R,H,T,2,WF).
1633 equal_cons_wf(R,H,T,WF) :-
1634 %get_cardinality_wait_flag(R,equal_cons_wf,WF,LWF),
1635 %get_binary_choice_wait_flag(equal_cons_wf,WF,LWF), %old version
1636 LWF = lwf_card(R,equal_cons_wf,WF), % will be instantiated by instantiate_lwf
1637 ? equal_cons_lwf(R,H,T,LWF,WF).
1638
1639 % a deterministic version; will never instantiate non-deterministically:
1640 % probably better to use equal_cons_wf if possible
1641 %equal_cons_det(R,H,T) :- equal_cons_lwf4(R,H,T,_).
1642
1643 equal_cons(R,H,T) :-
1644 ? equal_cons_lwf(R,H,T,2,no_wf_available). %lwf_first(2)).
1645
1646 :- block blocking_equal_cons_lwf(-,?,?,?,?).
1647 ?blocking_equal_cons_lwf(E,H,T,LWF,WF) :- equal_cons_lwf(E,H,T,LWF,WF).
1648
1649 %equal_cons_lwf4(R,H,T,LWF) :- equal_cons_lwf(R,H,T,LWF,no_wf_available).
1650
1651 ?equal_cons_lwf(R,H,T,_,_) :- var(R),!,add_new_el(T,H,R).
1652 equal_cons_lwf([HR|TR],H,T,_,WF) :- ground_value(H), %print(delete_exact(H,[HR|TR])),nl,
1653 try_quick_delete_exact_member([HR|TR],H,Rest), % try and see if we can find an exact member in the list
1654 % adds quadratic complexity if TR is a list; TODO: maybe do a sort
1655 !,
1656 %equal_object(Rest,T,equal_cons_lwf_1).
1657 ? equal_object_wf(Rest,T,equal_cons_lwf_1,WF).
1658 ?equal_cons_lwf([HR|TR],H,T,LWF,WF) :- !, equal_cons_cons(HR,TR,H,T,LWF,WF).
1659 equal_cons_lwf(avl_set(AVL),H,T,LWF,WF) :- !,
1660 (is_one_element_custom_set(avl_set(AVL),El)
1661 ? -> empty_set(T), % was T=[], but T could be an empty closure !
1662 ? equal_object_wf(El,H,equal_cons_lwf_2,WF)
1663 ; T==[] -> fail % we have a one element set and AVL is not
1664 ; element_can_be_added_or_removed_to_avl(H) ->
1665 remove_element_from_explicit_set(avl_set(AVL),H,AR),
1666 ? equal_object_wf(AR,T,equal_cons_lwf_3,WF)
1667 ; nonvar(T),T=[H2|T2],element_can_be_added_or_removed_to_avl(H2) ->
1668 remove_element_from_explicit_set(avl_set(AVL),H2,AR),
1669 ? equal_object_wf(AR,[H|T2],equal_cons_lwf_4,WF)
1670 % TO DO: move all such H2 to the front ??
1671 % Common pattern for function application patterns f(a) = 1 & f(b) = 2 & f = AVL
1672 % We have f = [(a,1),(b,2)|_] to be unified with an avl_set
1673 ; at_most_one_match_possible(H,AVL,Pairs) -> Pairs=[H2], % unification could fail if no match found
1674 % this optimisation is redundant wrt definitely_not_in_list optimisation below; check test 1716
1675 % but it has better performance for large sets, e.g., when unifying with a large sequence skeleton
1676 % TODO: it could be useful even if there are more than one matches??
1677 ? equal_object_wf(H,H2,WF),
1678 % element_can_be_added_or_removed_to_avl not checked !
1679 % we may need to call another predicate to remove, which only checks index
1680 % or at_most_one_match_possible should remove the element itself
1681 remove_element_from_explicit_set(avl_set(AVL),H2,AR), % print(removed_from_avl_by_equal_cons(H)),nl,
1682 ? equal_object_wf(AR,T,equal_cons_lwf_3,WF) %%
1683 ; expand_custom_set_wf(avl_set(AVL),ES,equal_cons_lwf,WF), % length(ES,LenES),print(expanded(LenES,T)),nl,
1684 % before attempting unification quickly look if lengths are compatible:
1685 ? quick_check_length_compatible(ES,[H|T]), % not really sure this is worth it: we have propagate_card in equal_cons_cons below
1686 %we could do the following: (nonvar(LWF),LWF=lwf_card(_,_,WF) -> quick_propagation_element_information(avl_set(AVL),H,WF,NS) ; true) % we could also do it for T, but both H/T can cause issues with free_var detection
1687 equal_cons_perf_message(AVL,H,T,WF),
1688 ? equal_cons_lwf(ES,H,T,LWF,WF) ).
1689 equal_cons_lwf(C,H,T,LWF,WF) :-
1690 is_interval_closure_or_integerset(C,Low,Up),
1691 (T==[] -> true ; finite_bound(Low), finite_bound(Up)),
1692 !,
1693 ? equal_cons_interval(H,T,Low,Up,LWF,WF).
1694 equal_cons_lwf(closure(P,Ty,B),H,T,LWF,WF) :- !,
1695 ? equal_cons_closure(P,Ty,B,H,T,LWF,WF).
1696 equal_cons_lwf(freetype(ID),H,T,LWF,WF) :- !, expand_custom_set_wf(freetype(ID),ES,equal_cons_lwf,WF),
1697 blocking_equal_cons_lwf(ES,H,T,LWF,WF).
1698 ?equal_cons_lwf(global_set(G),H,T,LWF,WF) :- equal_cons_global_set(G,H,T,LWF,WF).
1699
1700
1701 :- use_module(probsrc(avl_tools),[avl_height_less_than/2]).
1702 :- use_module(performance_messages,[perf_format_wf/3]).
1703 equal_cons_perf_message(AVL,H,T,WF) :- preference(performance_monitoring_on,true),
1704 \+ avl_height_less_than(AVL,5),
1705 \+ is_unbound_ordered_list_skeleton(H,T), % otherwise H will be set to minimum of AVL deterministically
1706 !,
1707 translate:translate_bvalue(avl_set(AVL),AS),
1708 translate:translate_bvalue([H|T],HTS),
1709 perf_format_wf('Expanding avl_set for set-unification~n ~w~n =~n ~w~n',[AS,HTS],WF).
1710 equal_cons_perf_message(_,_,_,_).
1711
1712 equal_cons_closure(P,Ty,B,_H,T,_LWF,_WF) :- nonvar(T),
1713 is_definitely_finite(T), % move earlier; is_infinite_closure can perform expansions, e.g., for nested closures
1714 is_infinite_closure(P,Ty,B),
1715 !,
1716 fail. % an infinite set cannot be equal to a finite one.
1717 equal_cons_closure(Par,Types,B,H,T,LWF,WF) :-
1718 % used to be expand_custom_set_wf(closure(Par,Types,B),ES,equal_cons_closure,WF) which calls:
1719 expand_closure_to_list(Par,Types,B,ES,Done,equal_cons_closure,WF),
1720 ? lazy_check_elements_of_closure([H|T],Done, Par,Types,B,WF), % relevant for test 2466
1721 % the lazy check in custom_explicit_sets does not trigger, as we cannot unify [H|T] with ES (unlike in equal_expansions3)
1722 % because we do not know if [H|T] is ordered
1723 ? blocking_equal_cons_lwf(ES,H,T,LWF,WF).
1724
1725 is_definitely_finite(Var) :- var(Var),!,fail.
1726 is_definitely_finite([]).
1727 is_definitely_finite([_|T]) :- is_definitely_finite(T).
1728 is_definitely_finite(avl_set(_)).
1729
1730 %get_wf_from_lwf(LWF,WF) :- % TO DO: a cleaner, less hacky version; passing WF around if possible
1731 % (nonvar(LWF),LWF=lwf_card(_,_,WF1) -> WF=WF1 ; WF = no_wf_available).
1732
1733 finite_bound(I) :- (var(I) -> true /* inf would be created straightaway */ ; number(I)).
1734
1735 % Purpose: treat some specific closures better; e.g., interval closures and constraint a..b = {1,y,5,x,4} or a..b = {x} & x:100..1002
1736 equal_cons_interval(H,T,Low,Up,_LWF,_WF) :- T==[],!, % Low..Up = {H} -> Low=H & Up=H
1737 % unification will fail if Low or Up are not numbers (inf)
1738 (int(Low),int(Up)) = (H,H).
1739 %equal_cons_interval(_H,_T,Low,Up,_LWF,WF) :- (nonvar(Low),\+ number(Low) ; nonvar(Up),\+ number(Up)),!,
1740 % gen_enum_warning_wf('OPEN INTERVAL',Low:Up,'cannot expand',trigger_throw(equal_cons_interval),WF),
1741 % % we could try and instantiate T to an infinite closure
1742 % fail.
1743 equal_cons_interval(H,T,Low,Up,LWF,WF) :-
1744 (number(Low),number(Up) -> true % we can expand interval fully
1745 ; propagate_in_interval([H|T],int(Low),int(Up),0)),
1746 expand_interval_closure_to_avl(Low,Up,ES),
1747 ? blocking_equal_cons_lwf(ES,H,T,LWF,WF).
1748
1749 :- block propagate_in_interval(-,?,?,?).
1750 propagate_in_interval([],Low,Up,Sze) :-
1751 (Sze > 0 -> S1 is Sze-1, int_plus(Low,int(S1),Up) ; true). % Test should always be true
1752 propagate_in_interval([H|T],Low,Up,Sze) :-
1753 in_nat_range(H,Low,Up), % without enumeration
1754 S1 is Sze+1,
1755 propagate_in_interval(T,Low,Up,S1).
1756 propagate_in_interval(avl_set(_A),_Low,_Up,_). % TO DO: propagate if Low/Up not instantiated
1757 propagate_in_interval(closure(_,_,_),_,_,_).
1758 propagate_in_interval(global_set(_),_,_,_).
1759
1760 quick_check_length_compatible([],R) :- !,
1761 (var(R) -> R=[] % can we force R=[] here ??
1762 ; R \= [_|_]). %(R \= [_|_] -> true ; print(incompatible(R)),fail).
1763 quick_check_length_compatible([_|T],R) :-
1764 (var(R) -> true
1765 ; R = [] -> fail
1766 ? ; R = [_|RT] -> quick_check_length_compatible(T,RT)
1767 ; true).
1768
1769 :- block equal_cons_global_set(-,?,?,?,?).
1770 ?equal_cons_global_set(G,H,T,LWF,WF) :- is_infinite_global_set(G,_),!,
1771 % for maximal sets we could complement_set([H],global(G),Res),
1772 /* should normally fail, unless T is not a list but contains closure or global set */
1773 test_finite_set_wf(T,Finite,WF), dif(Finite,pred_true),
1774 when((nonvar(Finite);nonvar(LWF)),equal_cons_global_set_warning(LWF,G,H,T,WF)).
1775 % used to be : expand_custom_set(global_set(G),ES), equal_cons_lwf4(ES,H,T,LWF))).
1776 equal_cons_global_set(G,H,T,LWF,WF) :-
1777 %(is_infinite_global_set(G,_) -> test_finite_set_wf(T,Finite,WF), Finite \== pred_true ; true),
1778 expand_custom_set_wf(global_set(G),ES,equal_cons_global_set,WF),
1779 ? equal_cons_lwf(ES,H,T,LWF,WF).
1780
1781
1782 :- block equal_cons_global_set_warning(-,?,?,?,?).
1783 equal_cons_global_set_warning(_,G,H,T,WF) :-
1784 add_new_event_in_error_scope(enumeration_warning(enumerating(G),G,'{}',finite,critical),
1785 print_equal_cons_warning(G,H,T,WF)),
1786 fail. % WITH NEW SEMANTICS OF ENUMERATION WARNING WE SHOULD PROBABLY ALWAYS FAIL HERE !
1787
1788 % THROWING, Span added by add_new_event_in_error_scope
1789 print_equal_cons_warning(G,H,T,WF,THROWING,Span) :-
1790 print('### Enumeration Warning: trying to deconstruct infinite set: '),
1791 translate:print_bvalue(global_set(G)),nl,
1792 print('### Source: '), print(equal_cons_global_set(G,H,T)),nl,
1793 print_throwing_wf(THROWING,unknown_info,Span,WF).
1794
1795 add_new_el(T,H,R) :- var(T),!,R=[H|T].
1796 add_new_el(T,H,R) :- nonvar(T), is_custom_explicit_set_nonvar(T),
1797 add_element_to_explicit_set_wf(T,H,Res,no_wf_available), % will fail for closure/3
1798 !,
1799 Res=R.
1800 add_new_el([HT|TT],H,R) :- !,R=[H,HT|TT].
1801 add_new_el([],H,R) :- !, R=[H].
1802 add_new_el(Set,H,R) :- expand_custom_set_to_list(Set,ESet,_,add_new_el),
1803 add_new_el(ESet,H,R).
1804
1805 %delete_exact_member(V,_,_) :- var(V),!,fail.
1806 %delete_exact_member([H|T],El,Res) :-
1807 % (H==El -> Res=T
1808 % ; Res=[H|TR], delete_exact_member(T,El,TR)).
1809
1810 % a version of delete_exact_member with a cut off
1811 % avoids spending useless time traversing large non-ground lists
1812 % for a list consisting only of non-ground elements delete_exact_member will never succeed !
1813 % this occurs e.g., when a large list skeleton generated by e.g. size_of_sequence is unified with an avl_set
1814 % (e.g., m = READ_PGM_IMAGE_FILE("pgm_files/yuv_1.pgm") & %i.(i:1..550| m(i) /|\ 725))
1815 try_quick_delete_exact_member(List,El,Result) :-
1816 try_quick_delete_exact_member(List,1,El,Result).
1817 try_quick_delete_exact_member(V,_,_,_) :- var(V),!,fail.
1818 try_quick_delete_exact_member([H|T],Sz,El,Res) :-
1819 (H==El -> Res=T
1820 ; Res=[H|TR],
1821 (Sz>50
1822 -> ground_value(H), % after a certain limit we only proceed if there are ground elements
1823 % we could also check: preferences:preference(use_smt_mode,true)
1824 Sz1=30 % check again in 20 steps
1825 ; Sz1 is Sz+1),
1826 try_quick_delete_exact_member(T,Sz1,El,TR)).
1827
1828
1829 %unbound_variable(V) :- !, unbound_variable_check(V).
1830 unbound_variable(V) :- free_var(V), frozen(V,Residue),
1831 %unbound_residue(Residue,V).
1832 (unbound_residue(Residue,V) -> true ; %print(bound_var(V,Residue)),nl,trace,unbound_residue(Residue,V),
1833 fail).
1834 unbound_residue((A,B),V) :- !,unbound_residue(A,V), unbound_residue(B,V).
1835 unbound_residue(true,_) :- !.
1836 unbound_residue(Module:Call,Variable) :- unbound_residue_m(Module,Call,Variable).
1837
1838 unbound_residue_m(external_functions,to_string_aux(GrV,_Val,Str),V) :- !, %GrV checks for groundness of _Val
1839 V==GrV,unbound_variable(Str).
1840 unbound_residue_m(external_functions,format_to_string_aux(GrV,_Format,_Val,Str),V) :- !,
1841 %GrV checks for groundness of _Val
1842 V==GrV,unbound_variable(Str).
1843 % TO DO: we need to detect other functions (e.g., B function application,...) which result in values which are not used
1844 %unbound_residue_m(_,ground_value_check(V1,V2),V) :- !, V1==V, unbound_variable(V2). % V1==V not necessary?! cycle check
1845 unbound_residue_m(Module,Residue,Var) :- unbound_basic_residue(Module,Residue,Var).
1846
1847 %unbound_basic_residue(_,true,_).
1848 unbound_basic_residue(_,ground_value_check(V1,V2),Var) :- !, Var==V1, % == check to prevent loops
1849 % in particularly in SWI, where residues also contain calls where Var==V2; e.g., test 639
1850 unbound_variable(V2).
1851 unbound_basic_residue(_,ground_value_check_aux(V1,V2,V3),Var) :- !, (Var==V1 -> true ; Var==V2), unbound_variable(V3).
1852 % we could also treat ground_value_opt_check
1853 unbound_basic_residue(b_interpreter_components,observe_variable_block(_,_,_,_,_),_). % when in -p TRACE_INFO TRUE mode
1854 unbound_basic_residue(b_interpreter_components,observe_variable1_block(_,_,_,_),_). % (provide_trace_information pref)
1855 unbound_basic_residue(kernel_objects,mark_as_to_be_computed(_),_).
1856 unbound_basic_residue(custom_explicit_sets,block_copy_waitflag_store(_,_,_,_,_),_). % this stems from checking the domain predicate of function application check_element_of_function_closure
1857 %unbound_basic_residue(kernel_objects,ordered_value(V,_),_). % <-- TO DO: treat this and then assign minimal value !
1858 %unbound_basic_residue(kernel_ordering,ordered_value2(V,_),_).
1859 % b_tighter_enumerate_sorted_value_and_continue
1860 %unbound_basic_residue(M,U,Var) :- print(bound_basic_residue(M,U,Var)),nl,fail.
1861
1862 % check if we have an unbound list_skeleton with optionally just ordering constraints
1863 % check if it is safe to assign H minimal value
1864 % TO DO: also accept if all elements have the same co-routines constraints attached (e.g., because of +-> check)
1865 is_unbound_ordered_list_skeleton(H,T) :-
1866 is_unbound_ordered_list_skeleton3(H,T,[allow_ordered_values]).
1867 is_unbound_list_skeleton(H,T) :-
1868 ? is_unbound_ordered_list_skeleton3(H,T,[]).
1869
1870 is_unbound_ordered_list_skeleton(H,T,Ordered) :-
1871 ? is_unbound_ordered_list_skeleton3(H,T,List),
1872 % if List gets instantiated it will become [allow_ordered_values|_]
1873 (var(List) -> Ordered=unordered ; Ordered=ordered).
1874
1875 is_unbound_ordered_list_skeleton3(H,T,Options) :-
1876 free_var(H),
1877 (var(T) -> unbound_variable(H),
1878 ? unbound_ordered_tail(T,Options) % or ? unbound_variable_for_cons(T)
1879 ; T = [H2|T2],
1880 unbound_variable_or_ordered(H,'$$',H2,T,Options),
1881 is_unbound_ordered_list_skeleton5(H,H2,T2,[H|T],Options)).
1882 is_unbound_ordered_list_skeleton5(Prev,H,T,All,Options) :-
1883 free_var(H),
1884 (var(T) -> unbound_variable_or_ordered(H,Prev,'$$',All,Options),
1885 unbound_ordered_tail(T,Options)
1886 ; T==[] -> unbound_variable_or_ordered(H,Prev,'$$',All,Options)
1887 ; T = [H2|T2],
1888 unbound_variable_or_ordered(H,Prev,H2,All,Options),
1889 is_unbound_ordered_list_skeleton5(H,H2,T2,All,Options)).
1890
1891 % utility: if is_unbound_ordered_list_skeleton is true, extract for every element in the list one minimal element from CS
1892 remove_minimal_elements(T,CS,Res) :- var(T),!,Res=CS.
1893 remove_minimal_elements([],CS,Res) :- !, empty_set(CS),Res=[].
1894 remove_minimal_elements([_H|T],CS,[Min|Rest]) :-
1895 remove_minimum_element_custom_set(CS,Min,NewCS), % _H will be unified in one go with Min later
1896 remove_minimal_elements(T,NewCS,Rest).
1897
1898 % it is unbound or can be assigned the minimal value of a set
1899 unbound_variable_or_ordered(Var,Prev,Nxt,All,Options) :-
1900 free_var(Var), frozen(Var,Residue),
1901 unbound_ord_residue_aux(Residue,Prev,Var,Nxt,All,Options).
1902 unbound_ord_residue_aux(true,_Prev,_,_Nxt,_All,_Options).
1903 unbound_ord_residue_aux((A,B),Prev,V,Nxt,All,Options) :- !,
1904 unbound_ord_residue_aux(A,Prev,V,Nxt,All,Options),
1905 unbound_ord_residue_aux(B,Prev,V,Nxt,All,Options).
1906 unbound_ord_residue_aux(Module:Call,Prev,V,Nxt,All,Options) :-
1907 unbound_ord_residue_m(Module,Call,Prev,V,Nxt,All,Options).
1908 unbound_ord_residue_m(Module,Residue,_,Var,_,_,_) :- unbound_basic_residue(Module,Residue,Var),!.
1909 unbound_ord_residue_m(kernel_relations,check_index(V2,_),_,V,_,_,_) :- !,
1910 V2==V. % assumes all index elements in the sequence are being checked; this is the case
1911 unbound_ord_residue_m(kernel_objects,ordered_value(A,B),Prev,V,Nxt,_,Options) :- !,
1912 % there is also a kernel_relations version
1913 ((A,B)==(Prev,V) ; (A,B)==(V,Nxt)),
1914 (member(allow_ordered_values,Options) -> true).
1915 unbound_ord_residue_m(kernel_objects,not_equal_object_wf(A,B,_),_,V,_,All,_) :- !,
1916 % check for all diff constraint; e.g., set up by not_element_of_wf(H,SoFar,WF) in cardinality_as_int2;
1917 % anyway: all elements in a list must be different
1918 (A==V -> exact_member_in_skel(B,All) ; B==V, exact_member_in_skel(A,All)).
1919 unbound_ord_residue_m(kernel_objects,not_element_of_wf1(Set,Val,_),_,V,_,All,_) :- !, Val==V,
1920 open_tail(All,Tail), Tail==Set. % ditto, again just stating that Values are distinct in the list
1921 %unbound_ord_residue_m(A,Prev,V,Nxt,All) :-
1922 % print(unbound_ord_residue_aux(A,Prev,V,Nxt,All)),nl,fail.
1923
1924 % get tail of an open list:
1925 open_tail(X,Res) :- var(X),!,Res=X.
1926 open_tail([_|T],Res) :- open_tail(T,Res).
1927 % exact member in a possibly open list:
1928 exact_member_in_skel(X,List) :- nonvar(List), List=[Y|T],
1929 (X==Y -> true ; exact_member_in_skel(X,T)).
1930
1931
1932 unbound_ordered_tail(T,Options) :- free_var(T), frozen(T,Residue),
1933 ? unbound_ordered_tail_aux(Residue,T,Options).
1934 unbound_ordered_tail_aux(true,_,_).
1935 unbound_ordered_tail_aux(kernel_objects:propagate_card(A,B,_Eq),V,_) :-
1936 (V==A ; V==B). % just specifies A and B have same cardinality
1937 unbound_ordered_tail_aux(prolog:dif(X,Y),V,_) :- (V==X,Y==[] ; V==Y,X==[]).
1938 unbound_ordered_tail_aux(dif(X,Y),V,_) :- (V==X,Y==[] ; V==Y,X==[]).
1939 unbound_ordered_tail_aux(kernel_objects:lazy_ordered_value(W,_),T,Options) :-
1940 W==T, %% difference with just_cardinality_constraints
1941 (member(allow_ordered_values,Options)->true).
1942 unbound_ordered_tail_aux(kernel_relations:propagate_empty_set(_,_),_,_).
1943 unbound_ordered_tail_aux(kernel_objects:prop_non_empty(_,W,_),T,_) :- W==T.
1944 unbound_ordered_tail_aux(kernel_objects:cardinality_as_int2(W,_,_,_,_,_),T,_) :- W==T.
1945 unbound_ordered_tail_aux(kernel_objects:cardinality3(W,_,_),Var,_) :- W==Var.
1946 unbound_ordered_tail_aux((A,B),T,Options) :-
1947 ? (unbound_ordered_tail_aux(A,T,Options) -> true ; unbound_ordered_tail_aux(B,T,Options)).
1948 % TODO: call unbound_basic_residue
1949
1950 % co-routine used to mark certain values as to be computed; avoid instantiating them
1951 :- block mark_as_to_be_computed(-).
1952 mark_as_to_be_computed(_).
1953
1954 is_marked_to_be_computed(X) :- var(X),frozen(X,G), %nl,print(check_frozen(X,G)),nl,
1955 marked_aux(G,X).
1956 marked_aux((A,B),V) :- (marked_aux(A,V) -> true ; marked_aux(B,V)).
1957 marked_aux(kernel_objects:mark_as_to_be_computed(M),V) :- V==M.
1958
1959 :- public unbound_variable_check/1.
1960 % currently not used; but can be useful for debugging
1961 unbound_variable_check(V) :- free_var(V), % check no bool_pred attributes
1962 (frozen(V,Goal), Goal\=true
1963 -> nl,print('### WARNING: goal attached to unbound variable expression'),nl,print(V:Goal),nl, %trace,
1964 fail
1965 ; true).
1966
1967 % check if a variable is unbound or only dif(_,[]) attached; we do not need to check for bool_pred attributes as we have a set
1968 unbound_variable_for_cons(Set) :- var(Set),frozen(Set,F),
1969 \+ contains_problematic_coroutine_for_cons(F,Set). % for equal cons we can allow more co-routines than when we want to freely determine a value in enumeration; the head of the list is unbound
1970
1971 % prolog:dif(X,Y) with Y == [] is ok
1972 contains_problematic_coroutine_for_cons(custom_explicit_sets:element_of_avl_set_wf3(Var,_,_,_,_),V) :- V==Var. % occurs in test 1270
1973 contains_problematic_coroutine_for_cons(kernel_objects:non_free(_),_). % has been marked as non-free
1974 contains_problematic_coroutine_for_cons(kernel_objects:mark_as_to_be_computed(_),_). % has been marked to be computed by closure expansion
1975 % contains_problematic_coroutine_for_cons(kernel_relations:range_wf(_,Var,_),V) :- V==Var. % will be computed by range, range does not propagate well backwards (does it?)
1976 % contains_problematic_coroutine_for_cons(custom_explicit_sets:expand_custom_set_to_list3(_From,Var,_Done,_Source,_WF),V) :- V==Var. % this can propagate backwards
1977 contains_problematic_coroutine_for_cons((A,B),Var) :-
1978 ? (contains_problematic_coroutine_for_cons(A,Var) -> true
1979 ; contains_problematic_coroutine_for_cons(B,Var)).
1980 %contains_problematic_coroutine_for_cons(M:Call,Var) :-
1981 % functor(Call,F,N), format('~w:~w/~w for ~w~n',[M,F,N,Var]),fail.
1982
1983 unbound_variable_for_card(Set) :- % when do we allow card to instantiate a list skeleton
1984 preference(data_validation_mode,true),
1985 !,
1986 unbound_variable(Set).
1987 unbound_variable_for_card(Set) :- unbound_variable_for_cons(Set).
1988
1989
1990
1991 % handling equal_object for [HR|TR] = [H|T]
1992
1993 equal_cons_cons(HR,TR,H,T,_LWF,WF) :- TR==[],!,
1994 ? empty_set_wf(T,WF), % was T=[], but T could be an empty closure
1995 ? equal_object_wf(HR,H,equal_cons_cons_1,WF).
1996 equal_cons_cons(HR,TR,H,T,_LWF,WF) :- T==[],!,
1997 ? empty_set_wf(TR,WF), % was TR=[], but TR could be an empty closure
1998 ? equal_object_wf(HR,H,equal_cons_cons_2,WF).
1999 equal_cons_cons(HR,TR,H,T,_LWF,WF) :-
2000 %(is_unbound_list_skeleton(H,T) -> true ; is_unbound_list_skeleton(HR,TR)),
2001 ? (is_unbound_ordered_list_skeleton(H,T,Ordered)
2002 -> (Ordered = unordered -> true
2003 ; is_unbound_ordered_list_skeleton(HR,TR))
2004 ? ; is_unbound_list_skeleton(HR,TR)),
2005 % if both are ordered: then the first elements must be equal,
2006 % if one or both are not ordered: the unification HR=H is only ok if the other is unbound
2007 % beware of tests 1078 and 1101 when allowing ordered lists
2008 !,
2009 % HR is variable: no constraints/co-routines attached to it; no other element in TR is constrained either
2010 %(HR,TR)=(H,T). %fails, e.g., if TR=[] and T= empty closure !
2011 % at the moment : unbound_check does not allow ordered set skeletons
2012 HR=H, equal_object_wf(TR,T,equal_cons_cons3,WF).
2013 equal_cons_cons(HR,TR,H,T,LWF,WF) :-
2014 % here we use LWF for the first time
2015 %(number(LWF) -> LWF2=LWF ; true),
2016 equality_objects_lwf(HR,H,EqRes,LWF2,WF),
2017 ? equal_cons1(EqRes,HR,TR,H,T,LWF,LWF2,WF).
2018
2019 equal_cons1(EqRes,_HR,TR,_H,T,_LWF,_LWF2,WF) :- EqRes == pred_true,!,
2020 ? equal_object_wf(TR,T,equal_cons1,WF).
2021 equal_cons1(EqRes,HR,TR,H,T,_LWF,_LWF2,WF) :- var(EqRes),
2022 (definitely_not_in_list(TR,H)
2023 ; definitely_not_in_list(T,HR) % this can induce a quadratic complexity for large list skeletons
2024 ),
2025 !,
2026 EqRes=pred_true, % H cannot appear in TR; it must match HR
2027 ? equal_object_wf(TR,T,equal_cons1,WF).
2028 equal_cons1(EqRes,HR,TR,H,T,LWF,LWF2,WF) :-
2029 ? instantiate_lwf(LWF,LWF2), % instantiate later to ensure var(EqRes) can hold if LWF already bound
2030 %print(eq_cons_cons_lwf2(HR,H,EqRes,LWF2)),nl,
2031 ? equal_cons2(EqRes,HR,TR,H,T,LWF2,WF),
2032 propagate_card(TR,T,EqRes). % prevents tail recursion; move earlier/remove if EqRes nonvar?
2033 %,instantiate_lwf(LWF,LWF2) % we could instantiate LWF2 later here to give propagate_card a chance to figure out value of EqRes first ? this slows down examples/B/Alstom/CompilatonProject/Regles/Rule_DB_Route_0001ori.his
2034
2035
2036 % this will instantiate LWF if it has not yet been computed
2037 % (Idea: get_cardinality_wait_flag can be expensive; only do it if we really need the wait_flag)
2038 instantiate_lwf(LWF,R) :- var(LWF),!,R=LWF.
2039 instantiate_lwf(lwf_card(Set,Info,WF),LWF) :- !, % TO DO: in prob_data_validation_mode: increase or get_last_wait_flag
2040 ? get_cardinality_wait_flag(Set,Info,WF,LWF).
2041 %% get_cardinality_powset_wait_flag(Set,Info,WF,_,LWF).
2042 %instantiate_lwf(lwf_first(X),R) :- !, R=X.
2043 instantiate_lwf(LWF,LWF).
2044
2045 :- block equal_cons2(-,?,?,?,?,?,?).
2046 ?equal_cons2(pred_true,_HR,TR,_H,T,_,WF) :- equal_object_wf(TR,T,equal_cons2,WF).
2047 equal_cons2(pred_false,HR,TR, H,T,LWF,WF) :-
2048 ? equal_cons_lwf(T,HR,TR2,LWF,WF), % look for HR inside T
2049 T2=TR2,
2050 ? equal_cons_lwf(TR,H,T2,LWF,WF). %, was instead of T2=TR2: equal_object(TR2,T2).
2051
2052 :- use_module(kernel_tools,[cannot_match/2]).
2053 % TO DO: investigate whether we should not use kernel_equality or at least a blocking version
2054 definitely_not_in_list(V,_) :- var(V),!,fail.
2055 definitely_not_in_list([],_).
2056 definitely_not_in_list([H|T],X) :- cannot_match(H,X), definitely_not_in_list(T,X).
2057
2058
2059 :- block propagate_card(-,-,-).
2060 propagate_card(X,Y,EqRes) :-
2061 (nonvar(EqRes) -> true % we no longer need to propagate; equal_cons will traverse
2062 ; nonvar(X) -> propagate_card2(X,Y,EqRes)
2063 ; propagate_card2(Y,X,EqRes)).
2064 propagate_card2([],Y,_) :- !,empty_set(Y).
2065 propagate_card2([_|TX],Y,EqRes) :- !,
2066 (var(Y) -> Y= [_|TY], propagate_card(TX,TY,EqRes)
2067 ; Y=[] -> fail
2068 ; Y=[_|TY] -> propagate_card(TX,TY,EqRes)
2069 ; true
2070 ). % TO DO: add more propagation
2071 propagate_card2(_,_,_).
2072
2073 %same_card_and_expand(A,B,ExpA,ExpB) :- .... + reorder ??
2074
2075
2076 % CODE FOR CHECKING FOR TYPE ERRORS AT RUNTIME
2077
2078 % explicitly check for type errors between two terms
2079 % can be useful for some external functions were users provide predicates/values at runtime
2080 % should be called before attempting e.g., equal_object
2081 check_values_have_same_type(TermA,TermB,_Pos) :- (var(TermA) ; var(TermB)),!.
2082 check_values_have_same_type((A1,A2),(B1,B2),Pos) :- !,
2083 check_values_have_same_type(A1,B1,Pos),
2084 check_values_have_same_type(A2,B2,Pos).
2085 % TODO: better checking for fields
2086 check_values_have_same_type(TermA,TermB,Pos) :- type_error(TermA,TermB),!,
2087 add_error(kernel_objects,'Type error, values are incompatible:',(TermA,TermB),Pos).
2088 check_values_have_same_type(_,_,_).
2089
2090 % the following is used by some kernel predicates if(environ(prob_safe_mode,true)).
2091 :- assert_must_succeed(type_error([],int(1))).
2092 :- assert_must_succeed(type_error((int(1),int(2)),[pred_true])).
2093 :- assert_must_succeed(type_error(string('Name'),global_set('Name'))).
2094 :- assert_must_fail((type_error([],[_]))).
2095 type_error(pred_true,Y) :- \+ bool_val(Y).
2096 type_error(pred_false,Y) :- \+ bool_val(Y).
2097 type_error([],Y) :- no_set_type_error(Y).
2098 type_error([_|_],Y) :- no_set_type_error(Y).
2099 %type_error(X,Y) :- is_custom_explicit_set(X,type_error1), no_set_type_error(Y).
2100 type_error(avl_set(A),Y) :- illegal_avl_set(A) -> true ; no_set_type_error(Y).
2101 type_error(global_set(_),Y) :- no_set_type_error(Y).
2102 type_error(freetype(_),Y) :- no_set_type_error(Y).
2103 type_error(closure(P,_,B),Y) :-
2104 (var(P) -> true ; var(B) -> true ; P=[] -> true ; P=[P1|_], var(P1) -> true ; no_set_type_error(Y)).
2105 type_error((_,_),Y) :- Y \= (_,_).
2106 type_error(fd(_,T1),Y) :- (Y= fd(_,T2) -> nonvar(T1),nonvar(T2),T1 \=T2 ; true).
2107 type_error(int(_),Y) :- Y\= int(_).
2108 type_error(term(_),Y) :- Y\= term(_).
2109 type_error(rec(FX),Y) :- (Y = rec(FY) -> type_error_fields(FX,FY,'$') ; true).
2110 type_error(freeval(ID,_,_),Y) :- Y \= freeval(ID,_,_).
2111 type_error(string(_),Y) :- Y \= string(_).
2112 % Should raise type error: kernel_objects:union([int(1)],[[]],R).
2113
2114 bool_val(pred_true).
2115 bool_val(pred_false).
2116
2117 type_error_fields(X,Y,_) :- (var(X);var(Y)),!,fail.
2118 type_error_fields([],[_|_],_).
2119 type_error_fields([_|_],[],_).
2120 type_error_fields([F1|T1],[F2|T2],PrevField) :-
2121 nonvar(F1),nonvar(F2),F1=field(Name1,_),F2=field(Name2,_),
2122 nonvar(Name1),
2123 (Name1 @=< PrevField -> true % not sorted
2124 ; Name1 \= Name2 -> true % other record has different field
2125 ; type_error_fields(T1,T2,Name1)).
2126
2127 :- public illegal_value/1.
2128 illegal_value(X) :- var(X),!,fail.
2129 illegal_value(avl_set(A)) :- illegal_avl_set(A).
2130 illegal_value([H|T]) :- illegal_value(H) -> true ; illegal_value(T).
2131 illegal_value(global_set(G)) :- \+ ground(G).
2132 illegal_value(N) :- number(N).
2133 illegal_value((A,B)) :- illegal_value(A) -> true ; illegal_value(B).
2134 % TO DO: complete this
2135
2136 illegal_avl_set(X) :- var(X),!.
2137 illegal_avl_set(empty).
2138 illegal_avl_set(X) :- (X=node(_,_,_,_,_) -> \+ ground(X) ; true).
2139
2140 no_set_type_error(int(_)).
2141 no_set_type_error(fd(_,_)).
2142 no_set_type_error((_,_)).
2143 no_set_type_error(rec(_)).
2144 no_set_type_error(pred_true /* bool_true */).
2145 no_set_type_error(pred_false /* bool_false */).
2146 no_set_type_error(term(_)).
2147 no_set_type_error(string(_)).
2148 no_set_type_error(freeval(_,_,_)).
2149 no_set_type_error(avl_set(A)) :- illegal_avl_set(A).
2150 %% END OF TYPE CHECKING CODE
2151
2152
2153 :- assert_must_succeed(not_equal_object(term(a),term(b))).
2154 :- assert_must_succeed(not_equal_object(string('a'),string('b'))).
2155 :- assert_must_succeed(not_equal_object(int(1),int(2))).
2156 :- assert_must_succeed(not_equal_object(rec([field(a,int(1))]),rec([field(a,int(2))]))).
2157 :- assert_must_succeed(not_equal_object(rec([field(a,int(1)),field(b,int(2))]),
2158 rec([field(a,int(1)),field(b,int(3))]))).
2159 :- assert_must_fail(not_equal_object(rec([field(a,int(1))]),rec([field(a,int(1))]))).
2160 :- assert_must_fail(not_equal_object(rec([field(a,int(1)),field(b,int(2))]),
2161 rec([field(a,int(1)),field(b,int(2))]))).
2162 :- assert_must_fail(not_equal_object(term(msg),int(2))).
2163 :- assert_must_fail(not_equal_object(fd(1,a),term(msg))).
2164 :- assert_must_succeed(not_equal_object(global_set(a),global_set(b))).
2165 :- assert_must_succeed(not_equal_object([term(a),term(b)],[term(a),term(c)])).
2166 :- assert_must_succeed((not_equal_object([(int(1),[Y])],[(int(X),[Z])]),
2167 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[int(2)])).
2168 :- assert_must_succeed(not_equal_object((int(1),int(2)),(int(3),int(4)))).
2169 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_equal_object((int(1),int(2)),(int(1),int(4))))).
2170 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_equal_object((int(1),int(4)),(int(3),int(4))))).
2171 :- assert_must_fail(not_equal_object((int(1),int(4)),(int(1),int(4)))).
2172 :- assert_must_succeed(not_equal_object((int(1),string('a')),(int(1),string('b')))).
2173 :- assert_must_fail(not_equal_object((int(1),string('b')),(int(1),string('b')))).
2174 :- assert_must_fail(not_equal_object([(term(a),[])],[(term(a),[])])).
2175 :- assert_must_fail((not_equal_object([(int(1),[Y])],[(int(X),[Z])]),
2176 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[])).
2177 :- assert_must_fail(not_equal_object([int(1),int(2)],[int(2),int(1)])).
2178 :- assert_must_succeed(not_equal_object(term(msg),term(another_msg))).
2179 :- assert_must_succeed(not_equal_object([int(1),int(2)],[int(0),int(4)])).
2180 :- assert_must_fail((sample_closure(C),
2181 not_equal_object(C,[int(1),int(2)]))).
2182 :- assert_must_succeed((sample_closure(C),
2183 not_equal_object(C,[int(1),int(0)]))).
2184 :- assert_must_succeed((sample_closure(C),
2185 not_equal_object(C,global_set('NAT')))).
2186 :- assert_must_fail((not_equal_object(
2187 [[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
2188 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(3,'Name'),fd(2,'Name')]]
2189 ,[[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
2190 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(2,'Name'),fd(3,'Name')]])
2191 )).
2192 :- assert_must_fail((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,a,int(2))))).
2193 :- assert_must_succeed((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,a,int(3))))).
2194 :- assert_must_succeed((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,b,int(2))))).
2195 :- assert_must_succeed((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,a,int(3))))).
2196
2197 :- assert_must_succeed((not_equal_object(pred_true /* bool_true */,X), X==pred_false /* bool_false */)).
2198 :- assert_must_succeed((not_equal_object([],X),X=[_|_])).
2199 %:- assert_must_succeed((not_equal_object([],X), nonvar(X),X=[_|_])).
2200 :- assert_must_succeed((not_equal_object(X,[]), X=[_|_])).
2201 :- assert_must_succeed((not_equal_object(X,pred_false /* bool_false */), X==pred_true /* bool_true */)).
2202
2203 :- assert_must_succeed(not_equal_object([_X],[int(1),int(3)])). % Inefficiency example of setlog
2204 :- assert_must_succeed_any(not_equal_object([_X],[int(1)])). % Inefficiency example of setlog
2205 :- assert_must_succeed((not_equal_object([X],[pred_true /* bool_true */]),X==pred_false /* bool_false */)).
2206 :- assert_must_succeed((not_equal_object([pred_true /* bool_true */],[X]),X==pred_false /* bool_false */)).
2207 :- assert_must_succeed((not_equal_object([[X]],[[pred_true /* bool_true */]]),X==pred_false /* bool_false */)).
2208 :- assert_must_succeed((not_equal_object([[pred_true /* bool_true */]],[[X]]),X==pred_false /* bool_false */)).
2209 :- assert_must_succeed((custom_explicit_sets:construct_one_element_custom_set(pred_true /* bool_true */, A), kernel_objects:not_equal_object(A,[X]), X==pred_false /* bool_false */)).
2210 :- assert_must_succeed((custom_explicit_sets:construct_one_element_custom_set(pred_true /* bool_true */,A), kernel_objects:not_equal_object([X],A), X==pred_false /* bool_false */)).
2211 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([],[int(3333)]))).
2212 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([],[int(2),int(1),int(3)]))).
2213 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([int(3)],[int(2),int(1),int(3)]))).
2214 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([int(3),int(1),int(4)],[int(2),int(1),int(3)]))).
2215 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([int(2),int(1),int(3),int(5)],[int(2),int(1),int(3)]))).
2216 % X in 3..4, kernel_objects:not_equal_object([int(2),int(3)],[int(2),int(X)]), X==4. in clpfd Mode
2217 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object(
2218 [(string(three),term(floating(3.0))),(string(one),term(floating(1.0))), (string(three),term(floating(1.0)))],
2219 [(string(three),term(floating(1.0))),(string(one),term(floating(3.0))), (string(three),term(floating(3.0)))]))).
2220
2221
2222 not_equal_object_wf(X,Y,WF) :-
2223 (var(X)
2224 -> (var(Y)
2225 -> X \== Y,
2226 when((nonvar(X);nonvar(Y);?=(X,Y)), not_equal_object_wf0(X,Y,WF))
2227 ? ; not_equal_object_wf1(Y,X,WF) % invert arguments
2228 )
2229 ? ; not_equal_object_wf1(X,Y,WF)).
2230
2231 %:- block not_equal_object_wf0(-,-,?).
2232 /* TO DO: implement a better _wf version ; use bool_dif if possible */
2233 % block is relevant for tests 1374, 1737
2234 not_equal_object_wf0(X,Y,WF) :-
2235 %(X==Y -> print(not_eq_pruned(X,Y)),nl,fail ; true),
2236 %X\==Y, % could be expensive if X,Y assigned to large term simultaneously (just woken up by when)
2237 ? (var(X) -> X\==Y, not_equal_object_wf1(Y,X,WF)
2238 ? ; not_equal_object_wf1(X,Y,WF)).
2239
2240 not_equal_object_wf1([],R,WF) :- !, not_empty_set_wf(R,WF).
2241 not_equal_object_wf1(R,E,WF) :- E==[],!, not_empty_set_wf(R,WF).
2242 ?not_equal_object_wf1(X,Y,WF) :- not_equal_object2_wf(X,Y,WF).
2243
2244 not_equal_object(X,Y) :-
2245 ? ( nonvar(X) -> not_equal_object2_wf(X,Y,no_wf_available)
2246 ; nonvar(Y) -> not_equal_object2_wf(Y,X,no_wf_available)
2247 ; X\==Y, when((?=(X,Y);nonvar(X);nonvar(Y)), not_equal_object0(X,Y))).
2248
2249 not_equal_object0(X,Y) :- X\==Y,(var(X) -> not_equal_object2_wf(Y,X,no_wf_available)
2250 ; not_equal_object2_wf(X,Y,no_wf_available)).
2251
2252 %not_equal_object2_wf(X,Y,_) :- print(not_equal_object2_wf(X,Y)),nl,fail.
2253 not_equal_object2_wf(pred_true /* bool_true */,R,_) :- !, R=pred_false /* bool_false */.
2254 not_equal_object2_wf(pred_false /* bool_false */,R,_) :- !, R=pred_true /* bool_true */.
2255 not_equal_object2_wf(fd(X,Type),R,_) :- !, get_global_type_value(R,Type,Y), % also sets up FD range for Y if R was var
2256 ? neq_fd(X,Y,Type).
2257 ?not_equal_object2_wf(int(X),R,_WF) :- !, R=int(Y), integer_dif(X,Y).
2258 not_equal_object2_wf(string(X),R,_) :- !, R=string(Y), dif(X,Y).
2259 not_equal_object2_wf(term(X),R,WF) :- !, R=term(Y), not_equal_term_wf(X,Y,WF).
2260 not_equal_object2_wf(rec(F1),R,WF) :- !, R=rec(F2),
2261 not_equal_fields_wf(F1,F2,WF).
2262 not_equal_object2_wf([],X,WF) :- !, not_empty_set_wf(X,WF).
2263 not_equal_object2_wf((X1,X2),R,WF) :- !, R=(Y1,Y2),
2264 ? not_equal_couple_wf(X1,Y1,X2,Y2,WF).
2265 not_equal_object2_wf(X,Y,WF) :- is_custom_explicit_set(X,not_equal_object2),!,
2266 ? not_equal_explicit_set_wf(X,Y,WF).
2267 ?not_equal_object2_wf(X,Y,WF) :- not_equal_object3(X,Y,WF).
2268
2269 :- block not_equal_term_wf(-,-,?).
2270 not_equal_term_wf(X,Y,_WF) :- % triggered e.g. in test 1225 or 1227 for nil (freetypes)
2271 dif(X,Y).
2272 % TO DO: should we treat floating/1 in a special way?
2273
2274 :- block not_equal_explicit_set_wf(?,-,?).
2275 not_equal_explicit_set_wf(X,Y,WF) :-
2276 is_custom_explicit_set_nonvar(Y),!,
2277 not_equal_explicit_sets_wf(X,Y,WF).
2278 not_equal_explicit_set_wf(X,[],WF) :- !,
2279 is_non_empty_explicit_set_wf(X,WF).
2280 not_equal_explicit_set_wf(CS,[H|T],WF) :-
2281 is_simple_infinite_set(CS), % global_set(.) or open interval
2282 !, % TODO: maybe also detect other infinite sets
2283 test_finite_set_wf(T,Finite,WF),
2284 when(nonvar(Finite),(Finite=pred_true -> true % infinite set cannot be equal finite one
2285 ; not_equal_explicit_set_expand(CS,[H|T],WF))).
2286 not_equal_explicit_set_wf(X,Y,WF) :-
2287 ? not_equal_explicit_set_expand(X,Y,WF).
2288
2289 not_equal_explicit_set_expand(X,Y,WF) :-
2290 expand_custom_set_wf(X,EX,not_equal_explicit_set_wf,WF),
2291 ? not_equal_object3_block(EX,Y,WF).
2292
2293 :- block not_equal_object3_block(-,?,?).
2294 ?not_equal_object3_block(EX,Y,WF) :- not_equal_object3(EX,Y,WF).
2295
2296 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
2297 :- block not_equal_object3(?,-,?).
2298 :- if(environ(prob_safe_mode,true)).
2299 not_equal_object3(X,Y,_) :- nonvar(X),type_error(X,Y),
2300 add_internal_error('Internal Typing Error (please report as bug !) : ',not_equal_object(X,Y)),
2301 fail.
2302 :- endif.
2303 not_equal_object3(X,Y,WF) :- is_custom_explicit_set(Y,not_equal_object2),!,
2304 ? not_equal_explicit_set_wf(Y,X,WF). % TODO: will uselessly check for X being custom_set or []
2305 not_equal_object3(freeval(ID,Case1,Value1),freeval(ID,Case2,Value2),WF) :-
2306 instantiate_freetype_case(ID,Case1,Case2),
2307 when(?=(Case1,Case2), % we first have to be able to decide the case; if cases are different types of values may be different
2308 not_equal_freeval_wf(Case1,Value1,Case2,Value2,WF)).
2309 not_equal_object3([],X,WF) :- not_empty_set_wf(X,WF).
2310 not_equal_object3([H|T],Set2,WF) :-
2311 (Set2==[] -> true % note second argument is nonvar
2312 ; cardinality_peano_wf([H|T],N1,no_wf_available),
2313 cardinality_peano_wf(Set2,N2,no_wf_available), % TODO(?): pending co-routines if Set2 infinite
2314 ? when(?=(N1,N2), % when we trigger code below, = can be decided:
2315 (N1=N2 -> neq_cons_wf(Set2,H,T,WF) ; true))).
2316 % (dif(N1,N2) ; (N1=N2, neq_cons_wf(Set2,H,T,WF)))). %not_equal_object_sets(Set1,Set2) )) ).
2317
2318 not_equal_freeval_wf(Case1,Value1,Case2,Value2,WF) :-
2319 ? (Case1=Case2 -> not_equal_object_wf(Value1,Value2,WF) ; true).
2320
2321 :- block not_equal_object_sets_wf(-,?,?), not_equal_object_sets_wf(?,-,?).
2322 not_equal_object_sets_wf([H|T],Set2,WF) :- !,
2323 ( Set2=[H2|_T2]
2324 ? -> not_equal_object_sets2(H,T,H2,Set2,WF)
2325 ; Set2=[] -> true
2326 ; not_equal_object2_wf(Set2,[H|T],WF) % avl_set probably
2327 ).
2328 not_equal_object_sets_wf(Set1,Set2,WF) :- % Note : if Set1 =[] then we can fail, as both sets have same length
2329 % we could have empty set or avl_set can sometimes creep into end of lists
2330 not_equal_object2_wf(Set1,Set2,WF).
2331
2332 :- block not_equal_object_sets2(-,?,?,?,?), not_equal_object_sets2(?,?,-,?,?).
2333 not_equal_object_sets2(H,_T,_H2,Set2,WF) :-
2334 % TO DO: should we not use kernel_equality:membership_test_wf here ??
2335 not_element_of_wf(H,Set2,WF).
2336 not_equal_object_sets2(H,T,_H2,Set2,WF) :-
2337 ? remove_element_wf(H,Set2,Del2,WF), % used to be remove_element(X,Set,Res) :- equal_cons(Set,X,Res).
2338 ? not_equal_object_wf(T,Del2,WF).
2339
2340
2341 :- block neq_cons_wf(-,?,?,?).
2342 neq_cons_wf([],_,_,_) :- !.
2343 neq_cons_wf([H2|T2],H1,T1,WF) :- !,
2344 (T2==[],T1==[]
2345 ? -> not_equal_object_wf(H1,H2,WF)
2346 ; check_and_remove([H2|T2],H1,NewSet2,RemoveSuccesful),
2347 ? neq_cons2(RemoveSuccesful,T1,NewSet2,WF)
2348 ).
2349 neq_cons_wf(avl_set(A),H1,T1,WF) :- element_can_be_added_or_removed_to_avl(H1),!,
2350 (remove_element_from_explicit_set(avl_set(A),H1,RA)
2351 -> not_equal_object_wf(T1,RA,WF)
2352 ; true ).
2353 neq_cons_wf(ES,H1,T1,WF) :- is_custom_explicit_set(ES,neq_cons),
2354 expand_custom_set_wf(ES,ExpSet,neq_cons_wf,WF),
2355 neq_cons_wf(ExpSet,H1,T1,WF).
2356
2357 :- block neq_cons2(-,?,?,?).
2358 neq_cons2(not_successful,_T1,_NewSet2,_WF). % one element could not be removed: the sets are different
2359 ?neq_cons2(successful,T1,NewSet2,WF) :- not_equal_object_sets_wf(T1,NewSet2,WF).
2360
2361 % kernel_objects:not_equal_couple(int(1),int(Y),B,pred_true).
2362 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(1),int(Y),B,pred_true,no_wf_available),Y=1, B==pred_false)).
2363 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),B,pred_true,no_wf_available),Y=1, B==pred_false)).
2364 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),B,pred_false,no_wf_available),Y=1, B==pred_true)).
2365 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),pred_false,B,no_wf_available),Y=1, B==pred_true)).
2366 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),B,pred_true,no_wf_available),Y=2, var(B))).
2367 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(B,pred_true,int(Y),int(1),no_wf_available),Y=1, B==pred_false)).
2368 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(B,fd(C,'Code'),fd(Y,'Name'),F,no_wf_available),F=fd(1,'Name'),Y=1,B=fd(1,'Code'),C=2 )).
2369 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(B,pred_true,fd(Y,'Name'),F,no_wf_available),F=fd(1,'Name'),Y=1, B==pred_false)).
2370
2371 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(2500),int(50),_,_,no_wf_available))).
2372 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(_,_,int(2500),int(50),no_wf_available))).
2373
2374
2375 %was too lax (but works): :- block not_equal_couple_wf(-,?,-,?,?),not_equal_couple_wf(?,-,?,-,?).
2376 % but not sure if this new declaration below is worth it, also since X1==Y1 or X2==Y2 is possible
2377 :- block not_equal_couple_wf(-,?,-,?,?), % X1 or X2 must be known
2378 not_equal_couple_wf(?,-,?,-,?), % Y1 or Y2 must be known
2379 not_equal_couple_wf(?,-,-,?,?), % X2 or Y1 must be known
2380 not_equal_couple_wf(-,?,?,-,?). % X1 or Y2 must be known
2381 % (X1,X2) /= (Y1,Y2)
2382
2383 % using CLPFD results in less propagation it seems
2384 % e.g. post_constraint((A1 #\= A2 #\/ B1 #\= B2), dif((A1,B1),(A2,B2))) will not propagate if A1=A2 or B1=B2
2385 % we could do something like
2386 % post_constraint((N*A1 + B1 #\= N*A2 + B2), dif((A1,B1),(A2,B2))). ; but we need to know good value for N
2387 % TO DO: pass typing information when available ?? or not needed because type info extracted ?
2388
2389 not_equal_couple_wf(X1,Y1,X2,Y2,WF) :- var(X1), var(Y1),!,
2390 (X1==Y1 -> not_equal_object_wf(X2,Y2,WF)
2391 ; not_equal_couple_wf_aux(X2,Y2,X1,Y1,WF)). % change order to test
2392 not_equal_couple_wf(X1,Y1,X2,Y2,WF) :-
2393 ? not_equal_couple_wf_aux(X1,Y1,X2,Y2,WF).
2394
2395 not_equal_couple_wf_aux(X1,Y1,X2,Y2,WF) :-
2396 ? equality_objects_wf(X1,Y1,EqRes1,WF),
2397 (var(EqRes1)
2398 -> equality_objects_wf(X2,Y2,EqRes2,WF),
2399 ? not_equal_couple4(EqRes1,X1,Y1,EqRes2,X2,Y2)
2400 ? ; EqRes1=pred_true -> not_equal_object_wf(X2,Y2,WF)
2401 ; true).
2402
2403 :- block not_equal_couple4(-,?,?,-,?,?).
2404 not_equal_couple4(EqRes1,X1,Y1,EqRes2,X2,Y2) :-
2405 (var(EqRes1)
2406 ? -> not_equal_couple5(EqRes2,X1,Y1,EqRes1)
2407 ? ; not_equal_couple5(EqRes1,X2,Y2,EqRes2)).
2408
2409 not_equal_couple5(pred_true,_X2,_Y2,EqResOther) :- EqResOther=pred_false.
2410 not_equal_couple5(pred_false,_,_,_).
2411
2412
2413 /* To do: provide special support for things like
2414 couple of fd's [done], list of fd's, set of fd's */
2415
2416 :- use_module(kernel_records,[check_field_name_compatibility/3]).
2417 :- block not_equal_fields_wf(-,-,?).
2418 not_equal_fields_wf([field(ID1,V1)|T1],[field(ID2,V2)|T2],WF) :-
2419 % should we wait for ID1 or ID2 to become nonvar?
2420 check_field_name_compatibility(ID1,ID2,not_equal_fields_wf),
2421 (T1==[]
2422 -> T2=[], not_equal_object_wf(V1,V2,WF)
2423 ; not_equal_couple_wf(V1,V2,rec(T1),rec(T2),WF) % would be slightly more efficient to have a custom version of not_equal_couple
2424 ).
2425
2426
2427 /* ------------------------------------------- */
2428 /* equality_objects/3 function */
2429 /* ------------------------------------------- */
2430
2431 %% :- ensure_loaded(kernel_equality).
2432
2433 % ----------------------------------------------------------
2434 % ----------------------------------------------------------
2435
2436
2437
2438 :- use_module(kernel_equality).
2439
2440 % ----------------------------------------------------------
2441 % ----------------------------------------------------------
2442
2443 /* ---------------> */
2444 /* This should probably be more systematically applied before every kernel call
2445 + expanded for other symbolic representations !! */
2446
2447
2448
2449 /* underlying assumption: if G is a global set: we get back the
2450 global_set tag immediately: no need to use when to wait;
2451 better: ensure that b_compute_expression always returns a nonvar term */
2452
2453 integer_global_set('NAT').
2454 integer_global_set('NATURAL').
2455 integer_global_set('NAT1').
2456 integer_global_set('NATURAL1').
2457 integer_global_set('INT').
2458 integer_global_set('INTEGER').
2459
2460 string_global_set('STRING'). % TODO : check what happens when we have STRING in Event-B as a set
2461 real_global_set('REAL'). % TODO: ditto
2462 real_global_set('FLOAT'). % TODO: ditto
2463
2464
2465 :- assert_must_succeed(( kernel_objects:element_of_global_set(int(0),'NATURAL'))).
2466 :- assert_must_fail(( kernel_objects:element_of_global_set(int(0),'NATURAL1'))).
2467 :- assert_must_fail(( kernel_objects:element_of_global_set(int(-1),'NATURAL'))).
2468 :- assert_must_succeed(( kernel_objects:element_of_global_set(int(-1),'INTEGER'))).
2469 :- assert_must_succeed(( kernel_objects:element_of_global_set(int(0),'NAT'))).
2470 :- assert_must_fail(( kernel_objects:element_of_global_set(int(0),'NAT1'))).
2471 :- assert_must_succeed(( kernel_objects:element_of_global_set(X,'NAT'),X=int(1))).
2472 :- assert_must_succeed(( kernel_objects:element_of_global_set(X,'NATURAL'),X=int(1))).
2473
2474 element_of_global_set(X,GS) :-
2475 ? init_wait_flags(WF),element_of_global_set_wf(X,GS,WF),ground_wait_flags(WF).
2476
2477 element_of_global_set_wf(El,Set,WF) :- element_of_global_set_wf(El,Set,WF,unknown).
2478
2479 :- use_module(kernel_reals,[is_real/1, is_float_wf/2, is_not_float/1]).
2480 :- block element_of_global_set_wf(?,-,?,?).
2481 ?element_of_global_set_wf(El,Set,WF,_) :- b_global_set(Set),!,
2482 global_type_wf(El,Set,WF).
2483 element_of_global_set_wf(X,'STRING',_WF,_) :- !, X=string(_).
2484 element_of_global_set_wf(X,'REAL',_WF,_) :- !, is_real(X).
2485 element_of_global_set_wf(X,'FLOAT',WF,_) :- !, is_float_wf(X,WF).
2486 element_of_global_set_wf(int(X),GS,WF,Span) :-
2487 element_of_global_integer_set_wf(GS,X,WF,Span).
2488
2489 /* what about BOOL ?? */
2490 element_of_global_integer_set_wf('NAT',X,WF,_) :-
2491 preferences:get_preference(maxint,MAXINT),
2492 in_nat_range_wf(int(X),int(0),int(MAXINT),WF).
2493 element_of_global_integer_set_wf('NATURAL',X,WF,Span) :-
2494 (ground(X) -> X>=0
2495 ; is_natural(int(X),WF),
2496 %get_last_wait_flag(element_of_global_set(int(X),'NATURAL'),WF,LWF),
2497 get_integer_enumeration_wait_flag(X,'NATURAL',WF,LWF),
2498 enumerate_natural(X,0,LWF,Span,WF)
2499 ).
2500 element_of_global_integer_set_wf('NAT1',X,WF,_) :-
2501 preferences:get_preference(maxint,MAXINT),
2502 in_nat_range_wf(int(X),int(1),int(MAXINT),WF).
2503 element_of_global_integer_set_wf('NATURAL1',X,WF,Span) :-
2504 (ground(X) -> X>=1
2505 ; is_natural1(int(X),WF),
2506 %get_last_wait_flag(element_of_global_set_wf(int(X),'NATURAL1'),WF,LWF),
2507 get_integer_enumeration_wait_flag(X,'NATURAL1',WF,LWF),
2508 enumerate_natural(X,1,LWF,Span,WF)
2509 ).
2510 element_of_global_integer_set_wf('INT',X,WF,_) :-
2511 preferences:get_preference(minint,MININT),
2512 preferences:get_preference(maxint,MAXINT),
2513 in_nat_range_wf(int(X),int(MININT),int(MAXINT),WF).
2514 element_of_global_integer_set_wf('INTEGER',X,WF,Span) :-
2515 (ground(X) -> true
2516 ; get_integer_enumeration_wait_flag(X,'INTEGER',WF,LWF),
2517 enumerate_int_wf(X,LWF,'INTEGER',WF,Span)
2518 ).
2519
2520
2521 get_integer_enumeration_wait_flag(X,SET,WF,LWF) :-
2522 clpfd_domain(X,FDLow,FDUp), finite_domain(FDLow,FDUp),!,
2523 Size is 1+FDUp-FDLow,
2524 get_wait_flag(Size,element_of_global_set_wf(int(X),SET),WF,LWF).
2525 get_integer_enumeration_wait_flag(X,SET,WF,LWF) :-
2526 get_integer_enumeration_wait_flag(element_of_global_set_wf(int(X),SET),WF,LWF).
2527 % important for e.g., solving r = /*@symbolic*/ {u|#x.(x : NATURAL & u : {x |-> x * x,x |-> x + x})} & 10|->20 : r
2528 % see test 1933, the code was: get_enumeration_starting_wait_flag(element_of_global_set_wf(int(X),SET),WF,LWF), which is a lower number
2529
2530 :- assert_must_succeed((kernel_objects:enumerate_int_wf(X,4,self_check,no_wf_available,unknown),X==2)).
2531 :- block enumerate_int_wf(-,-,?,?,?).
2532 enumerate_int_wf(X,_LWF,Source,WF,Span) :-
2533 (ground(X) -> true
2534 ; add_call_stack_to_span(Span,WF,Span2), % TODO: necessary?
2535 ? enumerate_int_with_span(X,trigger_true(Source),Span2,WF)).
2536
2537 :- assert_must_succeed(not_element_of_global_set(int(-1),'NAT')).
2538 :- assert_must_succeed(not_element_of_global_set(int(-1),'NATURAL')).
2539 :- assert_must_succeed(not_element_of_global_set(int(0),'NAT1')).
2540 :- assert_must_succeed(not_element_of_global_set(int(0),'NATURAL1')).
2541 not_element_of_global_set(_,GS) :- is_maximal_global_set(GS),!, fail. % covers REAL, STRING, INTEGER
2542 not_element_of_global_set(X,'FLOAT') :- !, is_not_float(X).
2543 not_element_of_global_set(int(X),GS) :-
2544 (var(GS) -> add_error(kernel_objects,var_not_element_of_global_set,(int(X),GS)) ; true),
2545 ? not_element_of_global_set2(GS,X).
2546 not_element_of_global_set2('NAT',X) :-
2547 preferences:get_preference(maxint,MAXINT),
2548 ? clpfd_not_in_non_empty_range(X,0,MAXINT). %when(nonvar(X), (X<0 ; X>MAXINT)).
2549 not_element_of_global_set2('NATURAL',X) :- is_not_natural(int(X)).
2550 not_element_of_global_set2('NAT1',X) :-
2551 preferences:get_preference(maxint,MAXINT),
2552 ? clpfd_not_in_non_empty_range(X,1,MAXINT). %when(nonvar(X),(X<1 ; X>MAXINT)).
2553 not_element_of_global_set2('NATURAL1',X) :- is_not_natural1(int(X)).
2554 not_element_of_global_set2('INT',X) :-
2555 preferences:get_preference(minint,MININT),
2556 preferences:get_preference(maxint,MAXINT),
2557 clpfd_not_in_non_empty_range(X,MININT,MAXINT). %when(nonvar(X), (X < MININT ; X > MAXINT)).
2558 %not_element_of_global_set(string(_X),'STRING') :- fail.
2559 %not_element_of_global_set(int(_X),'INTEGER') :- fail.
2560 %not_element_of_global_set(_El,Set) :- b_global_set(Set), fail.
2561
2562
2563
2564 /* ---- */
2565 /* SETS */
2566 /* ---- */
2567
2568 %:- block is_a_set(-).
2569 %is_a_set(X) :- is_a_set2(X).
2570 %is_a_set2([]) :- !.
2571 %is_a_set2([_|_]) :- !.
2572 %is_a_set2(X) :- is_custom_explicit_set(X,is_a_set2).
2573
2574
2575
2576
2577 :- assert_must_succeed(exhaustive_kernel_fail_check(empty_set([int(4),int(3)]))).
2578 :- assert_must_fail((empty_set([int(2),int(1)]))).
2579 :- assert_must_fail((empty_set([int(1)]))).
2580 :- assert_must_fail((empty_set([[]]))).
2581 :- assert_must_fail((empty_set(global_set('Name')))).
2582 :- assert_must_fail((empty_set(X),X=[int(1)])).
2583 :- assert_must_succeed((empty_set([]))).
2584 empty_set(X) :- (var(X) -> X=[]
2585 ; X=[] -> true
2586 % ; X=[_|_] -> fail
2587 ; is_custom_explicit_set_nonvar(X),is_empty_explicit_set(X)).
2588 empty_set_wf(X,WF) :- (var(X) -> X=[]
2589 ; X=[] -> true
2590 % ; X=[_|_] -> fail
2591 ; is_custom_explicit_set_nonvar(X),is_empty_explicit_set_wf(X,WF)).
2592
2593
2594 :- assert_must_succeed(exhaustive_kernel_check(not_empty_set([int(4),int(3)]))).
2595 :- assert_must_succeed((kernel_objects:not_empty_set([int(2),int(1)]))).
2596 :- assert_must_succeed((kernel_objects:not_empty_set([int(1)]))).
2597 :- assert_must_succeed((kernel_objects:not_empty_set([[]]))).
2598 :- assert_must_succeed((kernel_objects:not_empty_set(global_set('Name')))).
2599 :- assert_must_succeed((kernel_objects:not_empty_set_lwf(X,1),nonvar(X),X=[_|_])).
2600 :- assert_must_succeed((kernel_objects:not_empty_set_lwf([int(1)],_))).
2601 :- assert_must_fail((kernel_objects:not_empty_set([]))).
2602
2603 :- use_module(kernel_non_empty_attr,[mark_var_set_as_non_empty/1]).
2604
2605 not_empty_set_wf(S,WF) :- WF==no_wf_available,!, not_empty_set2(S,WF).
2606 not_empty_set_wf(S,WF) :- var(S), !,
2607 (preferences:preference(use_smt_mode,true) -> S=[_|_]
2608 % ; WF=no_wf_available -> not_empty_set(S)
2609 ; get_large_finite_wait_flag(not_empty_set_wf,WF,LWF),
2610 % print(not_empty(S)),nl, % TO DO: set kernel_cardinality attribute if variable
2611 mark_var_set_as_non_empty(S),
2612 not_empty_set_lwf(S,LWF)).
2613 not_empty_set_wf(closure(P,T,B),WF) :- !, is_non_empty_explicit_set_wf(closure(P,T,B),WF).
2614 not_empty_set_wf(S,WF) :- not_empty_set2(S,WF).
2615
2616 :- block not_empty_set_lwf(-,-).
2617 % the instantiation with a list skeleton can easily cause multiple solutions for the same
2618 % set to be found: hence we guard it by a wait flag
2619 not_empty_set_lwf(S,_LWF) :- var(S),!,
2620 S=[_|_].
2621 not_empty_set_lwf(S,_) :- not_empty_set(S).
2622
2623 not_empty_set(Set) :- not_empty_set2(Set,no_wf_available).
2624
2625 :- use_module(error_manager,[add_warning/2]).
2626 :- block not_empty_set2(-,?).
2627 %not_empty_set(S) :- var(S),!,S=[_|_].
2628 % not_empty_set(X) :- not_equal_object([],X).
2629 not_empty_set2([_|_],_).
2630 not_empty_set2(avl_set(A),_) :- (A==empty -> add_warning(not_empty_set,'Empty avl_set'),fail ; true).
2631 not_empty_set2(closure(P,T,B),WF) :- is_non_empty_explicit_set_wf(closure(P,T,B),WF). % TO DO: also use WF
2632 not_empty_set2(global_set(Type),_) :- b_non_empty_global_set(Type).
2633 not_empty_set2(freetype(ID),_) :- kernel_freetypes:is_non_empty_freetype(ID).
2634
2635 % there also exists: eq_empty_set , a reified version, i.e., test_empty_set
2636
2637
2638 :- assert_must_succeed((exact_element_of(int(1),[int(2),int(1)]))).
2639 :- assert_must_succeed((exact_element_of(int(1),[int(2),int(3),int(4),int(1)]))).
2640 :- assert_must_succeed((exact_element_of(int(4),[int(2),int(3),int(4),int(1)]))).
2641 :- assert_must_succeed((exact_element_of(int(1),[int(2),int(3)|T]), T=[int(4),int(1)])).
2642 :- assert_must_fail((exact_element_of(int(5),[int(2),int(3)|T]), T=[int(4),int(1)])).
2643 :- assert_must_succeed((exact_element_of(fd(1,'Name'),global_set('Name')))).
2644 :- assert_must_succeed((exact_element_of([int(2),int(1)],[[],[int(2),int(1)]]))).
2645 :- assert_must_fail((exact_element_of([int(1),int(2)],[[],[int(2),int(1)]]))).
2646 %:- assert_must_succeed((exact_element_of([(int(1),fd(2,'Name'))],
2647 % closure([zzzz],[set(couple(integer,global('Name')))], 'In'('ListExpression'(['Identifier'(zzzz)]),
2648 % 'Seq'(value([fd(1,'Name'),fd(2,'Name')]))))) )).
2649 %:- assert_must_succeed((exact_element_of(XX,
2650 % closure([zzzz],[set(couple(integer,global('Name')))], 'In'('ListExpression'(['Identifier'(zzzz)]),
2651 % 'Seq'(value([fd(1,'Name'),fd(2,'Name')]))))),
2652 % equal_object(XX,[(int(1),fd(1,'Name'))]) )).
2653 %:- assert_must_succeed((
2654 %exact_element_of(XX,closure([zzzz],[set(couple(integer,global('Name')))],
2655 % 'In'('ListExpression'(['Identifier'(zzzz)]),
2656 % 'Perm'(value([fd(1,'Name'),fd(2,'Name')]))))),
2657 % equal_object(XX,[(int(1),fd(2,'Name')),(int(2),fd(1,'Name'))]) )).
2658
2659 %:- assert_must_succeed(( exact_element_of(X,
2660 % closure([zzzz],[set(record([field(balance,integer),field(name,global('Code'))]))],
2661 % 'In'('ListExpression'(['Identifier'(zzzz)]),
2662 % 'PowerSet'(value(closure([zzzz],
2663 % [record([field(balance,integer),field(name,global('Code'))])],'In'('ListExpression'(['Identifier'(zzzz)]),
2664 % 'SetOfRecords'(value(cons_expr(field(balance,global_set('NAT')),
2665 % cons_expr(field(name,global_set('Code')),nil_expr))))))))))),
2666 % X=[rec([field(balance,int(0)),field(name,fd(2,'Code'))])] )).
2667 %:- assert_must_fail(( exact_element_of(X,
2668 % closure([zzzz],[set(record([field(balance,integer),field(name,global('Code'))]))],
2669 % 'In'('ListExpression'(['Identifier'(zzzz)]),
2670 % 'PowerSet'(value(closure([zzzz],
2671 % [record([field(balance,integer),field(name,global('Code'))])],'In'('ListExpression'(['Identifier'(zzzz)]),
2672 % 'SetOfRecords'(value(cons_expr(field(balance,global_set('NAT')),
2673 % cons_expr(field(name,global_set('Code')),nil_expr))))))))))),
2674 % X=[rec([field(balance,int(-1)),field(name,fd(2,'Code'))])] )).
2675
2676
2677 /* use this to compute elements */
2678 exact_element_of(X,Set) :-
2679 dif(Set,[]),
2680 ? exact_element_of2(Set,X).
2681 :- block exact_element_of2(-,?).
2682 exact_element_of2([H|_],H).
2683 ?exact_element_of2([_|T],E) :- exact_element_of3(T,E).
2684 exact_element_of2(X,E) :- is_custom_explicit_set_nonvar(X), check_element_of(E,X).
2685 :- block exact_element_of3(-,?).
2686 exact_element_of3([H|_],H).
2687 ?exact_element_of3([_|T],E) :- exact_element_of3(T,E).
2688
2689
2690 :- assert_must_succeed(exhaustive_kernel_check(check_element_of(int(1),[int(2),int(1)]))).
2691 :- assert_must_succeed(exhaustive_kernel_fail_check(check_element_of(int(3),[int(2),int(1)]))).
2692 :- assert_must_succeed(exhaustive_kernel_fail_check(check_element_of(int(1),[]))).
2693
2694 /* uses equal_object instead of unification */
2695 :- assert_must_succeed((check_element_of(X,
2696 [(int(1),(int(1),(int(1),int(1)))),(int(2),(int(1),(int(1),int(1)))),
2697 (int(1),(int(1),(int(1),int(2)))),(int(2),(int(1),(int(1),int(2))))]),
2698 equal_object(X, (int(2),(int(1),(int(1),int(2))))) )).
2699 :- assert_must_succeed((check_element_of(X,
2700 [ (((int(1),int(1)),int(1)),int(1)), (((int(1),int(1)),int(1)),int(2)),
2701 (((int(1),int(1)),int(1)),int(3)), (((int(1),int(1)),int(1)),int(4)),
2702 (((int(1),int(1)),int(2)),int(1)), (((int(1),int(1)),int(2)),int(2))
2703 ]), equal_object(X, (((int(1),int(1)),int(2)),int(1)))
2704 )).
2705 :- assert_must_succeed((check_element_of(fd(1,'Name'),global_set('Name')))).
2706 %:- assert_must_succeed_multiple(check_element_of(X,[[fd(1,'Name')],[]])).
2707 :- assert_must_succeed((check_element_of((int(1),int(2)),[(int(1),int(2))]))).
2708 :- assert_must_succeed((check_element_of((_X,_Y),[(fd(2,'Code'),fd(2,'Code'))]))).
2709 :- assert_must_succeed((init_wait_flags(WF),
2710 check_element_of_wf((X,Y),[(fd(2,'Code'),fd(2,'Code'))],WF),
2711 ground_det_wait_flag(WF), X= fd(2,'Code'), Y= fd(2,'Code'),
2712 kernel_waitflags:ground_wait_flags(WF) )).
2713 :- assert_must_succeed((init_wait_flags(WF),
2714 check_element_of_wf((Y,X),[(fd(2,'Code'),fd(2,'Code'))],WF),
2715 ground_det_wait_flag(WF), X= fd(2,'Code'), Y= fd(2,'Code'),
2716 kernel_waitflags:ground_wait_flags(WF) )).
2717 :- assert_must_succeed((check_element_of([int(1),int(2)],[[int(2),int(1)]]))).
2718
2719 :- assert_must_succeed((check_element_of([int(1),int(2)],[[],[int(2),int(1)]]))).
2720 :- assert_must_succeed((check_element_of(X,[[],[int(2),int(1)]]), X==[] )).
2721 :- assert_must_succeed((check_element_of_wf(X,[[],[int(2),int(1)]],_WF),
2722 equal_object(X,[int(1),int(2)]) )).
2723 :- assert_must_succeed((check_element_of_wf(XX,global_set('Name'),WF),kernel_waitflags:ground_wait_flags(WF), XX==fd(3,'Name') )).
2724 :- assert_must_fail(check_element_of([fd(2,'Name')],[[fd(1,'Name')],[]])).
2725 :- assert_must_fail((check_element_of([int(2)],[[],[int(2),int(1)]]))).
2726 :- assert_must_succeed((check_element_of(int(1),_X))).
2727 :- assert_must_succeed((check_element_of((int(2),_X),[(int(1),[(int(1),int(22))]),(int(2),[(int(1),int(55))])]))).
2728
2729 check_element_of(X,Set) :- init_wait_flags(WF,[check_element_of]),
2730 ? check_element_of_wf(X,Set,WF),
2731 ? ground_wait_flags(WF).
2732
2733 % new test: check_element_of(int(1),X).
2734 % new test: check_element_of(int(1),[int(2)|X]).
2735
2736 check_element_of_wf(X,Set,WF) :- %print(el_of(X,Set)),nl,
2737 dif(Set,[]),
2738 % TO do: mark Set as non-empty not_empty_set_wf from kernel_cardinality_attr
2739 ? check_element_of1(X,Set,WF).
2740
2741 %check_element_of1(X,Set,WF) :- var(X),var(Set),unbound_variable_check(Set),!,
2742 % Set=[_|_], check_element_of2(Set,X,WF).
2743 %:- block check_element_of1(-,-,?). %%
2744
2745
2746 %:- block check_element_of1(-,-,?). % leads to time-out in test 292 for {x,S,S2|x : S & S <: (1 .. 213) & S \/ {x} = S2 & x /: S2} and test 1976 in data_validation mode and CLPFD false
2747 check_element_of1(X,Set,WF) :-
2748 (unbound_variable_for_element_of(Set),
2749 preference(data_validation_mode,false) % TODO: this leads to failure of test 1976 with CLPFD FALSE
2750 % but avoids instantiating Sets to lists early on: can disturb enumeration and efficient computation/unification of large sets
2751 ? -> check_element_of_unbound_set(X,Set,WF)
2752 ? ; check_element_of2(Set,X,WF)
2753 ).
2754
2755 check_element_of_unbound_set(X,Set,_WF) :-
2756 mark_as_non_free(X,check_element_of_unbound_set),
2757 Set=[X|_]. % Note: X needs to be nonvar so that other code knows X is not free anymore
2758 % TO DO: normalise X ?
2759 % TO DO: do this using CHR/attributes rather than by instantiation
2760
2761
2762 unbound_variable_for_element_of(Set) :- unbound_variable_for_cons(Set).
2763
2764 % attach co-routine to mark a given term as not a real variable
2765 mark_as_non_free(X,_Info) :- var(X) -> non_free(X) ; true.
2766 mark_as_non_free(X) :- var(X) -> non_free(X) ; true.
2767 :- block non_free(-).
2768 non_free([H|T]) :- !, mark_as_non_free(H), mark_as_non_free(T).
2769 non_free((A,B)) :- !, mark_as_non_free(A), mark_as_non_free(B).
2770 non_free(rec(Fields)) :- !, mark_as_non_free_fields(Fields).
2771 non_free(_).
2772 :- block mark_as_non_free_fields(-).
2773 mark_as_non_free_fields([]).
2774 mark_as_non_free_fields([field(_,Val)|T]) :- mark_as_non_free(Val),mark_as_non_free_fields(T).
2775
2776 :- use_module(clpfd_lists,[lazy_fd_value_check/4]).
2777
2778 :- block check_element_of2(-,?,?).
2779 check_element_of2(CS,El,WF) :-
2780 ? is_custom_explicit_set_nonvar(CS),!, element_of_custom_set_wf(El,CS,WF).
2781 check_element_of2([],_,_) :- !,fail.
2782 %check_element_of2([H|T],El,WF) :- try_expand_and_convert_to_avl([H|T],AVL),AVL=avl_set(_),!, % much better support exists for AVL trees; should we enable this conversion ?? %nl,print(converted_list_to_AVL([H|T])),nl,nl,
2783 % element_of_custom_set_wf(El,AVL,WF).
2784 check_element_of2([H|T],E,WF) :- !, % print(check_element_of4w(E,H,T,WF)),nl,
2785 % try and transform E : Set into clpfd:element(_,FDVals,EFD) check:
2786 ? lazy_fd_value_check([H|T],E,WF,FullyChecked),
2787 %get_partial_set_priority([H|T],WF,LWF), %%
2788 %get_wait_flag(2,check_element_of2([H|T],E),WF,LWF), %%
2789 (FullyChecked==true,ground(E) -> true % no need to check
2790 ; get_cardinality_wait_flag([H|T],check_element_of2,WF,LWF),
2791 ? check_element_of4w(E,H,T,WF,LWF) % this call is somewhat redundant if FullyChecked=true; but otherwise in_fd_value_list will not enumerate on its own (e.g., self-checks for relation_over will fail)
2792 ).
2793 check_element_of2(freetype(Id),E,WF) :- !, is_a_freetype_wf(E,Id,WF).
2794 check_element_of2(term(Z),_E,_WF) :- Z==undefined,!,
2795 add_error_fail(check_element_of2,'Encountered uninitialised set variable', '').
2796 check_element_of2(Set,E,WF) :-
2797 add_internal_error('Illegal argument: ',check_element_of2(Set,E,WF)),fail.
2798
2799
2800 % call if you already have an explicit waitflag (LWF) setup for the cardinality of the set
2801 :- block check_element_of_wf_lwf(?,-,?,?).
2802 check_element_of_wf_lwf(El,CS,WF,_LWF) :-
2803 ? is_custom_explicit_set_nonvar(CS),!, element_of_custom_set_wf(El,CS,WF).
2804 ?check_element_of_wf_lwf(E,[H|T],WF,LWF) :- check_element_of4w(E,H,T,WF,LWF).
2805 check_element_of_wf_lwf(E,freetype(Id),WF,_) :- !, is_a_freetype_wf(E,Id,WF).
2806
2807 :- block check_element_of4w(-,?,-,?,-).
2808 % check_element_of4w(E,H,T,_WF,_LWF) :- print(check_element_of4w(E,H,T,_WF,_LWF)),nl,fail.
2809 ?check_element_of4w(E,H,T,_WF,_LWF) :- T==[],!,equal_object(E,H,check_element_of4w).
2810 check_element_of4w(E,H,_T,_WF,_LWF) :- E==H ,!. %,print(eq(E,H)),nl. % added by mal, 17.10 2007
2811 check_element_of4w(E,H,T,WF,LWF) :- T\==[],
2812 ? equality_objects_lwf(E,H,Res,LWF,WF),
2813 ? check_element_of4(Res,E,T,WF,LWF).
2814
2815 :- block check_element_of4(-,?,?,?,-).
2816 check_element_of4(pred_true,_E,_,_WF,_LWF).
2817 check_element_of4(pred_false,E,T,WF,LWF) :-
2818 ? (var(T) -> T = [E|_] ; check_element_of5(E,T,WF,LWF)).
2819
2820 :- block check_element_of5(?,-,?,?).
2821 check_element_of5(E,R,WF,LWF) :-
2822 get_next_element(R,H,T),
2823 ? check_element_of4w(E,H,T,WF,LWF).
2824
2825
2826
2827 :- assert_must_succeed(exhaustive_kernel_check(not_element_of(int(3),[int(2),int(1)]))).
2828 :- assert_must_succeed(exhaustive_kernel_check(not_element_of(int(3),[int(2),int(1),int(4)]))).
2829 :- assert_must_succeed(exhaustive_kernel_fail_check(not_element_of(int(1),[int(2),int(1)]))).
2830 :- assert_must_succeed((kernel_objects:not_element_of(int(3),[int(2),int(1)]))).
2831 :- assert_must_succeed((kernel_objects:not_element_of(fd(1,'Name'),[]))).
2832 :- assert_must_fail((kernel_objects:not_element_of(fd(1,'Name'),global_set('Name')))).
2833 :- assert_must_succeed((kernel_objects:not_element_of(X,[fd(1,'Name')]),X = fd(2,'Name'))).
2834 :- assert_must_fail((kernel_objects:not_element_of(X,[fd(1,'Name')]),X = fd(1,'Name'))).
2835 :- assert_must_succeed(kernel_objects:not_element_of(term(a),[])).
2836 :- assert_must_fail((kernel_objects:not_element_of(int(1),[int(2),int(1)]))).
2837 :- assert_must_succeed((kernel_objects:not_element_of([int(1),int(2)],
2838 [[int(1)],[int(0),int(4)],[int(0),int(3)],[int(0),int(1)],[int(0)],[]]))).
2839 :- assert_must_fail((kernel_objects:not_element_of(term(3),[int(2),int(1)]))).
2840
2841
2842 not_element_of(X,Set) :- init_wait_flags(WF,[not_element_of]),
2843 ? not_element_of_wf(X,Set,WF),
2844 ? ground_wait_flags(WF).
2845
2846 :- use_module(b_global_sets,[b_get_fd_type_bounds/3]).
2847 :- block not_element_of_wf(-,-,?).
2848 not_element_of_wf(_,Set,_) :- Set==[],!.
2849 not_element_of_wf(El,Set,WF) :- nonvar(El),El=fd(X,GS),b_get_fd_type_bounds(GS,N,N),!,
2850 % we have a global set with a single element; Set must be empty
2851 X=N,empty_set_wf(Set,WF).
2852 ?not_element_of_wf(El,Set,WF) :- not_element_of_wf1(Set,El,WF).
2853
2854 :- block not_element_of_wf1(-,?,?).
2855 not_element_of_wf1(X,E,WF) :- is_custom_explicit_set_nonvar(X),!,
2856 ? not_element_of_custom_set_wf(E,X,WF).
2857 not_element_of_wf1([],_E,_WF).
2858 not_element_of_wf1([H|T],E,WF) :-
2859 ? not_equal_object_wf(E,H,WF),
2860 ? not_element_of_wf1(T,E,WF).
2861
2862
2863 :- assert_must_succeed(exhaustive_kernel_check(add_element(int(3),[int(2),int(1)],[int(1),int(3),int(2)]))).
2864 :- assert_must_succeed(exhaustive_kernel_fail_check(add_element(int(2),[int(2),int(1)],[int(1),int(3),int(2)]))).
2865 :- assert_must_succeed(exhaustive_kernel_fail_check(add_element(int(4),[int(2),int(1)],[int(1),int(3),int(2)]))).
2866 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(2),int(1)],R),
2867 kernel_objects:equal_object(R,[int(1),int(2),int(3)]))).
2868 :- assert_must_succeed((kernel_objects:add_element([int(2)],[[int(2),int(1)],[]],R),
2869 kernel_objects:equal_object(R,[[],[int(1),int(2)],[int(2)]]))).
2870 :- assert_must_succeed((kernel_objects:add_element([int(1),int(2)],[[int(2),int(1)],[]],R),
2871 kernel_objects:equal_object(R,[[],[int(1),int(2)]]))).
2872 :- assert_must_succeed((kernel_objects:add_element(X,[int(2),int(1)],R),
2873 kernel_objects:equal_object(R,[int(1),int(2)]), X = int(1))).
2874 :- assert_must_succeed((kernel_objects:add_element([int(1),int(2)],
2875 [[int(1)],[int(0),int(4)],[int(0),int(3)],[int(0),int(1)],[int(0)],[]], _R))).
2876
2877 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(X),int(1)],R,D),
2878 var(D), X=3, R==[int(3),int(1)], D==done)).
2879
2880 :- assert_must_fail((kernel_objects:add_element(term(msg),[int(2),int(1)],_R))).
2881 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(2),int(X)],R),
2882 nonvar(R), R =[H|T], H==int(2), nonvar(T),T=[_HH|TT],var(TT),
2883 X=4, T==[int(4),int(3)])).
2884 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(2),int(X)],R),
2885 nonvar(R), R =[H|T], H==int(2), nonvar(T),T=[_HH|TT],var(TT),
2886 X=3, T==[int(3)])).
2887 :- assert_must_succeed((kernel_objects:add_element(int(3),X,[int(2),int(3)]),
2888 kernel_objects:equal_object(X,[int(2)]) )).
2889 :- assert_must_succeed((kernel_objects:add_element(int(3),X,[int(3)]),
2890 kernel_objects:equal_object(X,[]) )).
2891 :- assert_must_succeed((add_element(X,[int(1)],[int(1)]),X==int(1))).
2892 :- assert_must_succeed((add_element(X,[],[int(1)]),X==int(1))).
2893 % kernel_objects:add_element(E,[H],R,Done), H = int(X), E=int(Y), X in 1..10, Y in 11..20.
2894
2895
2896 add_element(E,Set,NewSet) :- add_element(E,Set,NewSet,_).
2897 add_element(Element,Set,NewSet,Done) :- add_element_wf(Element,Set,NewSet,Done,no_wf_available).
2898 ?add_element_wf(E,Set,NewSet,WF) :- add_element_wf(E,Set,NewSet,_,WF).
2899
2900 :- block add_element_wf(?,-,?,?,?).
2901 add_element_wf(Element,Set,NewSet,Done,_WF) :- Set==[],!,
2902 % try and convert to AVL if possible:
2903 ? equal_object_optimized(NewSet,[Element]), % we could call equal_object_opt3 directly
2904 Done=done.
2905 ?add_element_wf(E,Set,NewSet,Done,WF) :- add_element1_wf(E,Set,NewSet,Done,WF).
2906
2907 :- block %add_element1(-,?,-,?),
2908 add_element1_wf(?,-,?,?,?).
2909 add_element1_wf(E,Set,NewSet,Done,WF) :- var(E),!, add_element_var(Set,NewSet,E,Done,WF).
2910 add_element1_wf(E,[H|T],NewSet,Done,WF) :- E==H,!,
2911 % avoid running [H|T] through expand_custom_set_to_list, in case T is a variable this will create a pending co-routine
2912 equal_object_wf(NewSet,[H|T],add_element1_1,WF),Done=done.
2913 add_element1_wf(E,Set,NewSet,Done,WF) :-
2914 nonvar(Set), is_custom_explicit_set_nonvar(Set),
2915 add_element_to_explicit_set_wf(Set,E,R,WF),!,
2916 ? equal_object_wf(R,NewSet,add_element1_2,WF),Done=done.
2917 add_element1_wf(E,Set,NewSet,Done,WF) :-
2918 expand_custom_set_to_list_wf(Set,ESet,_,add_element1,WF),
2919 % we could avoid this expansion by treating avl_set,... below in add_element3
2920 ? add_element2_wf(ESet,E,NewSet,Done,WF).
2921
2922
2923 add_element_var([],Res,Element,Done,WF) :- !,
2924 equal_cons_wf(Res,Element,[],WF),Done=done.
2925 add_element_var(Set,Res,Element,Done,WF) :- Set \= [], Set \= closure(_,_,_),
2926 is_one_element_set(Res,ResEl), !,
2927 % the result is a one element set; hence Element *must* be the element in that set
2928 equal_object_wf(Element,ResEl,add_element_var_1,WF),
2929 equal_object_wf(Set,Res,add_element_var_2,WF), Done=done.
2930 add_element_var(Set,Res,Element,Done,WF) :- %when(nonvar(Element), add_element(Element,Set,Res,Done)).
2931 expand_custom_set_to_list_wf(Set,ESet,_,add_element_var,WF),
2932 add_element2_wf(ESet,Element,Res,Done,WF).
2933
2934 is_one_element_set(S,_) :- var(S),!,fail.
2935 is_one_element_set([H|T],H) :- T==[].
2936 is_one_element_set(avl_set(S),El) :- is_one_element_custom_set(avl_set(S),El).
2937
2938 :- block add_element2_wf(-,?,?,?,?).
2939 add_element2_wf([],E,Res,Done,WF) :- var(Res),should_be_converted_to_avl(E),
2940 construct_avl_from_lists_wf([E],R,WF),!,
2941 (R,Done)=(Res,done).
2942 ?add_element2_wf(S,E,Res,Done,WF) :- copy_list_skeleton(S,Res,WF),
2943 ? add_element3_wf(S,E,Res,Done,WF).
2944
2945 % TO DO: use something else, like subset to propagate info that Set1 <: Set1 \/ {New}
2946 :- block copy_list_skeleton(-,?,?).
2947 copy_list_skeleton([],_,_WF) :- !.
2948 copy_list_skeleton([H|T],R,WF) :- !, % H must be in R, but not all elements of R are in [H|T] !; it could be the added element
2949 ((ground_value(H) ; unbound_variable_for_cons(R) ;
2950 custom_explicit_sets:singleton_set(R,_) % if R is a singleton set {EL} then H must be EL and T=[]
2951 )
2952 ? -> equal_cons_wf(R,H,RR,WF),
2953 copy_list_skeleton(T,RR,WF)
2954 ; %nl,print(not_copying([H|T],R)),nl,
2955 true % otherwise equal_cons_wf can backpropagate elements from R into H !! see {x,y| x = {1,2} & x \/ y = {1,2,3} & 1:y } test 1535
2956 ).
2957 copy_list_skeleton(Set,R,WF) :- is_custom_explicit_set(Set,copy_list_skeleton),!,
2958 expand_custom_set_to_list_wf(Set,ESet,_,copy_list_skeleton,WF), copy_list_skeleton(ESet,R,WF).
2959 copy_list_skeleton(Skel,R,WF) :- add_internal_error('Argument not a set: ',copy_list_skeleton(Skel,R,WF)),fail.
2960
2961 :- block add_element3_wf(-,?,?,?,?).
2962 add_element3_wf([],E,Res,Done,WF) :- % Res must be {E}
2963 ? equal_cons_wf(Res,E,[],WF),
2964 Done=done.
2965 add_element3_wf([H|T],E,Res,Done,WF) :-
2966 ? equality_objects_wf(H,E,EqRes,WF),
2967 ? equal_cons_wf(Res,H,TailRes,WF), % was: equal_object([H|TailRes],Res), % use WF?
2968 (var(EqRes)
2969 ? -> has_not_to_be_added([H|T],Res,EqRes,0)
2970 ; true),
2971 %(when(nonvar(EqRes),(print(nv(EqRes,H,T,WF)),nl))),
2972 ? add_element4_wf(EqRes,T,E,TailRes,Done,WF).
2973
2974
2975 % check if an element has not to be added to arg1 to obtain arg2
2976 :- block has_not_to_be_added(?,-,?,?),has_not_to_be_added(-,?,?,?).
2977 %has_not_to_be_added(A,B,R,Sz) :- print(has_not_to_be_added(A,B,R,Sz)),nl,fail.
2978 has_not_to_be_added([],[],R,Sz) :- !,(Sz=1 -> R=pred_true % we have 1 element: force equality with first element
2979 ; true).
2980 has_not_to_be_added([],[_H|T],R,_Sz) :- !, %(var(R) -> print(add_f([],[_H|T],R,_Sz)),nl ; true),
2981 empty_set(T),R=pred_false. % R=pred_false means with add an element
2982 has_not_to_be_added([_|_],[],_,_) :- !,fail. % we can either add or not; in both cases we do not obtain []
2983 ?has_not_to_be_added([_|T1],[_|T2],R,Sz) :- !, S1 is Sz+1, has_not_to_be_added(T1,T2,R,S1).
2984 has_not_to_be_added(_,_,_,_). % to do: support custom explicit sets
2985
2986 :- block add_element4_wf(-,?,?,?,?,?).
2987 ?add_element4_wf(pred_true, T,_E,TRes,Done,WF) :- equal_object_wf(T,TRes,add_element4_wf,WF), Done=done.
2988 ?add_element4_wf(pred_false,T, E,TRes,Done,WF) :- add_element3_wf(T,E,TRes,Done,WF).
2989
2990
2991 :- assert_must_succeed((kernel_objects:add_new_element(int(3),[int(2),int(1)],R),
2992 kernel_objects:equal_object(R,[int(1),int(2),int(3)]))).
2993 :- assert_must_succeed((kernel_objects:add_new_element([int(2)],[[int(2),int(1)],[]],R),
2994 kernel_objects:equal_object(R,[[],[int(1),int(2)],[int(2)]]))).
2995
2996 % TO DO : get rid of need for non-WF version in enumeration basic type:
2997 add_new_element(E,Set,NewSet) :- init_wait_flags(WF),
2998 add_new_element_wf(E,Set,NewSet,WF), ground_wait_flags(WF).
2999
3000 % use when you are sure the element to add is not in the set
3001 % to be used for adding elements to an accumulator
3002 :- block add_new_element_wf(?,-,?,?).
3003 %%add_new_element(E,Set,NewSet) :- add_element(E,Set,NewSet). % TO DO : Improve
3004 add_new_element_wf(E,Set,NewSet,WF) :-
3005 is_custom_explicit_set(Set,add_element),
3006 add_element_to_explicit_set_wf(Set,E,R,WF),!,
3007 equal_object_wf(R,NewSet,add_new_element_wf,WF).
3008 add_new_element_wf(E,Set,NewSet,WF) :-
3009 expand_custom_set_to_list_wf(Set,ESet,_,add_new_element_wf,WF),
3010 add_new_element2(ESet,E,NewSet,WF).
3011
3012 :- block add_new_element2(-,?,?,?).
3013 add_new_element2([],E,Res,WF) :- var(Res),should_be_converted_to_avl(E),
3014 construct_avl_from_lists_wf([E],R,WF),!,equal_object_wf(R,Res,add_new_element2,WF).
3015 add_new_element2(S,E,Res,WF) :- equal_cons_wf(Res,E,S,WF).
3016
3017
3018
3019
3020 :- assert_must_succeed(exhaustive_kernel_check(remove_element_wf(int(3),[int(3),int(1)],
3021 [int(1)],_WF))).
3022 :- assert_must_succeed(exhaustive_kernel_check(remove_element_wf(int(1),[int(3),int(1)],
3023 [int(3)],_WF))).
3024 :- assert_must_succeed(exhaustive_kernel_fail_check(remove_element_wf(int(1),[int(3),int(1)],
3025 [int(1)],_WF))).
3026 :- assert_must_succeed(exhaustive_kernel_fail_check(remove_element_wf(int(11),[int(1)],
3027 [int(1)],_WF))).
3028 :- assert_must_succeed(exhaustive_kernel_fail_check(remove_element_wf(int(1),[int(3),int(1)],
3029 [],_WF))).
3030 :- assert_must_succeed((kernel_objects:remove_element_wf(fd(1,'Name'),X,[fd(2,'Name'),fd(3,'Name')],_WF),
3031 kernel_objects:equal_object(X,global_set('Name')))).
3032 :- assert_must_succeed((kernel_objects:remove_element_wf(int(1),X,[int(2)],_WF),
3033 kernel_objects:equal_object(X,[int(2),int(1)]))).
3034 :- assert_must_succeed(( kernel_objects:remove_element_wf(int(1),[int(X),int(2)],R,WF), kernel_waitflags:ground_wait_flags(WF),X==1,R==[int(2)] )).
3035 :- assert_must_succeed(( kernel_objects:remove_element_wf(X,[int(1),int(2)],R,WF), kernel_waitflags:ground_wait_flags(WF),X==int(2),R==[int(1)] )).
3036 :- assert_must_succeed(( kernel_objects:remove_element_wf(X,[pred_true /* bool_true */,pred_false /* bool_false */],R,WF), kernel_waitflags:ground_wait_flags(WF),X==pred_false /* bool_false */,R==[pred_true /* bool_true */] )).
3037
3038 ?remove_element_wf(X,Set,Res,WF) :- remove_element_wf(X,Set,Res,WF,_DONE).
3039
3040 :- block remove_element_wf(?,-, -,?,?).
3041 remove_element_wf(X,Set,Res,WF,_DONE) :- Res==[],!, % we know that X must be the only element in Set
3042 equal_object_wf(Set,[X],remove_element_wf,WF).
3043 remove_element_wf(X,Set,Res,WF,DONE) :-
3044 ? remove_element_wf1(X,Set,Res,WF,DONE).
3045
3046 :- block remove_element_wf1(?,-, ?,?,?).
3047 remove_element_wf1(X,avl_set(A),Res,WF,DONE) :- element_can_be_added_or_removed_to_avl(X),!,
3048 /* TO DO: try and move the check about whether X can be added to later; when either X is known
3049 or LWF is instantiated */
3050 remove_element_from_explicit_set(avl_set(A),X,AR),
3051 equal_object_wf(AR,Res,remove_element_wf1,WF), DONE=done.
3052 remove_element_wf1(X,Set,Res,WF,DONE) :- /* DONE is ground when element actually removed */
3053 expand_custom_set_to_list_wf(Set,ESet,_,remove_element_wf1,WF),
3054 %% nl,print(remove_element_wf1(X,Set,ESet,Res,WF,DONE)),nl,nl, %%
3055 ? remove_element_wf2(X,ESet,Res,LWF,DONE),
3056 %when(nonvar(DONE), print_bt_message(removed(X,ESet,Res,LWF))),
3057 (DONE==done -> true
3058 ; same_card_prop(ESet,[X|Res]), % in case result is instantiated: check compatible with inputs
3059 ? get_cardinality_wait_flag(ESet,remove_element_wf1(X,ESet,Res),WF,LWF),
3060 ? quick_propagation_element_information(Set,X,WF,_) % use Set rather than ESet; better if still closure or AVL
3061 ).
3062
3063 :- block same_card_prop(-,?), same_card_prop(?,-).
3064 same_card_prop([],[_|_]) :- !, fail.
3065 same_card_prop([_|T],R) :- !,
3066 (R=[] -> fail
3067 ; R=[_|RT] -> same_card_prop(T,RT)
3068 ; true). % just ignore
3069 same_card_prop(_,_).
3070
3071 :- block remove_element_wf2(?,-,?,?,?).
3072 remove_element_wf2(H1,[H2|T],Res,LWF,DONE) :- Res==[],!,
3073 equal_object(H1,H2,remove_element_wf2),
3074 remove_element_wf3(pred_true,H1,H2,T,Res,LWF,DONE).
3075 remove_element_wf2(H1,[H2|T],Res,LWF,DONE) :-
3076 prop_empty_set(T,EqRes),
3077 ? equality_objects_lwf(H1,H2,EqRes,LWF,no_wf_available), % TODO: pass WF
3078 ? remove_element_wf3(EqRes,H1,H2,T,Res,LWF,DONE).
3079 /* important for total_bijection that this has higher priority than other expansions */
3080
3081 :- block prop_empty_set(-,?).
3082 % force second argument to pred_true if first arg is empty set
3083 prop_empty_set([],R) :- !, R=pred_true.
3084 prop_empty_set(_,_).
3085
3086 :- block remove_element_wf3(-,?,?,?,?,-,?).
3087 % remove_element_wf3(EqRes,H1,H2,T,Res,LWF,DONE) :- print(remove_element_wf3(EqRes,H1,H2,T,Res,LWF,DONE)),nl,fail.
3088 remove_element_wf3(pred_true,_H1,_H2,T,Res,_LWF,DONE) :-
3089 ? equal_object(T,Res,remove_element_wf3_1),DONE=done.
3090 remove_element_wf3(pred_false,E,H,T,Res,LWF,DONE) :-
3091 ? equal_object([H|RT],Res,remove_element_wf3_2),
3092 ? remove_element_wf2(E,T,RT,LWF,DONE).
3093
3094 /* the same as above: but do not remove if infinite or closure */
3095
3096 :- block remove_element_wf_if_not_infinite_or_closure(?,-,?,?,?,?).
3097 remove_element_wf_if_not_infinite_or_closure(X,Set, Res,WF,LWF,Done) :-
3098 (dont_expand(Set)
3099 -> check_element_of_wf(X,Set,WF),
3100 equal_object_wf(Res,Set,remove_element_wf_if_not_infinite_or_closure,WF),
3101 Done=true % or should we wait until X known ?
3102 %(var(Res)->Res=Set ; equal_object(Res,Set))
3103 ; expand_custom_set_to_list_wf(Set,ESet,_,remove_element_wf_if_not_infinite_or_closure,WF),
3104 ? remove_element_wf2(X,ESet,Res,LWF,Done)
3105 ).
3106
3107 %:- use_module(bmachine_construction,[external_procedure_used/1]).
3108 %dont_expand(global_set('STRING')) :- !. % s: STRING +-> ... will generate new strings !
3109 %(external_procedure_used(_) -> true). % we could check if there is a STRING generating procedure involved
3110 % unless we use external functions, there is *no* way that new strings can be generated from a B machine !
3111 % Hence: we can expand STRING safely and thus avoid infinite enumeration of partial functions, ...
3112 % example: procs : STRING +-> {"waiting"} & card( dom(procs) ) = 6 thus fails quickly
3113 dont_expand(avl_set(_)) :- !,fail.
3114 dont_expand(closure(_,_,_)) :- !. % relevant for tests 283, 1609, 1858
3115 dont_expand(Set) :-
3116 is_infinite_or_very_large_explicit_set(Set).
3117 % should we use a smaller bound than 20000 (comprehension_set_symbolic_limit)? see test 1609
3118
3119
3120 :- assert_must_succeed((kernel_objects:check_no_duplicates_in_list([int(1),int(2)],[],no_wf_available))).
3121 :- assert_must_fail((kernel_objects:check_no_duplicates_in_list([int(1),int(2),int(1)],[],no_wf_available))).
3122
3123 :- block check_no_duplicates_in_list(-,?,?).
3124 check_no_duplicates_in_list([],_,_) :- !.
3125 check_no_duplicates_in_list([H|T],ElementsSoFar,WF) :- !,
3126 not_element_of_wf(H,ElementsSoFar,WF),
3127 add_new_element_wf(H,ElementsSoFar,ElementsSoFar2,WF),
3128 check_no_duplicates_in_list(T,ElementsSoFar2,WF).
3129 check_no_duplicates_in_list(CS,ElementsSoFar,WF) :-
3130 disjoint_sets(CS,ElementsSoFar,WF).
3131
3132 :- public warn_if_duplicates_in_list/3.
3133 % code for debugging / safe mode execution to check for duplicates
3134 warn_if_duplicates_in_list(List,Src,WF) :-
3135 %get_last_wait_flag(warn_if_duplicates_in_list,WF,WFX), % we may wish to use another WF here !?
3136 get_enumeration_finished_wait_flag(WF,WFX),
3137 when(nonvar(WFX),warn_if_duplicates_in_list(List,[],Src,WF)).
3138
3139 :- block warn_if_duplicates_in_list(-,?,?,?).
3140 warn_if_duplicates_in_list([],_,_,_) :- !.
3141 warn_if_duplicates_in_list([H|T],ElementsSoFar,Src,WF) :- !,
3142 membership_test_wf(ElementsSoFar,H,MemRes,WF),
3143 warn_aux(MemRes,H,T,ElementsSoFar,Src,WF).
3144 warn_if_duplicates_in_list(CS,ElementsSoFar,Src,WF) :-
3145 when(ground(CS),
3146 (disjoint_sets(CS,ElementsSoFar,WF)
3147 -> true
3148 ; add_error(Src,'Duplicates in list: ',CS:ElementsSoFar:Src))).
3149
3150 :- block warn_aux(-,?,?,?,?,?).
3151 warn_aux(pred_true,H,_,ElementsSoFar,Src,_WF) :-
3152 add_error(Src,'Duplicate in list: ',H:ElementsSoFar:Src).
3153 warn_aux(pred_false,H,T,ElementsSoFar,Src,WF) :-
3154 add_new_element_wf(H,ElementsSoFar,ElementsSoFar2,WF),
3155 warn_if_duplicates_in_list(T,ElementsSoFar2,Src,WF).
3156
3157
3158 :- assert_must_succeed((kernel_objects:remove_exact_first_element([int(1),int(2)],X,[[]]),
3159 X = [[int(1),int(2)],[]])).
3160 :- assert_must_succeed((kernel_objects:remove_exact_first_element(X,global_set('Name'),T),
3161 X==fd(1,'Name'),T==[fd(2,'Name'),fd(3,'Name')])).
3162 :- assert_must_fail((kernel_objects:remove_exact_first_element([[]],X,_),
3163 X = [[int(1),int(2)],[]])).
3164
3165 :- assert_must_succeed((kernel_objects:remove_exact_first_element(X,C,R),
3166 kernel_objects:gen_test_interval_closure(1,2,C),
3167 X == int(1), R == [int(2)] )).
3168
3169 gen_test_interval_closure(From,To,CL) :-
3170 CL=closure(['_zzzz_unary'],[integer],b(member( b(identifier('_zzzz_unary'),integer,[]),
3171 b(interval(b(value(int(From)),integer,[]),
3172 b(value(int(To)),integer,[])),set(integer),[])),pred,[])).
3173
3174 :- block remove_exact_first_element(?,-,?).
3175 remove_exact_first_element(X,Set,Res) :- remove_exact_first_element1(Set,X,Res).
3176
3177 remove_exact_first_element1([],_,_) :- fail.
3178 remove_exact_first_element1([H|T],H,T).
3179 remove_exact_first_element1(avl_set(A),H,T) :- remove_minimum_element_custom_set(avl_set(A),H,T).
3180 remove_exact_first_element1(global_set(GS),H,T) :-
3181 remove_minimum_element_custom_set(global_set(GS),H,T).
3182 remove_exact_first_element1(freetype(GS),H,T) :-
3183 remove_minimum_element_custom_set(freetype(GS),H,T).
3184 remove_exact_first_element1(closure(P,Types,B),H,T) :-
3185 remove_minimum_element_custom_set(closure(P,Types,B),H,T).
3186
3187
3188 :- assert_must_succeed((kernel_objects:delete_element_wf(fd(1,'Name'),X,[fd(2,'Name'),fd(3,'Name')],_WF),
3189 X = global_set('Name'))).
3190 :- assert_must_succeed((kernel_objects:delete_element_wf(int(1),X,[int(2)],_WF),
3191 X = [int(2),int(1)])).
3192 :- assert_must_succeed((kernel_objects:delete_element_wf([int(1),int(2)],X,[],_WF),
3193 X = [[int(2),int(1)]])).
3194 :- assert_must_succeed((kernel_objects:delete_element_wf(int(3),X,[int(2),int(1)],_WF),
3195 X = [int(2),int(1)])).
3196 :- assert_must_succeed((kernel_objects:delete_element_wf(int(1),X,X,_WF),
3197 X = [])).
3198 :- assert_must_fail((kernel_objects:delete_element_wf(int(X),[int(1)],[int(1)],_WF),
3199 X = 1)).
3200
3201 /* WARNING: only use when R is not instantiated by something else;
3202 (except for R=[]) */
3203
3204
3205 :- block delete_element_wf(?,-,?,?).
3206 delete_element_wf(X,Set,Res,WF) :-
3207 ground(X),
3208 try_expand_and_convert_to_avl_with_check(Set,ESet,delete_element_wf),!,
3209 delete_element0(X,ESet,Res,WF).
3210 delete_element_wf(X,Set,Res,WF) :- delete_element1(X,Set,Res,WF).
3211
3212 :- block delete_element0(?,-,?,?).
3213 delete_element0(X,ESet,Res,WF) :-
3214 ( is_custom_explicit_set(ESet,delete_element),
3215 delete_element_from_explicit_set(ESet,X,DS)
3216 -> equal_object_wf(DS,Res,delete_element0,WF)
3217 ; delete_element1(X,ESet,Res,WF)
3218 ).
3219
3220 delete_element1(X,Set,Res,WF) :- expand_custom_set_to_list_wf(Set,ESet,_,delete_element1,WF),
3221 %check_is_expanded_set(ESet,delete_element2),
3222 delete_element2(ESet,X,Res,WF).
3223
3224 :- block delete_element2(-,?,?,?).
3225 delete_element2([],_,[],_). /* same as above, but allow element to be absent */
3226 delete_element2([H2|T],E,R,WF) :-
3227 equality_objects_wf(H2,E,EqRes,WF),
3228 delete_element3(EqRes,H2,T,E,R,WF).
3229 %when_sufficiently_instantiated(E,H2,delete_element3(H1,[H2|T],R)). /* added by Michael Leuschel, 16/3/06 */
3230
3231 :- block delete_element3(-,?,?,?,?,?).
3232 delete_element3(pred_true,_H2,T,_,R,WF) :- equal_object_wf(R,T,delete_element3,WF).
3233 delete_element3(pred_false,H2,T,E,Res,WF) :- equal_cons_wf(Res,H2,RT,WF),delete_element2(T,E,RT,WF).
3234
3235
3236
3237
3238 :- assert_must_succeed(kernel_objects:check_is_expanded_set([int(1)],test)).
3239
3240 :- public check_is_expanded_set/2.
3241 check_is_expanded_set(X,Source) :-
3242 (nonvar(X),(X=[] ; X= [_|_]) -> true
3243 ; add_internal_error('Is not expanded set: ',check_is_expanded_set(X,Source))
3244 ).
3245
3246
3247 /* union/3 */
3248
3249 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(3)],[int(2),int(1),int(3)],[int(1),int(3),int(2)]))).
3250 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(1)],[int(1),int(2)],[int(1),int(2)]))).
3251 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(3)],[int(2),int(1)],[int(1),int(3),int(2)]))).
3252 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(3),int(2)],[int(2),int(1)],[int(1),int(3),int(2)]))).
3253 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],union([int(3),int(4)],[int(2),int(1)],[int(1),int(3),int(2)]))).
3254 :- assert_must_succeed((V1 = term(floating(1.0)), V2 = term(floating(2.0)), V3 = term(floating(-1.0)),
3255 exhaustive_kernel_check([commutative],union([V3,V2],[V2,V1],[V1,V3,V2])))).
3256 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3257 V3 = (string(three),term(floating(1.0))),
3258 exhaustive_kernel_check([commutative],union([V3,V2],[V2,V1],[V1,V3,V2])))).
3259 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3260 V3 = (string(three),term(floating(1.0))),
3261 exhaustive_kernel_check([commutative],union([V3,V2],[V1,V3],[V2,V3,V1])))).
3262 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3263 V3 = (string(three),term(floating(1.0))),
3264 exhaustive_kernel_fail_check([commutative],union([V3,V2],[V2,V1],[V1,V2])))).
3265 :- assert_must_succeed((kernel_objects:union([int(1)],[int(2)],Res),kernel_objects:equal_object(Res,[_,_]))).
3266 :- assert_must_succeed((kernel_objects:union([],[int(2)],Res),
3267 kernel_objects:equal_object(Res,[int(2)]))).
3268 :- assert_must_succeed((kernel_objects:union([int(2)],[],Res),
3269 kernel_objects:equal_object(Res,[int(2)]))).
3270 :- assert_must_succeed((kernel_objects:union([int(2)],[int(2)],Res),
3271 kernel_objects:equal_object(Res,[int(2)]))).
3272 :- assert_must_succeed((kernel_objects:union([int(1)],Res,[int(1),int(2)]),
3273 kernel_objects:equal_object(Res,[int(2)]))).
3274 :- assert_must_succeed((kernel_objects:union([fd(1,'Name')],X,Res),X=global_set('Name'),
3275 kernel_objects:equal_object(Res,X))).
3276 :- assert_must_succeed((kernel_objects:union(X,global_set('Name'),Res),X=[fd(2,'Name'),fd(1,'Name')],
3277 kernel_objects:equal_object(Res,global_set('Name')))).
3278 :- assert_must_succeed((kernel_objects:union([fd(1,'Name')],[fd(3,'Name'),fd(2,'Name')],Res),
3279 kernel_objects:equal_object(Res,global_set('Name')))).
3280 %:- assert_must_succeed((kernel_objects:union([fd(1,'Name')],[fd(3,'Name'),fd(2,'Name')],Res),
3281 % kernel_objects:equal_object(Res,X),X=global_set('Name'))).
3282 :- assert_must_fail((kernel_objects:union([int(1)],[int(2)],Res),
3283 (kernel_objects:equal_object(Res,[_]);kernel_objects:equal_object(Res,[_,_,_|_])))).
3284 :- assert_must_fail((kernel_objects:union([int(1)],[int(1)],Res),(Res=[];kernel_objects:equal_object(Res,[_,_|_])))).
3285 :- assert_must_fail((kernel_objects:union([fd(1,'Name')],[fd(2,'Name')],Res),
3286 kernel_objects:equal_object(Res,global_set('Name')))).
3287 % kernel_objects:union([int(1),int(2)],X,[int(1),int(2),int(3)])
3288
3289 ?union(S1,S2,Res) :- init_wait_flags(WF,[union]), union_wf(S1,S2,Res,WF), ground_wait_flags(WF).
3290
3291 :- block union_wf(-,-,-,?).
3292 %union_wf(Set1,Set2,Res,_WF) :- print(union_wf(Set1,Set2,Res)),nl,fail.
3293 union_wf(Set1,Set2,Res,WF) :- Set1==[],!,equal_object_wf(Set2,Res,union_wf_1,WF).
3294 union_wf(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,union_wf_2,WF).
3295 union_wf(Set1,Set2,Res,WF) :- Res==[],!,empty_set_wf(Set1,WF), empty_set_wf(Set2,WF).
3296 ?union_wf(Set1,Set2,Res,WF) :- union0(Set1,Set2,Res,WF).
3297
3298 :- block union0(-,-,?,?), union0(-,?,-,?), union0(?,-,-,?). % require two arguments to be known
3299 ?union0(Set1,Set2,Res,WF) :- Set1==[],!,equal_object_wf(Set2,Res,union0_1,WF).
3300 ?union0(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,union0_2,WF).
3301 union0(Set1,Set2,Res,WF) :- Res==[],!,empty_set_wf(Set1,WF), empty_set_wf(Set2,WF).
3302 union0(Set1,Set2,Res,WF) :- nonvar(Res), singleton_set(Res,X),!,
3303 (var(Set1) -> union0_to_singleton_set(Set2,Set1,X,WF) ; union0_to_singleton_set(Set1,Set2,X,WF)).
3304 ?union0(Set1,Set2,Res,WF) :- (var(Set1) -> union1(Set2,Set1,Res,WF) ; union1(Set1,Set2,Res,WF)).
3305
3306 % optimized version for Set1 \/ Set2 = {X}
3307 % TO DO: is not triggered when Set1 and Set2 are instantiated first (before result)
3308 % >>> z:11..12 & {x,y} \/ {v} = {z} does not work
3309 union0_to_singleton_set([],Set2,X,WF) :- !, equal_object_wf(Set2,[X],union0_3,WF). % cannot be reached, due to checks above
3310 union0_to_singleton_set([H|T],Set2,X,WF) :- !, empty_set_wf(T,WF), equal_object_wf(H,X,WF),
3311 check_subset_of_wf(Set2,[X],WF).
3312 union0_to_singleton_set(avl_set(A),Set2,X,WF) :- !, singleton_set(avl_set(A),AEl),
3313 equal_object_wf(AEl,X,WF),
3314 check_subset_of_wf(Set2,[X],WF).
3315 union0_to_singleton_set(Set1,Set2,X,WF) :- % closure or global_set; revert to normal treatment
3316 union1(Set1,Set2,[X],WF).
3317
3318 union1(Set1,Set2,Res,WF) :- var(Set2), dont_expand_this_explicit_set(Set1), !,
3319 block_union1e(Set2,Set1,Res,WF). % try avoid expanding Set1 and wait until Set2 becomes known, may enable symbolic union
3320 union1(Set1,Set2,Res,WF) :-
3321 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set1,ESet1,WF),
3322 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set2,ESet2,WF),
3323 ? union1e(ESet1,ESet2,Res,WF).
3324
3325 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set,ESet,_) :-
3326 (var(Set);Set=closure(_,_,_)),!,ESet=Set.
3327 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set,ESet,WF) :-
3328 try_expand_and_convert_to_avl_unless_large_wf(Set,ESet,WF).
3329
3330 :- block block_union1e(-,?,?,?).
3331 block_union1e(Set1,Set2,Res,WF) :- Res==[],!,
3332 empty_set_wf(Set1,WF), empty_set_wf(Set2,WF).
3333 block_union1e(Set1,Set2,Res,WF) :-
3334 union1e(Set1,Set2,Res,WF).
3335
3336 union1e(Set1,Set2,Res,WF) :-
3337 is_custom_explicit_set(Set1,union1e),
3338 union_of_explicit_set(Set1,Set2,Union),
3339 ? !, equal_object_wf(Union,Res,union1e,WF).
3340 union1e(Set2,Set1,Res,WF) :- % Set2=avl_set(_), nonvar(Set1), Set1 \= avl_set(_),
3341 nonvar(Set1), Set1=avl_set(_), Set2 \= avl_set(_), \+ ground(Set2),
3342 !, % avoid expanding Set2
3343 expand_custom_set_to_list_wf(Set1,ESet1,_,union1e_1,WF),
3344 ? union2(ESet1,Set2,Res,WF), lazy_check_subset_of(Set2,Res,WF).
3345 union1e(Set1,Set2,Res,WF) :-
3346 expand_custom_set_to_list_wf(Set1,ESet1,_,union1e_2,WF), % we could avoid this expansion by treating avl_set,... below in union2
3347 ? union2(ESet1,Set2,Res,WF),
3348 ? lazy_check_subset_of(Set1,Res,WF), % ADDED to solve {x,y| { x \/ y } <: {{1} \/ {2}}}
3349 ? lazy_check_subset_of(Set2,Res,WF) % could perform additional constraint checking
3350 % ,try_prop_card_leq(ESet1,Res), try_prop_card_leq(Set2,Res). %%% seems to slow down ProB: investigate
3351 .
3352
3353 /* not yet used:
3354 % lazy_check_in_union(R,Set1,Set2,WF): check if all elements of R appear in at least one of the sets Sets1/2:
3355 :- block lazy_check_in_union(-,?,?,?).
3356 lazy_check_in_union([],_,_,_) :- !.
3357 lazy_check_in_union([H|T],Set1,Set2,WF) :- !,
3358 in_one_of_sets(H,Set1,Set2,WF),
3359 lazy_check_in_union(T,Set1,Set2,WF).
3360 lazy_check_in_union(_,_,_,_).
3361
3362 % check if an element appear in at least one of the two sets:
3363 in_one_of_sets(H,Set1,Set2,WF) :-
3364 membership_test_wf(Set1,H,MemRes1,WF),
3365 (MemRes1==pred_true -> true
3366 ; one_true(MemRes1,MemRes2),
3367 membership_test_wf(Set2,H,MemRes2,WF)
3368 ).
3369
3370 :- block one_true(-,-).
3371 one_true(MemRes1,MemRes2) :- var(MemRes1),!,
3372 (MemRes2=pred_false -> MemRes1=pred_true ; true).
3373 one_true(pred_true,_).
3374 one_true(pred_false,pred_true).
3375 */
3376
3377
3378 :- block lazy_try_check_element_of(?,-,?).
3379 ?lazy_try_check_element_of(H,Set,WF) :- lazy_check_element_of_aux(Set,H,WF).
3380
3381 ?lazy_check_element_of_aux(closure(P,T,B),H,WF) :- !, check_element_of_wf(H,closure(P,T,B),WF).
3382 ?lazy_check_element_of_aux(avl_set(A),H,WF) :- !, check_element_of_wf(H,avl_set(A),WF).
3383 lazy_check_element_of_aux([X|T],H,WF) :- !, lazy_check_element_of_list(T,X,H,WF).
3384 lazy_check_element_of_aux(_,_,_).
3385
3386 :- block lazy_check_element_of_list(-,?,?,?).
3387 lazy_check_element_of_list([],X,H,WF) :- !, equal_object_wf(X,H,WF).
3388 lazy_check_element_of_list([Y|T],X,H,WF) :- !,
3389 quick_propagation_element_information([X,Y|T],H,WF,_). % TO DO: check that we loose no performance due to this
3390 lazy_check_element_of_list(_,_,_,_).
3391
3392 % an incomplete subset check without enumeration
3393 :- block lazy_check_subset_of(-,?,?), lazy_check_subset_of(?,-,?).
3394 lazy_check_subset_of(Set1,Set2,WF) :- nonvar(Set2),
3395 ? (Set2=closure(_,_,_) ; Set2=avl_set(_)),!, lazy_check_subset_of2(Set1,Set2,WF).
3396 lazy_check_subset_of(_,_,_). % ignore other set representations
3397 :- block lazy_check_subset_of2(-,?,?).
3398 lazy_check_subset_of2([],_,_WF) :- !.
3399 ?lazy_check_subset_of2([H|T],Set,WF) :- !, check_element_of_wf(H,Set,WF), lazy_check_subset_of2(T,Set,WF).
3400 lazy_check_subset_of2(_,_,_). % ignore other set representations
3401
3402 :- block union2(-,?,?,?).
3403 ?union2([],S,Res,WF) :- equal_object_optimized_wf(S,Res,union2,WF).
3404 union2([H|T],Set2,Res,WF) :-
3405 (T\==[],nonvar(Set2), Set2=[H2|T2], T2==[] % minor optimisation for improved propagation; e.g., for x:S & S<:1..13 & S \/ {x} = S2 & x/: S2
3406 % the constraint is not yet detected straight away: x:S & S<:1..12 & S \/ {x} /= S
3407 ? -> union3(H2,T2,[H|T],Res,WF)
3408 ? ; union3(H,T,Set2,Res,WF)
3409 ).
3410 union3(H,T,Set2,Res,WF) :-
3411 ? add_element_wf(H,Set2,R,Done,WF),
3412 ? lazy_try_check_element_of(H,Res,WF), % TO DO: propagate constraint that H is in Res
3413 (T==[]
3414 ? -> equal_object_optimized_wf(R,Res,union3,WF) %union2(T,R,Res,WF)
3415 ? ; union4(Done,T,R,Res,WF)).
3416 :- block union4(-,?,?,?,?).
3417 ?union4(_Done,T,R,Res,WF) :- union2(T,R,Res,WF). % if WF not set to 2 there maybe equality_objects pending from add_element_wf ! TO DO: investigate; see test 293
3418
3419
3420 :- assert_must_succeed(exhaustive_kernel_check(union_generalized([[int(3)],[int(2),int(1),int(3)]],[int(1),int(3),int(2)]))).
3421 :- assert_must_succeed(exhaustive_kernel_check(union_generalized([[int(3),int(2)],[],[int(2),int(1),int(3)]],[int(1),int(3),int(2)]))).
3422 :- assert_must_succeed(exhaustive_kernel_fail_check(union_generalized([[int(3)],[int(3),int(4)],[int(2),int(1),int(3)]],[int(1),int(3),int(2)]))).
3423 :- assert_must_succeed((kernel_objects:union_generalized([[]],Res),Res=[])).
3424 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2)]],Res),
3425 kernel_objects:equal_object(Res,[_,_]))).
3426 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2),int(1)]],Res),
3427 kernel_objects:equal_object(Res,[_,_]))).
3428 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2),int(1)],[],[int(2)]],Res),
3429 kernel_objects:equal_object(Res,[_,_]))).
3430 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2)],X],Res),
3431 kernel_objects:equal_object(X,Res), X = [int(2),int(1),int(3)])).
3432 :- assert_must_succeed((kernel_objects:union_generalized([global_set('Name'),X,X,X],Res),
3433 kernel_objects:equal_object(global_set('Name'),Res), X = [fd(2,'Name'),fd(1,'Name')])).
3434 :- assert_must_succeed((kernel_objects:union_generalized([X,global_set('Name')],Res),
3435 kernel_objects:equal_object(global_set('Name'),Res), X = [fd(2,'Name'),fd(1,'Name')])).
3436 :- assert_must_fail((kernel_objects:union_generalized([[int(1)],[int(2)]],Res),(Res=[_];
3437 kernel_objects:equal_object(Res,[_,_,_|_])))).
3438 :- assert_must_fail((kernel_objects:union_generalized([[int(1)],[int(1)]],Res),(Res=[];
3439 kernel_objects:equal_object(Res,[_,_|_])))).
3440
3441 % treates the general_union AST node (union(.) in B syntax)
3442 ?union_generalized(S,Res) :- init_wait_flags(WF), union_generalized_wf(S,Res,WF), ground_wait_flags(WF).
3443
3444 :- block union_generalized_wf(-,-,?).
3445 union_generalized_wf(SetsOfSets,Res,WF) :- var(SetsOfSets), Res==[],!,
3446 expand_custom_set_to_list_wf(SetsOfSets,ESetsOfSets,_,union_generalized_wf,WF),
3447 all_empty_sets_wf(ESetsOfSets,WF).
3448 union_generalized_wf(SetsOfSets,Res,WF) :-
3449 ? union_generalized_wf2(SetsOfSets,Res,WF).
3450
3451 :- block union_generalized_wf2(-,?,?).
3452 union_generalized_wf2(SetsOfSets,Res,WF) :-
3453 custom_explicit_sets:union_generalized_explicit_set(SetsOfSets,ARes,WF),!,
3454 ? equal_object_optimized_wf(ARes,Res,union_generalized_avl_set,WF).
3455 union_generalized_wf2(SetsOfSets,Res,WF) :-
3456 expand_custom_set_to_list_wf(SetsOfSets,ESetsOfSets,_,union_generalized_wf2,WF),
3457 ? union_generalized2(ESetsOfSets,[],Res,WF).
3458
3459 :- block union_generalized2(-,?,?,?).
3460 union_generalized2([],S,Res,WF) :- equal_object_optimized_wf(S,Res,union_generalized2,WF).
3461 union_generalized2([H|T],UnionSoFar,Res,WF) :-
3462 Res==[],
3463 !,
3464 empty_set_wf(H,WF),
3465 empty_set_wf(UnionSoFar,WF),
3466 all_empty_sets_wf(T,WF).
3467 union_generalized2([H|T],UnionSoFar,Res,WF) :- union_wf(H,UnionSoFar,UnionSoFar2,WF),
3468 ((var(T);var(UnionSoFar2)),
3469 nonvar(Res),is_custom_explicit_set(Res,union_generalized2) % check important for Schneider2_Trees/NewSolver_v3_complex.mch and query CHOOSE_MODULES("bk-phi-H-2013", solution) (0.1 vs 0.9 secs)
3470 ? -> check_subset_of_wf(H,Res,WF)
3471 % this is only a very weak propagation; example, for union(v) = {4444} & v={{x},{y},{z}} we will instantiate v={{4444},...} and z=4444; see also test 1216
3472 ; true),
3473 union_generalized2(T,UnionSoFar2,Res,WF).
3474
3475 :- block all_empty_sets_wf(-,?).
3476 all_empty_sets_wf([],_).
3477 all_empty_sets_wf([H|T],WF) :- empty_set_wf(H,WF), all_empty_sets_wf(T,WF).
3478
3479 :- assert_must_succeed(exhaustive_kernel_check([commutative],intersection([int(3)],[int(2),int(1),int(3)],[int(3)]))).
3480 :- assert_must_succeed(exhaustive_kernel_check([commutative],intersection([int(4),int(3),int(2)],[int(2),int(1),int(3)],[int(2),int(3)]))).
3481 :- assert_must_succeed(exhaustive_kernel_check([commutative],intersection([int(4),int(3),int(2)],[],[]))).
3482 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],intersection([int(1),int(3)],[int(4),int(3),int(2)],[]))).
3483 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3484 V3 = (string(three),term(floating(1.0))),
3485 exhaustive_kernel_check([commutative],intersection([V3,V2],[V1,V3],[V3])))).
3486 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3487 V3 = (string(three),term(floating(1.0))),
3488 exhaustive_kernel_fail_check([commutative],intersection([V3,V2],[V1,V3],[V3,V2])))).
3489 :- assert_must_succeed((kernel_objects:intersection(Y,X,Res),X=global_set('Name'),
3490 kernel_objects:equal_object(Res,Y), Y =[fd(1,'Name')])).
3491 :- assert_must_succeed((kernel_objects:intersection([int(1)],[int(2)],Res),Res=[])).
3492 :- assert_must_succeed((kernel_objects:intersection([int(1)],[int(2)],[]))).
3493 :- assert_must_fail((kernel_objects:intersection([int(1),int(4),int(3)],[int(2),int(3)],[]))).
3494 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(1)],_))).
3495 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(1)],[int(2),int(1)]))).
3496 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(1)],[int(1),int(2)]))).
3497 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(3)],Res),
3498 kernel_objects:equal_object(Res,[int(2)]))).
3499 :- assert_must_succeed((kernel_objects:intersection([int(2)],[int(2)],Res),
3500 kernel_objects:equal_object(Res,[int(2)]))).
3501 :- assert_must_succeed((kernel_objects:intersection([int(2),int(3)],[int(3),int(4),int(2)],Res),
3502 kernel_objects:equal_object(Res,[int(2),int(3)]))).
3503 :- assert_must_fail((kernel_objects:intersection([int(1)],[int(2)],Res),(
3504 kernel_objects:equal_object(Res,[_|_])))).
3505 :- assert_must_fail((kernel_objects:intersection([int(1)],[int(1)],Res),(Res=[];
3506 kernel_objects:equal_object(Res,[_,_|_])))).
3507 :- assert_must_fail((kernel_objects:intersection([fd(1,'Name')],X,Res),X=global_set('Name'),
3508 kernel_objects:equal_object(Res,X))).
3509
3510
3511 ?intersection(S1,S2,Res) :- init_wait_flags(WF,[intersection]), intersection(S1,S2,Res,WF), ground_wait_flags(WF).
3512
3513 :- block intersection(-,-,-,?).
3514 intersection(Set1,Set2,Res,WF) :- (Set1==[] ; Set2==[]),!, empty_set_wf(Res,WF).
3515 intersection(Set1,Set2,Res,WF) :- quick_same_value(Set1,Set2),!,
3516 equal_object_wf(Res,Set1,inter0_equal,WF).
3517 intersection(Set1,Set2,Res,WF) :- Res==[],!,
3518 disjoint_sets(Set1,Set2,WF).
3519 intersection(Set1,Set2,Res,WF) :- % now we need to know at least a bit about both Set1 and Set2; at least given the current code below; TO DO: infer that {x} /\ s = {x} => x:s
3520 ? intersection0(Set1,Set2,Res,WF),
3521 ? propagate_intersection(Set1,Set2,Res,WF).
3522
3523 :- block propagate_intersection(?,?,-,?). % propagate constraint that result elements must be in both sets
3524 propagate_intersection(Set1,Set2,[H|T],WF) :-
3525 preference(data_validation_mode,false),
3526 !,
3527 ? propagate_intersection_aux(Set1,Set2,H,T,WF).
3528 propagate_intersection(Set1,Set2,avl_set(A),WF) :- !,
3529 ((unknown_set(Set1) ; unknown_set(Set2)) % otherwise intersection0 has already triggered below
3530 -> custom_explicit_sets:avl_approximate_size(A,Size),
3531 (Size<20
3532 -> expand_custom_set_to_list_wf(avl_set(A),ESet,_,propagate_intersection,WF)
3533 ; avl_min(A,Min), avl_max(A,Max), ESet=[Min,Max]
3534 ),
3535 ? propagate_intersection(Set1,Set2,ESet,WF)
3536 ; true).
3537 % other cases: Set1,2,3 could be interval closure with unknown bounds,...
3538 propagate_intersection(_,_,_,_).
3539
3540 :- block propagate_intersection_aux(-,-,-,?,?).
3541 propagate_intersection_aux(Set1,Set2,H,T,WF) :-
3542 ((unknown_set(Set1) ; unknown_set(Set2)) % otherwise intersection0 has already triggered below
3543 ? -> check_element_of_wf(H,Set1,WF), % should we do this lazily ?
3544 ? check_element_of_wf(H,Set2,WF),
3545 ? propagate_intersection(Set1,Set2,T,WF)
3546 ; true).
3547
3548 unknown_set(Set) :- var(Set),!.
3549 unknown_set([H|T]) :- (unknown_val(H) -> true ; unknown_set(T)).
3550 unknown_val(Val) :- var(Val),!.
3551 unknown_val(int(X)) :- var(X).
3552 unknown_val(string(X)) :- var(X).
3553 unknown_val(fd(X,_)) :- var(X).
3554 unknown_val((A,B)) :- (unknown_val(A) -> true ; unknown_val(B)).
3555 unknown_val([H|T]) :- (unknown_val(H) -> true ; unknown_set(T)).
3556
3557 :- block intersection0(-,?,?,?), intersection0(?,-,?,?).
3558 intersection0(Set1,Set2,Res,WF) :-
3559 (Set1==[] ; Set2==[]),!, empty_set_wf(Res,WF).
3560 intersection0(Set1,Set2,Res,WF) :- quick_same_value(Set1,Set2),!,
3561 ? equal_object_wf(Res,Set1,inter0_equal,WF).
3562 intersection0(Set1,Set2,Res,WF) :- Res==[],!,
3563 disjoint_sets(Set1,Set2,WF).
3564 intersection0([El1|T1],[El2|T2],Res,WF) :- T1==[],T2==[],
3565 !, % avoid doing intersection_with_interval_closure, especially for nonvar El1,El2 ; see test 2021
3566 equality_objects_wf(El1,El2,EqRes,WF),
3567 kernel_equality:empty_set_test_wf(Res,Empty,WF),
3568 bool_pred:negate(Empty,EqRes),
3569 intersection_pair(EqRes,El1,El2,Res,WF).
3570 intersection0(Set1,Set2,Res,WF) :-
3571 ? intersection_with_interval_closure(Set1,Set2,Inter),!, % avoid expanding intervals at all
3572 equal_object_wf(Inter,Res,intersection0,WF).
3573 intersection0(Set1,Set2,Res,WF) :-
3574 try_expand_and_convert_to_avl_unless_large_wf(Set1,ESet1,WF),
3575 try_expand_and_convert_to_avl_unless_large_wf(Set2,ESet2,WF),
3576 ? intersection1(ESet1,ESet2,Res,WF).
3577
3578 % treat {El1} /\ {El2} = Res
3579 :- block intersection_pair(-,?,?,?,?).
3580 intersection_pair(pred_false,_,_,_,_). % empty_set_test_wf above will set Res to empty_set
3581 ?intersection_pair(pred_true,El1,_El2,Res,WF) :- equal_object_wf(Res,[El1],intersection_pair,WF).
3582
3583 intersection1(Set1,Set2,Res,WF) :- nonvar(Set1),is_custom_explicit_set(Set1,intersection),
3584 intersection_of_explicit_set_wf(Set1,Set2,Inter,WF), !,
3585 ? equal_object_wf(Inter,Res,intersection1,WF).
3586 intersection1(Set1,Set2,Res,WF) :-
3587 (Res==[] ->
3588 disjoint_sets(Set1,Set2,WF)
3589 ;
3590 ? (swap_set(Set1,Set2) -> intersection2(Set2,Set1,Res,WF)
3591 ? ; intersection2(Set1,Set2,Res,WF))
3592 ).
3593
3594 swap_set(Set1,_Set2) :- var(Set1),!.
3595 swap_set(_Set1,Set2) :- var(Set2),!,fail.
3596 %swap_set(_Set1,Set2) :- is_infinite_explicit_set(Set2),!,fail.
3597 swap_set(avl_set(_),Set2) :- \+ functor(Set2,avl_set,2), %Set2 \= avl_set(_),
3598 Set2 \= [],
3599 \+ functor(Set2,closure,3), %Set2 \= closure(_,_,_),
3600 \+ functor(Set2,global_set,1). %Set2 \= global_set(_). % if it was a small closure, intersection_of_explicit_set should have triggered
3601 swap_set(closure(_P,_T,_B),Set2) :- ok_to_swap(Set2). % TO DO: for two closures: we could try and use the smallest one as first argument to intersection2
3602 swap_set(global_set(_GS),Set2) :- ok_to_swap(Set2).
3603
3604 ok_to_swap(global_set(GS)) :- !, \+ is_infinite_or_very_large_explicit_set(global_set(GS),1000000).
3605 ok_to_swap(closure(P,T,B)) :- !,\+ is_infinite_or_very_large_explicit_set(closure(P,T,B),1000000).
3606 ok_to_swap(_).
3607 % maybe also use is_efficient_custom_set as below ??
3608 % what about freetype ?
3609
3610
3611 intersection2(Set1,Set2,Res,WF) :-
3612 expand_custom_set_to_list_wf(Set1,ESet1,_,intersection2,WF),
3613 ? intersection3(ESet1,Set2,Res,WF).
3614 :- block intersection3(-,?,?,?).
3615 ?intersection3([],_,Res,WF) :- empty_set_wf(Res,WF).
3616 intersection3([H|T],Set,Res,WF) :-
3617 (Res==[]
3618 -> not_element_of_wf(H,Set,WF),intersection3(T,Set,Res,WF)
3619 ; membership_test_wf(Set,H,MemRes,WF),
3620 ? intersection4(MemRes,H,T,Set,Res,WF)
3621 ).
3622
3623 :- block intersection4(-,?,?, ?,?,?).
3624 intersection4(pred_true,H,T,Set,Result,WF) :-
3625 ? equal_object_wf([H|Res],Result,intersection4,WF),
3626 ? intersection3(T,Set,Res,WF).
3627 intersection4(pred_false,_H,T,Set,Res,WF) :-
3628 ? intersection3(T,Set,Res,WF).
3629
3630
3631 :- assert_must_succeed(exhaustive_kernel_check_wfdet(disjoint_sets([int(5)],[int(2),int(1),int(3)],WF),WF)).
3632 :- assert_must_succeed(exhaustive_kernel_check_wfdet(disjoint_sets([int(5)],[],WF),WF)).
3633 :- assert_must_succeed(exhaustive_kernel_check_wfdet(disjoint_sets([int(5),int(2)],[int(6),int(1),int(3)],WF),WF)).
3634 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3635 V3 = (string(three),term(floating(1.0))),
3636 exhaustive_kernel_check([commutative],disjoint_sets([V3,V2],[V1])))).
3637 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3638 V3 = (string(three),term(floating(1.0))),
3639 exhaustive_kernel_fail_check([commutative],disjoint_sets([V3,V2],[V1,V3])))).
3640
3641 disjoint_sets(S1,S2) :- init_wait_flags(WF,[disjoint_sets]),
3642 disjoint_sets(S1,S2,WF),
3643 ? ground_wait_flags(WF).
3644
3645 :- block disjoint_sets(-,?,?), disjoint_sets(?,-,?).
3646 disjoint_sets(S1,S2,WF) :-
3647 % TO DO: we could provide faster code for two avl sets / intervals; but probably caught in intersection code above?
3648 ((S1==[];S2==[]) -> true
3649 ; is_interval_closure_or_integerset(S1,Low1,Up1),
3650 nonvar(Low1), nonvar(Up1), % avoid applying it to e.g., {x} /\ 0..2000 = {} from test 1165
3651 is_interval_closure_or_integerset(S2,Low2,Up2), nonvar(Low2), nonvar(Up2) ->
3652 custom_explicit_sets:disjoint_intervals_with_inf(Low1,Up1,Low2,Up2)
3653 ; is_efficient_custom_set(S2) -> expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_1,WF),
3654 % TODO: treat is_infinite_or_symbolic_closure S1
3655 disjoint_sets2(ESet1,S2,WF)
3656 ; is_efficient_custom_set(S1) -> expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_2,WF),
3657 disjoint_sets2(ESet2,S1,WF)
3658 ; expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_3,WF),
3659 %expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_4,WF),
3660 disjoint_sets2(ESet1,S2,WF)
3661 ).
3662
3663 % TO DO: we could infer some constraints on the possible max sizes of the sets
3664 % for finite types (sum of size must be <= size of type)
3665 :- block disjoint_sets2(-,?,?).
3666 disjoint_sets2([],_,_WF).
3667 disjoint_sets2([H|T],S2,WF) :- not_element_of_wf(H,S2,WF), disjoint_sets2(T,S2,WF).
3668
3669 % NOT YET USED: not_disjoint_sets could be used for S /\ R /= {}
3670 :- assert_must_succeed(exhaustive_kernel_check_wfdet(not_disjoint_sets([int(3)],[int(2),int(1),int(3)],WF),WF)).
3671 :- assert_must_succeed(exhaustive_kernel_check_wfdet(not_disjoint_sets([int(1),int(3)],[int(2),int(3)],WF),WF)). % common element not first
3672 :- assert_must_succeed(exhaustive_kernel_check_wfdet(not_disjoint_sets([int(1),int(2),int(3)],[int(3),int(2),int(1)],WF),WF)).
3673 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(not_disjoint_sets([int(1)],[int(2)],WF),WF)). % used to succeed
3674 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(not_disjoint_sets([int(5),int(4)],[int(2),int(1),int(3)],WF),WF)).
3675 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(not_disjoint_sets([int(5)],[],WF),WF)).
3676 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(not_disjoint_sets([],[int(2),int(1)],WF),WF)).
3677 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(not_disjoint_sets([],[],WF),WF)).
3678 :- block not_disjoint_sets(-,?,?), not_disjoint_sets(?,-,?).
3679 not_disjoint_sets(S1,S2,WF) :-
3680 ((S1==[];S2==[]) -> fail
3681 ; is_efficient_custom_set(S2) -> expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_1,WF),
3682 not_disjoint_sets2(ESet1,S2,WF)
3683 ; is_efficient_custom_set(S1) -> expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_2,WF),
3684 not_disjoint_sets2(ESet2,S1,WF)
3685 ; expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_3,WF),
3686 %expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_4,WF),
3687 not_disjoint_sets2(ESet1,S2,WF)
3688 ).
3689
3690 :- block not_disjoint_sets2(-,?,?).
3691 not_disjoint_sets2([],_,_WF) :- fail. % no common element found
3692 not_disjoint_sets2([H|T],S2,WF) :- membership_test_wf(S2,H,MemRes,WF), not_disjoint3(MemRes,T,S2,WF).
3693
3694 :- block not_disjoint3(-,?,?,?).
3695 not_disjoint3(pred_true,_,_,_).
3696 not_disjoint3(pred_false,T,S2,WF) :- not_disjoint_sets2(T,S2,WF).
3697
3698 test_disjoint_wf(S1,S2,DisjRes,WF) :-
3699 intersection(S1,S2,Inter,WF), % TODO: could be done more efficiently, without computing full intersection
3700 empty_set_test_wf(Inter,DisjRes,WF).
3701
3702 :- assert_must_succeed(exhaustive_kernel_check_wfdet(intersection_generalized_wf([[int(3)],[int(2),int(1),int(3)]],[int(3)],unknown,WF),WF)).
3703 :- assert_must_succeed(exhaustive_kernel_check_wfdet(intersection_generalized_wf([[int(3),int(2)],[int(2),int(1),int(3)],[int(4),int(3)]],[int(3)],unknown,WF),WF)).
3704 :- assert_must_succeed((kernel_objects:intersection_generalized_wf(avl_set(node(avl_set(node(fd(1,'Name'),true,1,empty,node(fd(2,'Name'),true,0,empty,empty))),
3705 true,1,empty,node(avl_set(node(fd(2,'Name'),true,1,empty,node(fd(3,'Name'),true,0,empty,empty))),true,0,empty,empty))),
3706 avl_set(node(fd(2,'Name'),true,0,empty,empty)),unknown,_WF))).
3707 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(1)],[int(2)]],Res,unknown,_WF),Res=[])).
3708 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(1)],[int(2),int(1)]],Res,unknown,_WF),
3709 kernel_objects:equal_object(Res,[int(1)]))).
3710 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(1)],X,[int(2),int(3),int(1)]],Res,unknown,_WF),
3711 X = [int(2),int(1)],
3712 kernel_objects:equal_object(Res,[int(1)]))).
3713 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([X,X,[int(2),int(3),int(1)]],Res,unknown,_WF),
3714 X = [int(2),int(1)], kernel_objects:equal_object(Res,[int(1),int(2)]))).
3715 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(2),int(1),int(3)],X,[int(1),int(2)],X],Res,unknown,_WF),
3716 kernel_objects:equal_object(X,Res), X = [int(2),int(1)])).
3717 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([global_set('Name'),X],Res,unknown,_WF),
3718 kernel_objects:equal_object(X,Res), X = [fd(2,'Name'),fd(1,'Name')])).
3719 :- assert_must_fail((kernel_objects:intersection_generalized_wf([[int(1)],[int(2)]],Res,unknown,_WF),(
3720 kernel_objects:equal_object(Res,[_|_])))).
3721 :- assert_must_fail((kernel_objects:intersection_generalized_wf([[int(1)],[int(1)]],Res,unknown,_WF),(Res=[];
3722 kernel_objects:equal_object(Res,[_,_|_])))).
3723 :- assert_must_abort_wf(kernel_objects:intersection_generalized_wf([],_R,unknown,WF),WF).
3724
3725 % code for general_intersection
3726 :- block intersection_generalized_wf(-,?,?,?).
3727 intersection_generalized_wf(SetsOfSets,Res,Span,WF) :-
3728 expand_custom_set_to_list_wf(SetsOfSets,ESetsOfSets,_,intersection_generalized_wf,WF),
3729 intersection_generalized2(ESetsOfSets,Res,Span,WF).
3730
3731 intersection_generalized2([],Res,Span,WF) :- /* Atelier-B manual requires argument to inter to be non-empty */
3732 add_wd_error_set_result('inter applied to empty set','',Res,[],Span,WF).
3733 intersection_generalized2([H|T],Res,_Span,WF) :- intersection_generalized3(T,H,Res,WF).
3734 :- block intersection_generalized3(-,?,?,?).
3735 intersection_generalized3([],SoFar,Res,WF) :- equal_object_optimized_wf(SoFar,Res,intersection_generalized3,WF).
3736 intersection_generalized3([H|T],InterSoFar,Res,WF) :-
3737 intersection(H,InterSoFar,InterSoFar2,WF),
3738 intersection_generalized3(T,InterSoFar2,Res,WF).
3739
3740 :- assert_must_succeed(exhaustive_kernel_check(difference_set([int(3),int(2)],[int(2),int(1),int(3)],[]))).
3741 :- assert_must_succeed(exhaustive_kernel_check(difference_set([int(3),int(2)],[int(2),int(1),int(4)],[int(3)]))).
3742 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3743 V3 = (string(three),term(floating(1.0))),
3744 exhaustive_kernel_check(difference_set([V3,V2,V1],[V1,V3],[V2])))).
3745 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3746 V3 = (string(three),term(floating(1.0))),
3747 exhaustive_kernel_fail_check(difference_set([V3,V2,V1],[V1,V3],[])))).
3748 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[int(1),int(2)]],[]),
3749 kernel_objects:equal_object(SSS,[[int(2),int(1)]]))).
3750 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[int(1),int(2)]],R), kernel_objects:equal_object(R,[]),
3751 kernel_objects:equal_object(SSS,[[int(2),int(1)]]))).
3752 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[fd(1,'Name'),fd(2,'Name')]],R),
3753 kernel_objects:equal_object(R,[]),
3754 kernel_objects:equal_object(SSS,[[fd(2,'Name'),fd(1,'Name')]]))).
3755 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[int(1),int(2)]],[]),
3756 kernel_objects:equal_object(SSS,[[int(1),int(2)]]))).
3757 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[int(1)],_))).
3758 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[int(2)],_))).
3759 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[int(2)],[int(1)]))).
3760 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[],[int(2),int(1)]))).
3761 :- assert_must_succeed((kernel_objects:difference_set([],[int(1),int(2)],[]))).
3762 :- assert_must_succeed((kernel_objects:difference_set(Y,X,Res),X=global_set('Name'),
3763 kernel_objects:equal_object(Res,[]), Y =[fd(1,'Name')])).
3764 :- assert_must_succeed((kernel_objects:difference_set(X,Y,Res),X=global_set('Name'),
3765 kernel_objects:equal_object(Res,[fd(3,'Name'),fd(1,'Name')]), Y =[fd(2,'Name')])).
3766 :- assert_must_fail((kernel_objects:difference_set(X,Y,Res),X=global_set('Name'),
3767 kernel_objects:equal_object(Res,[]), Y =[fd(1,'Name'),fd(2,'Name')])).
3768 :- assert_must_fail((kernel_objects:difference_set(Y,X,Res),X=global_set('Name'),
3769 kernel_objects:equal_object(Res,Y), Y =[fd(1,'Name')])).
3770
3771 % deals with set_subtraction AST node
3772 difference_set(Set1,Set2,Res) :- init_wait_flags(WF),
3773 ? difference_set_wf(Set1,Set2,Res,WF),
3774 ? ground_wait_flags(WF).
3775
3776 :- block difference_set_wf(-,-,?,?).
3777 difference_set_wf(Set1,_,Res,WF) :- Set1==[],!,empty_set_wf(Res,WF).
3778 difference_set_wf(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,difference_set_wf,WF).
3779 ?difference_set_wf(Set1,Set2,Res,WF) :- difference_set1(Set1,Set2,Res,WF).
3780
3781
3782 :- block difference_set1(?,-,-,?), difference_set1(-,?,-,?).
3783 difference_set1(Set1,Set2,Res,WF) :-
3784 nonvar(Set1),is_custom_explicit_set(Set1,difference_set),
3785 difference_of_explicit_set_wf(Set1,Set2,Diff,WF), !,
3786 equal_object_wf(Diff,Res,difference_set1_1,WF).
3787 difference_set1(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,difference_set1_2,WF).
3788 ?difference_set1(Set1,Set2,Res,WF) :- Res==[],!, check_subset_of_wf(Set1,Set2,WF).
3789 difference_set1(Set1,Set2,Res,WF) :-
3790 expand_custom_set_to_list_wf(Set1,ESet1,_,difference_set1,WF),
3791 ? compute_diff(ESet1,Set2,Res,WF),
3792 ? propagate_into2(Res,ESet1,Set2,WF).
3793
3794 :- block compute_diff(-,?,?,?).
3795 ?compute_diff([],_Set2,Res,WF) :- empty_set_wf(Res,WF).
3796 compute_diff([H|T],Set2,Res,WF) :-
3797 ? membership_test_wf(Set2,H,MemRes,WF),compute_diff2(MemRes,H,T,Set2,Res,WF).
3798
3799 :- block compute_diff2(-,?,?,?,?,?).
3800 ?compute_diff2(pred_true,_H,T,Set2,Res,WF) :- compute_diff(T,Set2,Res,WF).
3801 ?compute_diff2(pred_false,H,T,Set2,Res,WF) :- equal_object_wf([H|R2],Res,compute_diff2,WF),
3802 ? compute_diff(T,Set2,R2,WF).
3803
3804 % propagate all elements from one set into another one; do not use for computation; may skip elements ...
3805 /* this version not used at the moment:
3806 :- block propagate_into(-,?,?).
3807 propagate_into(_,Set2,_WF) :- nonvar(Set2),
3808 is_custom_explicit_set(Set2,propagate_into),!. % second set already fully known
3809 propagate_into([],_,_WF) :- !.
3810 propagate_into([H|T],Set,WF) :- !,check_element_of_wf(H,Set,WF), propagate_into(T,Set,WF).
3811 propagate_into(Set1,Set2,WF) :- is_custom_explicit_set(Set1,propagate_into),!,
3812 (is_infinite_explicit_set(Set1) -> true ;
3813 expand_custom_set_to_list(Set1,ESet1), propagate_into(ESet1,Set2,WF)). */
3814
3815 :- block propagate_into2(-,?,?,?).
3816 propagate_into2(_,Set2,_NegSet,_WF) :- nonvar(Set2),
3817 is_custom_explicit_set(Set2,propagate_into),!. % second set already fully known
3818 propagate_into2([],_,_,_WF) :- !.
3819 propagate_into2([H|T],PosSet,NegSet,WF) :- !,
3820 ? check_element_of_wf(H,PosSet,WF),
3821 ? not_element_of_wf(H,NegSet,WF),propagate_into2(T,PosSet,NegSet,WF).
3822 propagate_into2(Set1,PosSet,NegSet,WF) :- is_custom_explicit_set(Set1,propagate_into),!,
3823 (is_infinite_explicit_set(Set1) -> true ;
3824 expand_custom_set_to_list_wf(Set1,ESet1,_,propagate_into2,WF), propagate_into2(ESet1,PosSet,NegSet,WF)).
3825
3826 :- assert_must_succeed(exhaustive_kernel_check_wf(in_difference_set_wf(int(33),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3827 :- block in_difference_set_wf(-,-,-,?).
3828 in_difference_set_wf(A,X,Y,WF) :-
3829 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3830 % symbolic treatment would also make sense when A is nonvar and X var to force A to be in X ?!
3831 !,
3832 ? check_element_of_wf(A,X,WF), not_element_of_wf(A,Y,WF).
3833 in_difference_set_wf(A,X,Y,WF) :-
3834 difference_set_wf(X,Y,Diff,WF),
3835 check_element_of_wf(A,Diff,WF).
3836
3837 treat_arg_symbolically(X) :- var(X),!.
3838 treat_arg_symbolically(global_set(_)).
3839 treat_arg_symbolically(freetype(_)).
3840 treat_arg_symbolically(closure(P,T,B)) :- \+ small_interval(P,T,B).
3841
3842 small_interval(P,T,B) :- is_interval_closure(P,T,B,Low,Up),
3843 integer(Low), integer(Up),
3844 Up-Low < 500. % Magic Constant; TO DO: determine good value
3845
3846
3847 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_difference_set_wf(int(2),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3848 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_difference_set_wf(int(111),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3849 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_difference_set_wf(int(1),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3850
3851 :- block not_in_difference_set_wf(-,-,-,?).
3852 not_in_difference_set_wf(A,X,Y,WF) :-
3853 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3854 !,
3855 % A : (X-Y) <=> A:X & not(A:Y)
3856 % A /: (X-Y) <=> A/: X or A:Y
3857 membership_test_wf(X,A,AX_Res,WF),
3858 (AX_Res==pred_false -> true
3859 ; bool_pred:negate(AX_Res,NotAX_Res),
3860 b_interpreter_check:disjoin(NotAX_Res,AY_Res,pred_true,priority(16384),priority(16384),WF), % better: uese a version that does not do a case split ?! or use last wait flag ?
3861 ? membership_test_wf(Y,A,AY_Res,WF)
3862 ).
3863 not_in_difference_set_wf(A,X,Y,WF) :-
3864 difference_set_wf(X,Y,Diff,WF),
3865 not_element_of_wf(A,Diff,WF).
3866
3867
3868 :- assert_must_succeed(exhaustive_kernel_check_wf(in_intersection_set_wf(int(2),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3869
3870 :- block in_intersection_set_wf(-,-,-,?).
3871 in_intersection_set_wf(A,X,Y,WF) :-
3872 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y)
3873 ; preference(convert_comprehension_sets_into_closures,true)),
3874 (preference(data_validation_mode,true) -> nonvar(X) ; true),
3875 % otherwise we may change enumeration order and enumerate with Y first;
3876 % see private_examples/ClearSy/2019_May/perf_3264/rule_186.mch (but also test 1976);
3877 % we could check if A is ground
3878 !,
3879 Y \== [], % avoid setting up check_element_of for X then
3880 ? check_element_of_wf(A,X,WF), check_element_of_wf(A,Y,WF).
3881 in_intersection_set_wf(A,X,Y,WF) :-
3882 ? intersection(X,Y,Inter,WF),
3883 ? check_element_of_wf(A,Inter,WF).
3884
3885 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_intersection_set_wf(int(3),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3886 :- block not_in_intersection_set_wf(-,-,-,?).
3887 not_in_intersection_set_wf(_A,_X,Y,_WF) :- Y == [], !. % intersection will be empty; avoid analysing X
3888 not_in_intersection_set_wf(A,X,Y,WF) :-
3889 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3890 !,
3891 % A : (X /\ Y) <=> A:X & A:Y
3892 % A /: (X /\ Y) <=> A/:X or A/:Y
3893 membership_test_wf(X,A,AX_Res,WF),
3894 (AX_Res==pred_false -> true
3895 ; bool_pred:negate(AX_Res,NotAX_Res), bool_pred:negate(AY_Res,NotAY_Res),
3896 b_interpreter_check:disjoin(NotAX_Res,NotAY_Res,pred_true,priority(16384),priority(16384),WF),
3897 % better: use a version that does not do a case split ?! or use last wait flag ?
3898 membership_test_wf(Y,A,AY_Res,WF)
3899 ).
3900 not_in_intersection_set_wf(A,X,Y,WF) :-
3901 ? intersection(X,Y,Inter,WF),
3902 not_element_of_wf(A,Inter,WF).
3903
3904 :- assert_must_succeed(exhaustive_kernel_check_wf(in_union_set_wf(int(2),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3905 :- assert_must_succeed(exhaustive_kernel_check_wf(in_union_set_wf(int(33),[int(32),int(2)],[int(2),int(1),int(33)],WF),WF)).
3906
3907 :- block in_union_set_wf(-,-,-,?).
3908 in_union_set_wf(A,X,Y,WF) :-
3909 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3910 % symbolic treatment would also make sense when A is nonvar and X var to force A to be in X ?!
3911 !,
3912 membership_test_wf(X,A,AX_Res,WF),
3913 (AX_Res==pred_true -> true
3914 ; b_interpreter_check:disjoin(AX_Res,AY_Res,pred_true,priority(16384),priority(16384),WF), % better: use a version that does not do a case split ?! or use last wait flag ?
3915 membership_test_wf(Y,A,AY_Res,WF)
3916 ).
3917 in_union_set_wf(A,X,Y,WF) :-
3918 union_wf(X,Y,Union,WF),
3919 ? check_element_of_wf(A,Union,WF).
3920
3921 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_union_set_wf(int(3),[int(32),int(2)],[int(2),int(1),int(33)],WF),WF)).
3922
3923 :- block not_in_union_set_wf(-,-,-,?).
3924 not_in_union_set_wf(A,X,Y,WF) :-
3925 not_element_of_wf(A,X,WF),
3926 not_element_of_wf(A,Y,WF).
3927
3928 % ---------------------
3929
3930
3931 strict_subset_of(X,Y) :-
3932 init_wait_flags(WF,[strict_subset_of]),
3933 strict_subset_of_wf(X,Y,WF),
3934 ground_wait_flags(WF).
3935
3936 :- assert_must_succeed(exhaustive_kernel_check(strict_subset_of_wf([int(3),int(2)],[int(2),int(1),int(3)],_))).
3937 :- assert_must_succeed(exhaustive_kernel_check(strict_subset_of_wf([],[int(2),int(1),int(3)],_))).
3938 :- assert_must_succeed(exhaustive_kernel_check(strict_subset_of_wf([],[ [] ],_))).
3939 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([int(3),int(2),int(1)],[int(2),int(1),int(3)],_))).
3940 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([int(1),int(4)],[int(2),int(1),int(3)],_))).
3941 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([[]],[],_))).
3942 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([],[],_))).
3943 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3944 V3 = (string(three),term(floating(1.0))),
3945 exhaustive_kernel_check(strict_subset_of_wf([V3,V1],[V1,V2,V3],_WF)))).
3946 :- assert_must_succeed((V1 = (string(one),term(floating(1.0))), V2 = (string(one),term(floating(2.0))),
3947 V3 = (string(three),term(floating(1.0))),
3948 exhaustive_kernel_fail_check(strict_subset_of_wf([V3,V2,V1],[V1,V2,V3],_WF)))).
3949 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [int(1)], X=[int(2),int(1)])).
3950 :- assert_must_succeed((kernel_objects:strict_subset_of(Y,X), Y = [int(1)], X=[int(2),int(1)])).
3951 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [], X=[int(2),int(1)])).
3952 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [[int(1),int(2)]], X=[[int(2)],[int(2),int(1)]])).
3953 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [fd(1,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
3954 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [fd(3,'Name'),fd(2,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
3955 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
3956 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [fd(1,'Name'),fd(3,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
3957 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(1)], X=[int(2),int(1)])).
3958 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(1),int(2)], X=[int(2),int(1)])).
3959 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(2)], X=[int(2)])).
3960 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(2)], X=[int(1)])).
3961 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [], X=[int(1)])).
3962
3963
3964 :- use_module(chrsrc(chr_set_membership),[chr_subset_strict/2, chr_not_subset_strict/2]).
3965 :- use_module(chrsrc(chr_integer_inequality),[chr_in_interval/4]).
3966
3967 strict_subset_of_wf(Set1,Set2,WF) :-
3968 (preference(use_chr_solver,true) -> chr_subset_strict(Set1,Set2)
3969 ; Set1 \== Set2), % relevant for test 1326
3970 ? strict_subset_of_wf_aux(Set1,Set2,WF).
3971
3972 %:- block strict_subset_of_wf(-,-,?).
3973 strict_subset_of_wf_aux(Set1,Set2,WF) :- Set1==[],!,not_empty_set_wf(Set2,WF).
3974 %strict_subset_of_wf_aux(Set1,Set2,WF) :- var(Set2),nonvar(Set1), print(subs(Set1,Set2)),nl,fail.
3975 strict_subset_of_wf_aux(Set1,Set2,WF) :- nonvar(Set2), singleton_set(Set2,_),!, empty_set_wf(Set1,WF).
3976 strict_subset_of_wf_aux(Set1,Set2,WF) :-
3977 not_empty_set_wf(Set2,WF),
3978 get_cardinality_powset_wait_flag(Set2,strict_subset_of_wf,WF,_,LWF),
3979 % we could subtract 1 from priority !? (get_cardinality_pow1set_wait_flag)
3980 ? when(((nonvar(LWF),(nonvar(Set1);ground(Set2))) ; (nonvar(Set1),nonvar(Set2)) ),
3981 strict_subset_of_aux_block(Set1,Set2,WF,LWF)).
3982
3983 strict_subset_of_aux_block(Set1,_Set2,_WF,_LWF) :-
3984 Set1==[],
3985 !. % we have already checked that Set2 is not empty
3986 strict_subset_of_aux_block(Set1,Set2,WF,_LWF) :-
3987 nonvar(Set2), is_definitely_maximal_set(Set2),
3988 !,
3989 not_equal_object_wf(Set1,Set2,WF).
3990 strict_subset_of_aux_block(Set1,Set2,WF,_LWF) :- nonvar(Set2), singleton_set(Set2,_),!,
3991 empty_set_wf(Set1,WF).
3992 strict_subset_of_aux_block(Set1,Set2,_WF,_LWF) :-
3993 both_global_sets(Set1,Set2,G1,G2),
3994 !, %(print(check_strict_subset_of_global_sets(G1,G2)),nl,
3995 ? check_strict_subset_of_global_sets(G1,G2).
3996 strict_subset_of_aux_block(Set1,Set2,WF,LWF) :-
3997 var(Set1), nonvar(Set2), Set2=avl_set(_),
3998 check_card_waitflag_less(LWF,4097), % if the number is too big strict_subset_of0 has better chance of working ?!
3999 % without avl_set check test 1003 leads to time out for plavis-TransData_SP_13.prob, with
4000 % memp : seq(STRING) & dom(memp) <<: ( mdp + 1 .. ( mdp + 43 ) )
4001 !,
4002 %non_free(Set1), % as we used to force order, now we use equal_object_wf in gen_strict_subsets and no longer need non_free checking
4003 expand_custom_set_to_list_wf(Set2,ESet2,_,strict_subset_of_wf,WF),
4004 gen_strict_subsets(Set1,ESet2,WF).
4005 strict_subset_of_aux_block(Set1,Set2,WF,LWF) :-
4006 ? strict_subset_of0(Set1,Set2,WF,LWF).
4007 % TO DO (26.10.2014): test 1270 now passes thanks to maximal set check above
4008 % but we should need a better way of ensuring that something like {ssu|ssu<<:POW(elements)} is efficiently computed
4009 % (which it no longer is once the unbound_variable check had been fixed)
4010 % we could also just generally use Set1 <: Set2 & Set1 /= Set2
4011
4012 check_card_waitflag_less(float(Nr),Limit) :- number(Nr), Nr<Limit.
4013
4014 % avoid generating different ordering of the same subset ([1,2] and [2,1] for example), useful for test 642
4015 % Note: remove_element_wf in strict_subset_of2 will create different orders
4016 % for sequence domains gen_strict_subsets uses just the wrong order (deciding to remove 1 first);
4017 % cf test 1003 where not including 1 in domain is bad: memp : seq(STRING) & dom(memp) <<: ( mdp + 1 .. ( mdp + 43 ) )
4018 gen_strict_subsets(T,[H2|T2],WF) :-
4019 not_element_of_wf(H2,T,WF),
4020 gen_subsets(T,T2,WF).
4021 gen_strict_subsets(SubSet,[H2|T2],WF) :-
4022 equal_object_wf([H2|T],SubSet,gen_strict_subsets,WF),
4023 gen_strict_subsets(T,T2,WF).
4024
4025
4026 %:- block strict_subset_of0(-,?,?,?). % required to wait: we know Set2 must be non-empty, but Set1 could be an avl-tree or closure
4027 strict_subset_of0(Set1,Set2,WF,_) :-
4028 subset_of_explicit_set(Set1,Set2,Code,WF),!,
4029 ? call(Code),
4030 not_equal_object_wf(Set1,Set2,WF).
4031 strict_subset_of0(Set1,Set2,WF,LWF) :-
4032 expand_custom_set_to_list_wf(Set1,ESet1,_,strict_subset_of0,WF),
4033 (ESet1==[] -> true %not_empty_set(Set2) already checked above
4034 ? ; is_infinite_explicit_set(Set2) ->
4035 % Set1 is expanded to a list ESet1 and thus finite: it is sufficient to check subset relation
4036 check_subset_of_wf(ESet1,Set2,WF)
4037 ; try_expand_custom_set_wf(Set2,ESet2,strict_subset_of0,WF),
4038 %%try_prop_card_lt(ESet1,ESet2), try_prop_card_gt(ESet2,ESet1),
4039 ? strict_subset_of2(ESet1,[],ESet2,WF,LWF)
4040 ).
4041
4042 :- block strict_subset_of2(-,?,?,?,-).
4043 %strict_subset_of2(S,SoFar,Set2,WF,LWF) :- nl,print(strict_subset_of2(S,SoFar,Set2,WF,LWF)),nl,fail.
4044 strict_subset_of2([],SoFar,RemS,WF,_LWF) :-
4045 ? not_empty_set_wf(RemS,WF), % check remaining set (elements in Set2 not in Set1) is not empty
4046 ? disjoint_sets(RemS,SoFar). % ensure we have not accidentally created Set2 with duplicates
4047 % if a duplicate is in RemS, we may not have a strict_subset (test 2480) !
4048 strict_subset_of2([H|T],SoFar,Set2,WF,LWF) :- var(Set2),!,
4049 equal_cons_wf(Set2,H,Set2R,WF), %was Set2 = [H|Set2R],
4050 not_element_of_wf(H,SoFar,WF),
4051 add_new_element_wf(H,SoFar,SoFar2,WF), %was SoFar2 = [H|SoFar],
4052 ? strict_subset_of2(T,SoFar2,Set2R,WF,LWF).
4053 strict_subset_of2([H|T],SoFar,Set2,WF,LWF) :-
4054 % when_sufficiently_for_member(H,Set2,WF,
4055 ? remove_element_wf(H,Set2,RS2,WF),
4056 ? not_empty_set_wf(RS2,WF),
4057 not_element_of_wf(H,SoFar,WF), /* consistent((H,SoFar)), necessary? */
4058 when((nonvar(T) ; (ground(LWF),ground(RS2))),
4059 (add_new_element_wf(H,SoFar,SoFar2,WF), %SoFar2 = [H|SoFar],
4060 strict_subset_of2(T,SoFar2,RS2,WF,LWF) )).
4061
4062
4063
4064
4065 :- assert_must_succeed(exhaustive_kernel_check(partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ],_))).
4066 :- assert_must_succeed(exhaustive_kernel_check(partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)] ],_))).
4067 :- assert_must_succeed(exhaustive_kernel_check(partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5)],[int(1)] ],_))).
4068 :- assert_must_succeed(exhaustive_kernel_fail_check(partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)], [int(3)] ],_))).
4069 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ], _))).
4070 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2)],[ [int(2)], [int(1)], [] ], _))).
4071 :- assert_must_fail((kernel_objects:partition_wf([int(1),int(2)],[ [int(2)], [int(1),int(2)] ], _))).
4072 :- assert_must_fail((kernel_objects:partition_wf([int(1),int(3)],[ [int(1)], [int(2)] ], _))).
4073 :- assert_must_fail((kernel_objects:partition_wf([int(1),int(2),int(3)],[ [int(1)], [int(2)] ], _))).
4074 :- assert_must_succeed((kernel_objects:partition_wf([int(1)],[S1,S2],_WF), S1=[H|T], S2==[],T==[],H==int(1))).
4075 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2)],[S1,S2],_WF), S1=[H|T], S2=[int(1)],(preferences:preference(use_clpfd_solver,true) -> T==[],H==int(2) ; T=[],H=int(2)))).
4076 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2),int(3)],[S1,S2,S3],_WF), S1=[H2|T], S3=[int(3)],T=[H1|TT],H2=int(2),TT==[],S2==[],H1==int(1))).
4077 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2),int(3)],[[int(1)],X,[int(2)]],_WF),
4078 X==[int(3)])).
4079
4080 :- use_module(kernel_relations,[disjoint_union_generalized_wf/3]).
4081 :- use_module(kernel_tools,[ground_value/1]).
4082 :- block partition_wf(?,-,?).
4083 partition_wf(Set,ListOfSets,WF) :-
4084 ? partition_disj_union_wf(Set,ListOfSets,WF),
4085 all_disjoint(ListOfSets,WF).
4086
4087 % just check that the disjoint union of all sets is equal to Set
4088 partition_disj_union_wf(Set,ListOfSets,WF) :-
4089 ground_value(Set),find_non_ground_set(ListOfSets,NGS,Rest),!,
4090 disjoint_union_generalized_wf(Rest,RestSet,WF),
4091 ? check_subset_of_wf(RestSet,Set,WF), % otherwise this is not a partition of Set
4092 difference_set(Set,RestSet,NGS).
4093 partition_disj_union_wf(Set,ListOfSets,WF) :-
4094 disjoint_union_generalized_wf(ListOfSets,Set,WF).
4095
4096 :- assert_must_succeed((kernel_objects:find_non_ground_set([int(1),int(2),A,int(5)],B,C), B==A,C==[int(1),int(2),int(5)])).
4097 find_non_ground_set([H|T],NG,Rest) :-
4098 (ground_value(H) -> Rest=[H|TR], find_non_ground_set(T,NG,TR)
4099 ; ground_value(T),NG=H, Rest=T).
4100
4101 :- block all_disjoint(-,?).
4102 % check if a list of sets is all disjoint (Note: this is not a set of sets)
4103 all_disjoint([],_WF) :- !.
4104 all_disjoint([H|T],WF) :- !,
4105 all_disjoint_with(T,H,WF),
4106 all_disjoint(T,WF).
4107 all_disjoint(S,WF) :- add_internal_error('Not a list for partition:',all_disjoint(S,WF)),fail.
4108
4109 :- block all_disjoint_with(-,?,?).
4110 all_disjoint_with([],_,_WF).
4111 all_disjoint_with([H|T],Set1,WF) :- disjoint_sets(Set1,H,WF), all_disjoint_with(T,Set1,WF).
4112
4113
4114 % a utility to check for duplicates in set lists and enter debugger
4115 %:- block check_set_for_repetitions(-,?).
4116 %check_set_for_repetitions([],_) :- !.
4117 %check_set_for_repetitions([H|T],Acc) :- !,
4118 % when(ground(H),(member(H,Acc) -> tools:print_bt_message(duplicate(H,Acc)),trace
4119 % ; check_set_for_repetitions(T,[H|Acc]))).
4120 %check_set_for_repetitions(_,_).
4121
4122 :- assert_must_succeed(exhaustive_kernel_fail_check(not_partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ],_))).
4123 :- assert_must_succeed(exhaustive_kernel_fail_check(not_partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)] ],_))).
4124 :- assert_must_succeed(exhaustive_kernel_fail_check(not_partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5)],[int(1)] ],_))).
4125 :- assert_must_succeed(exhaustive_kernel_check(not_partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)], [int(3)] ],_))).
4126 :- assert_must_fail((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ], _))).
4127 :- assert_must_fail((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(2)], [int(1)], [] ], _))).
4128 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(2)], [int(1),int(2)] ], _))).
4129 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(3)],[ [int(1)], [int(2)] ], _))).
4130 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(2),int(3)],[ [int(1)], [int(2)] ], _))).
4131 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(1),int(2)], [int(1),int(2)] ], _))).
4132
4133 not_partition_wf(FullSet,ListOfSets,WF) :-
4134 ? test_partition_wf(FullSet,ListOfSets,pred_false,WF).
4135
4136
4137 :- use_module(b_interpreter_check,[imply_true/2]). % TODO: move to another module
4138 :- block test_partition_wf(?,-,?,?).
4139 test_partition_wf(FullSet,ListOfSets,PredRes,WF) :-
4140 bool_pred:negate(PredRes,NotPredRes),
4141 propagate_partition_true(FullSet,ListOfSets,PredRes,WF),
4142 ? test_partition_wf2(ListOfSets,[],FullSet,PredRes,NotPredRes,WF).
4143
4144 :- block propagate_partition_true(?,?,-,?).
4145 propagate_partition_true(FullSet,ListOfSets,pred_true,WF) :-
4146 % ensure we propagate more info; required for tests 1059, 1060
4147 partition_disj_union_wf(FullSet,ListOfSets,WF).
4148 propagate_partition_true(_,_,pred_false,_).
4149
4150 :- block test_partition_wf2(-,?,?, ?,?,?).
4151 %test_partition_wf2(Sets,SoFar,_,Pred,_,_) :- print_term_summary(test_partition_wf2(Sets,SoFar,Pred)),nl,fail.
4152 ?test_partition_wf2([],ElementsSoFar,FullSet,PredRes,_,WF) :- !, equality_objects_wf(ElementsSoFar,FullSet,PredRes,WF).
4153 test_partition_wf2([Set1|Rest],ElementsSoFar,FullSet,PredRes,NotPredRes,WF) :- !,
4154 expand_custom_set_to_list_wf(Set1,ESet1,_,test_partition_wf2,WF), % TODO: requires finite set; choose instantiated sets first
4155 ? test_partition_wf3(ESet1,ElementsSoFar,ElementsSoFar,Rest,FullSet,PredRes,NotPredRes,WF).
4156 test_partition_wf2(A,E,FS,PR,NPR,WF) :-
4157 add_internal_error('Not a list for partition:',test_partition_wf2(A,E,FS,PR,NPR,WF)),fail.
4158
4159 :- block test_partition_wf3(-,?,?,?, ?,?,?,?).
4160 test_partition_wf3([],_,NewElementsSoFar,OtherSets,FullSet,PredRes,NPR,WF) :-
4161 ? test_partition_wf2(OtherSets,NewElementsSoFar,FullSet,PredRes,NPR,WF). % finished treating this set
4162 test_partition_wf3([H|T],ElementsSoFar,NewElementsSoFar,OtherSets,FullSet,PredRes,NotPredRes,WF) :-
4163 imply_true(MemRes,NotPredRes), % if not disjoint (MemRes=pred_true) then we do not have a partition
4164 membership_test_wf(ElementsSoFar,H,MemRes,WF),
4165 ? test_partition_wf4(MemRes,H,T,ElementsSoFar,NewElementsSoFar,OtherSets,FullSet,PredRes,NotPredRes,WF).
4166
4167 :- block test_partition_wf4(-,?,?,?,?, ?,?,?,?,?).
4168 test_partition_wf4(pred_true,_,_,_,_,_,_,pred_false,_,_). % Not disjoint
4169 test_partition_wf4(pred_false,H,T,ElementsSoFar,NewElementsSoFar,OtherSets,FullSet,PredRes,NotPredRes,WF) :-
4170 add_element_wf(H,NewElementsSoFar,NewElementsSoFar2,WF), % we could also already check whether H in FullSet or not
4171 %(PredRes==pred_true -> check_element_of_wf(H,FullSet,WF) ; true),
4172 ? test_partition_wf3(T,ElementsSoFar,NewElementsSoFar2,OtherSets,FullSet,PredRes,NotPredRes,WF).
4173
4174
4175
4176 :- assert_must_succeed(exhaustive_kernel_succeed_check(check_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1),int(3)]))).
4177 :- assert_must_succeed(exhaustive_kernel_succeed_check(check_subset_of([int(1),int(2),int(5)],[int(2),int(5),int(1)]))).
4178 :- assert_must_succeed(exhaustive_kernel_fail_check(check_subset_of([int(1),int(3),int(5)],[int(2),int(5),int(1)]))).
4179 :- assert_must_succeed((kernel_objects:power_set(global_set('Name'),PS),kernel_objects:check_subset_of(X,PS),
4180 kernel_objects:equal_object(X,[[fd(2,'Name'),fd(1,'Name')]]))).
4181 :- assert_must_succeed(findall(X,kernel_objects:check_subset_of(X,[[int(1),int(2)],[]]),[_1,_2,_3,_4])).
4182 :- assert_must_succeed((kernel_objects:check_subset_of(X,[[int(1),int(2)],[]]),
4183 nonvar(X),
4184 kernel_objects:equal_object(X,[[int(2),int(1)]]))).
4185 :- assert_must_succeed((kernel_objects:check_subset_of_wf(Y,X,_WF), Y = [fd(1,'Name')],
4186 nonvar(X),X=[H|T], var(T), H==fd(1,'Name'), X=Y)).
4187 :- assert_must_succeed((kernel_objects:check_subset_of(Y,X), Y = [fd(1,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4188 :- assert_must_succeed((kernel_objects:check_subset_of(Y,X), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4189 :- assert_must_succeed((kernel_objects:check_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4190 :- assert_must_succeed((kernel_objects:sample_closure(C),kernel_objects:check_subset_of(C,global_set('NAT')))).
4191 :- assert_must_succeed((kernel_objects:check_subset_of(global_set('NAT'),global_set('NAT')))).
4192 :- assert_must_succeed((kernel_objects:check_subset_of(global_set('NAT'),global_set('NATURAL')))).
4193 :- assert_must_fail((kernel_objects:check_subset_of(global_set('NAT'),global_set('NATURAL1')))).
4194 :- assert_must_fail((kernel_objects:check_subset_of(global_set('NAT'),global_set('NAT1')))).
4195 :- assert_must_fail((kernel_objects:check_subset_of(X,Y), Y = [fd(1,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4196 /* TO DO: add special treatment for closures and type checks !! */
4197
4198 check_subset_of(Set1,Set2) :- init_wait_flags(WF),
4199 ? check_subset_of_wf(Set1,Set2,WF),
4200 ? ground_wait_flags(WF).
4201
4202 check_finite_subset_of_wf(Set1,Set2,WF) :-
4203 check_subset_of_wf(Set1,Set2,WF),
4204 is_finite_set_wf(Set1,WF).
4205
4206 :- block check_subset_of_wf(-,-,?).
4207 check_subset_of_wf(Set1,Set2,WF) :-
4208 (both_global_sets(Set1,Set2,G1,G2)
4209 ? -> check_subset_of_global_sets(G1,G2)
4210 ? ; check_subset_of0(Set1,Set2,WF)
4211 ).
4212
4213 both_global_sets(S1,S2,G1,G2) :- nonvar(S1),nonvar(S2),
4214 is_global_set_or_interval(S1,G1), is_global_set_or_interval(S2,G2).
4215
4216 % check if we have a global set or interval
4217 % is_global_set_or_interval([],R) :- !, R=interval(0,-1). % useful ???
4218 is_global_set_or_interval(global_set(G1),R) :- !,
4219 (custom_explicit_sets:get_integer_set_interval(G1,Low,Up) -> R=interval(Low,Up) ; R=G1).
4220 is_global_set_or_interval(Closure,R) :-
4221 custom_explicit_sets:is_interval_closure_or_integerset(Closure,Low,Up),!,
4222 R=interval(Low,Up).
4223
4224
4225 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(0,0),interval(minus_inf,inf))).
4226 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(-200,1000),interval(minus_inf,inf))).
4227 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(10,1000),interval(0,inf))).
4228 :- assert_must_fail(kernel_objects:check_subset_of_global_sets(interval(-10,1000),interval(0,inf))).
4229 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(0,inf),interval(0,inf))).
4230 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(0,inf),interval(minus_inf,inf))).
4231 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(1,inf),interval(0,inf))).
4232 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(1,inf),interval(minus_inf,inf))).
4233
4234 % to do: also extend to allow intervals with inf/minus_inf
4235 check_subset_of_global_sets(X,Y) :- (var(X) ; var(Y)),
4236 add_internal_error('Illegal call: ',check_subset_of_global_sets(X,Y)),fail.
4237 check_subset_of_global_sets(interval(Low1,Up1),interval(Low2,Up2)) :- !,
4238 ? interval_subset(Low1,Up1,Low2,Up2).
4239 check_subset_of_global_sets(X,X) :- !. % both args must be atomic and ground (global set names)
4240 % BUT WE COULD HAVE {x|x>0} <: NATURAL1 ? interval(0,inf) <: NATURAL1
4241 check_subset_of_global_sets(X,Y) :- check_strict_subset_of_global_sets(X,Y).
4242
4243 % To do: perform some treatment of inf, minus_inf values here <----
4244 interval_subset(Low1,Up1,Low2,Up2) :-
4245 (var(Low1) ; var(Up1)), % otherwise we can use code below
4246 finite_interval(Low1,Up1), finite_interval(Low2,Up2), % inf can appear as term; but only directly not later
4247 !,
4248 % Maybe to do: try to avoid CLPFD overflows if possible; pass WF to force case distinction between empty/non-empty intervals
4249 clpfd_in_interval(Low1,Up1,Low2,Up2).
4250 interval_subset(Low1,Up1,Low2,Up2) :-
4251 ? interval_subset_aux(Low1,Up1,Low2,Up2).
4252
4253 % check if we have a finite interval (fails for inf/minus_inf terms)
4254 finite_interval(Low1,Up1) :- (var(Low1) -> true ; integer(Low1)), (var(Up1) -> true ; integer(Up1)).
4255 finite_val(LowUp) :- (var(LowUp) -> true ; integer(LowUp)).
4256
4257
4258
4259 % assert Low1..Up1 <: Low2..Up2
4260 clpfd_in_interval(Low1,Up1,Low2,Up2) :-
4261 (preferences:preference(use_chr_solver,true)
4262 -> chr_in_interval(Low1,Up1,Low2,Up2) ; true),
4263 % TO DO: improve detection of Low1 #=< Up1; maybe outside of CHR ?; we could also add a choice point here
4264 % example: p..q <: 0..25 & p<q -> should constrain p,q to p:0..24 & q:1..25
4265 clpfd_interface:post_constraint2((Low1 #=< Up1) #=> ((Low2 #=< Low1) #/\ (Up1 #=< Up2)),Posted),
4266 (Posted==true -> true ; interval_subset_aux(Low1,Up1,Low2,Up2)).
4267
4268 :- block interval_subset_aux(-,?,?,?), interval_subset_aux(?,-,?,?).
4269 interval_subset_aux(Low1,Up1,_,_) :- safe_less_than_with_inf(Up1,Low1). %Set 1 is empty.
4270 interval_subset_aux(Low1,Up1,Low2,Up2) :-
4271 safe_less_than_equal_with_inf(Low1,Up1), % Set 1 is not empty
4272 safe_less_than_equal_with_inf_clpfd(Low2,Low1), safe_less_than_equal_with_inf_clpfd(Up1,Up2). % may call CLPFD
4273
4274 % a version of safe_less_than which allows minus_inf and inf, but only if those terms appear straightaway at the first call
4275 % assumes any variable will only be bound to a number
4276 safe_less_than_with_inf(X,Y) :- (X==Y ; X==inf ; Y==minus_inf), !,fail.
4277 safe_less_than_with_inf(X,Y) :- (X==minus_inf ; Y==inf), !.
4278 safe_less_than_with_inf(X,Y) :- safe_less_than(X,Y).
4279
4280 safe_less_than_with_inf_clpfd(X,Y) :- (X==Y ; X==inf ; Y==minus_inf), !,fail.
4281 safe_less_than_with_inf_clpfd(X,Y) :- (X==minus_inf ; Y==inf), !.
4282 safe_less_than_with_inf_clpfd(X,Y) :- less_than_direct(X,Y). % this can also call CLPFD
4283
4284 % a version of safe_less_than_equal which allows minus_inf and inf, but only if those terms appear straightaway at the first call
4285 safe_less_than_equal_with_inf(X,Y) :- X==Y,!.
4286 safe_less_than_equal_with_inf(X,Y) :- (X==inf ; Y==minus_inf), !,fail.
4287 safe_less_than_equal_with_inf(X,Y) :- (X==minus_inf ; Y==inf), !.
4288 safe_less_than_equal_with_inf(X,Y) :- safe_less_than_equal(X,Y).
4289
4290 safe_less_than_equal_with_inf_clpfd(X,Y) :- X==Y,!.
4291 safe_less_than_equal_with_inf_clpfd(X,Y) :- (X==inf ; Y==minus_inf), !,fail.
4292 safe_less_than_equal_with_inf_clpfd(X,Y) :- (X==minus_inf ; Y==inf), !.
4293 safe_less_than_equal_with_inf_clpfd(X,Y) :- less_than_equal_direct(X,Y). % this can also call CLPFD
4294
4295 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,2),interval(1,3))).
4296 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,1),interval(1,2))).
4297 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,1),interval(0,1))).
4298 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(2,1),interval(33,34))).
4299 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(3,1),interval(4,2))).
4300 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(3,1),interval(2,1))).
4301 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(1,2),interval(1,2))).
4302 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(1,2),interval(2,3))).
4303 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(2,3),interval(1,2))).
4304 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(0,1000),interval(0,inf))).
4305 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,1000),interval(1,inf))).
4306 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(-200,1000),interval(minus_inf,inf))).
4307 % for any other term we have global enumerated or deferred sets: they cannot be a strict subset of each other
4308 check_strict_subset_of_global_sets('FLOAT','REAL').
4309 check_strict_subset_of_global_sets(interval(Low1,Up1),interval(Low2,Up2)) :-
4310 ? check_strict_subset_intervals(Low1,Up1,Low2,Up2).
4311
4312 check_strict_subset_intervals(Low1,Up1,Low2,Up2) :-
4313 safe_less_than_equal_with_inf_clpfd(Low2,Up2), % Low2..Up2 not empty
4314 ? check_strict_subset_intervals1(Low1,Up1,Low2,Up2).
4315
4316 check_strict_subset_intervals1(Low1,Up1,Low2,Up2) :- % we cannot have inf as term (yet) here
4317 %preferences:preference(use_clpfd_solver,true),
4318 (var(Low1) ; var(Up1)),
4319 finite_interval(Low1,Up1), finite_interval(Low2,Up2),
4320 !,
4321 clpfd_interface:post_constraint2((Low1 #=< Up1) #=> ((Low2 #=< Low1) #/\ (Up1 #=< Up2) #/\ (Low1 #\= Low2 #\/ Up1 #\= Up2)),Posted),
4322 (Posted==true -> true ; check_strict_subset_intervals2(Low1,Up1,Low2,Up2)).
4323 ?check_strict_subset_intervals1(Low1,Up1,Low2,Up2) :- check_strict_subset_intervals2(Low1,Up1,Low2,Up2).
4324
4325 :- block check_strict_subset_intervals2(-,?,?,?),check_strict_subset_intervals2(?,-,?,?),
4326 check_strict_subset_intervals2(?,?,-,?).
4327 check_strict_subset_intervals2(Low1,Up1,_,_) :- safe_less_than_with_inf(Up1,Low1). % interval 1 empty
4328 check_strict_subset_intervals2(Low1,Up1,Low2,Up2) :-
4329 safe_less_than_equal_with_inf(Low1,Up1), % interval 1 not empty
4330 ( safe_less_than_with_inf(Low2,Low1), safe_less_than_equal_with_inf_clpfd(Up1,Up2)
4331 ;
4332 Low1=Low2,safe_less_than_with_inf_clpfd(Up1,Up2)
4333 ).
4334
4335 :- use_module(custom_explicit_sets,[is_definitely_maximal_set/1,singleton_set/2]).
4336 :- use_module(kernel_tools,[ground_value_check/2, quick_same_value/2]).
4337
4338 check_subset_of0(Set1,_Set2,_WF) :- Set1==[],!.
4339 check_subset_of0(Set1,Set2,WF) :- Set2==[],
4340 %nonvar(Set2),Set2=[], %var(Set1),
4341 !,
4342 empty_set_wf(Set1,WF).
4343 check_subset_of0(_Set1,Set2,_WF) :-
4344 nonvar(Set2),is_definitely_maximal_set(Set2),!.
4345 %singleton
4346 check_subset_of0(Set1,Set2,_) :-
4347 quick_same_value(Set1,Set2), % important for e.g. test 1948 for closures with different info fields
4348 !.
4349 check_subset_of0(Set1,Set2,WF) :- custom_explicit_sets:singleton_set(Set1,El),!,
4350 ? check_element_of_wf(El,Set2,WF).
4351 check_subset_of0(Set1,Set2,WF) :- % Note: two intervals are treated in check_subset_of_global_sets
4352 subset_of_explicit_set(Set1,Set2,Code,WF),!,
4353 ? call(Code).
4354 check_subset_of0(Set1,Set2,WF) :- nonvar(Set1),!,
4355 get_cardinality_powset_wait_flag(Set2,check_subset_of0,WF,_,LWF),
4356 expand_custom_set_to_list_wf(Set1,ESet1,_,check_subset_of1,WF),
4357 try_expand_and_convert_to_avl_unless_large_wf(Set2,ESet2,WF),
4358 % b_interpreter_components:observe_instantiation(ESet1,'ESet1',ESet1),
4359 ? check_subset_of2(ESet1,[],ESet2,WF,LWF,none).
4360 check_subset_of0(Set1,Set2,WF) :-
4361 is_wait_flag_info(WF,wfx_no_enumeration),!,
4362 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_).
4363 check_subset_of0(Set1,Set2,WF) :-
4364 % DO we need LWF if Set1=avl_set(_) ??
4365 get_cardinality_powset_wait_flag(Set2,check_subset_of0,WF,_Card,LWF),
4366 ground_value_check(Set2,GS2),
4367 ? check_subset_of0_lwf(Set1,Set2,WF,LWF,GS2).
4368
4369 :- use_module(custom_explicit_sets,[is_infinite_or_very_large_explicit_set/2]).
4370
4371 :- block check_subset_of0_lwf(-,?,?,-,?),check_subset_of0_lwf(-,?,?,?,-).
4372 check_subset_of0_lwf(Set1,_Set2,_WF,_LWF,_GS2) :- Set1==[],!.
4373 %check_subset_of0_lwf(Set1,Set2,WF,_LWF) :- Set2==[],!, % can never trigger as Set2 was already nonvar
4374 % empty_set_wf(Set1,WF).
4375 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_GS2) :- custom_explicit_sets:singleton_set(Set1,El),!,
4376 ? check_element_of_wf(El,Set2,WF).
4377 check_subset_of0_lwf(Set1,Set2,_WF,_,_) :-
4378 both_global_sets(Set1,Set2,G1,G2),!, % may now succeed compared to same check above, as Set1/Set2 now instantiated
4379 check_subset_of_global_sets(G1,G2).
4380 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_GS2) :- % Note: two intervals are treated in check_subset_of_global_sets
4381 nonvar(Set1), % otherwise we have already checked this code above
4382 subset_of_explicit_set(Set1,Set2,Code,WF),!,
4383 call(Code).
4384 check_subset_of0_lwf(Set1,Set2,WF,LWF,_GS2) :-
4385 (nonvar(Set1) ; nonvar(Set2),dont_expand_this_explicit_set(Set2)),
4386 !,
4387 expand_custom_set_to_list_wf(Set1,ESet1,_,check_subset_of1,WF),
4388 try_expand_and_convert_to_avl_unless_large_wf(Set2,ESet2,WF),
4389 % b_interpreter_components:observe_instantiation(ESet1,'ESet1',ESet1),
4390 ? check_subset_of2(ESet1,[],ESet2,WF,LWF,none).
4391 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_GS2) :-
4392 expand_custom_set_to_list_wf(Set2,ESet2,_,check_subset_of0_lwf,WF), % Set2 is ground
4393 % THIS WILL ENUMERATE, for something like dom(f) <: SET this is problematic, as information cannot be used
4394 % hence we use wfx_no_enumeration above
4395 %non_free(Set1), % we used to enumerate Set1 in a specific order ESet2; now we use equal_object_wf and we no longer need to mark Set1 as non-free ?
4396 ? gen_subsets(Set1,ESet2,WF).
4397
4398 :- block check_subset_of2(-,?,?,?,-, ?).
4399 check_subset_of2([],_SoFar,_Set2,_WF,_LWF,_Last).
4400 check_subset_of2(HT,SoFar,Set2,WF,LWF,Last) :-
4401 (var(HT), nonvar(Set2), Set2 = avl_set(AVL)
4402 -> % the value is chosen by the enumerator
4403 ? custom_explicit_sets:safe_avl_member(H,AVL),
4404 % this forces H to be ground; if Last /= none then it will be ground
4405 (Last==none -> true ; Last @< H),
4406 % TO DO: we could write a safe_avl_member_greater_than(H,Last,AVL)
4407 not_element_of_wf(H,SoFar,WF),
4408 NewLast=H,
4409 HT = [H|T]
4410 ; % the value may have been chosen by somebody else or will not be enumerated in order below
4411 HT = [H|T],
4412 not_element_of_wf(H,SoFar,WF),
4413 ? check_element_of_wf_lwf(H,Set2,WF,LWF),
4414 %check_element_of_wf(H,Set2,WF),
4415
4416 NewLast = Last
4417 ),
4418 ? check_subset_of3(H,T,SoFar,Set2,WF,LWF,NewLast).
4419
4420 % TO DO: write specific subsets code for avl_set(Set2) + try expand when becomes ground; merge with enumerate_tight_set ,...
4421 % TO DO: ensure that it also works with global_set(T) instead of avl_set(_) or with interval closures
4422
4423
4424 :- block check_subset_of3(?,-,-,?,?,-,?), check_subset_of3(?,-,?,-,?,-,?), check_subset_of3(?,-,-,-,?,?,?).
4425 check_subset_of3(_,T,_,_Set2,_WF,_LWF,_) :- T==[],!.
4426 check_subset_of3(H,T,SoFar,Set2,WF,LWF,Last) :- var(T),!,
4427 % Sofar, Set2 and LWF must be set
4428 ? when((nonvar(T);(ground(Set2),ground(H),ground(SoFar))),
4429 (T==[] -> true
4430 ; add_new_element_wf(H,SoFar,SoFar2,WF), %SoFar2 = [H|SoFar],
4431 check_subset_of2(T,SoFar2,Set2,WF,LWF,Last))).
4432 check_subset_of3(H,T,SoFar,Set2,WF,LWF,Last) :-
4433 % T must be set and not equal to []
4434 T = [H2|T2],
4435 add_new_element_wf(H,SoFar,SoFar2,WF), %SoFar2 = [H|SoFar],
4436 %check_subset_of2(T,SoFar2,Set2,WF,LWF))),
4437 ? check_element_of_wf(H2,Set2,WF),
4438 not_element_of_wf(H2,SoFar2,WF),
4439 ? check_subset_of3(H2,T2,SoFar2,Set2,WF,LWF,Last).
4440
4441
4442 :- block gen_subsets(?,-,?).
4443 gen_subsets([],_,_).
4444 gen_subsets(SubSet,Set,WF) :-
4445 ? ordered_delete(DH,Set,NewSet),
4446 ? equal_object_wf([DH|T],SubSet,gen_subsets,WF),
4447 ? gen_subsets(T,NewSet,WF).
4448
4449 % note: this is not select/3
4450 ordered_delete(H,[H|T],T).
4451 ?ordered_delete(H,[_|T],R) :- ordered_delete(H,T,R).
4452
4453
4454 :- assert_must_succeed(exhaustive_kernel_check_wf(check_finite_non_empty_subset_of_wf([int(1),int(5)], [int(2),int(5),int(1),int(3)],WF),WF)).
4455 :- assert_must_succeed(exhaustive_kernel_check_wf(check_finite_non_empty_subset_of_wf([int(1),int(5)], [int(5),int(1)],WF),WF)).
4456 check_finite_non_empty_subset_of_wf(Set1,Set2,WF) :-
4457 ? check_non_empty_subset_of_wf(Set1,Set2,WF),
4458 is_finite_set_wf(Set1,WF).
4459
4460 :- assert_must_succeed(exhaustive_kernel_check_wf(check_non_empty_subset_of_wf([int(1),int(5)], [int(2),int(5),int(1),int(3)],WF),WF)).
4461 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(check_non_empty_subset_of_wf([int(2)], [int(5),int(1)],WF),WF)).
4462 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(check_non_empty_subset_of_wf([], [int(1)],WF),WF)).
4463
4464 check_non_empty_subset_of_wf(S1,S2,WF) :- not_empty_set_wf(S1,WF),
4465 ? check_subset_of_wf(S1,S2,WF).
4466
4467 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_subset_of([int(1),int(2),int(5)], [int(2),int(4),int(1),int(3)]))).
4468 :- assert_must_succeed(exhaustive_kernel_fail_check(not_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1),int(3)]))).
4469 :- assert_must_succeed((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name')], X=global_set('Name'))).
4470 :- assert_must_succeed((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name')], X=[fd(2,'Name')])).
4471 :- assert_must_succeed((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name')], X=[fd(1,'Name'),fd(2,'Name')])).
4472 :- assert_must_fail((kernel_objects:not_subset_of(Y,X), Y = [fd(1,'Name'),fd(3,'Name')], X=global_set('Name'))).
4473 :- assert_must_fail((kernel_objects:not_subset_of(Y,X), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4474 :- assert_must_fail((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4475 :- assert_must_fail((kernel_objects:not_subset_of(global_set('NAT'),global_set('NAT')))).
4476 :- assert_must_succeed((kernel_objects:not_subset_of(global_set('NAT'),global_set('NAT1')))).
4477
4478
4479 not_subset_of(Set1,Set2) :- init_wait_flags(WF),
4480 not_subset_of_wf(Set1,Set2,WF),
4481 ground_wait_flags(WF).
4482
4483 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf([int(1),int(2),int(5)], [int(2),int(4),int(1),int(3)],_WF))).
4484 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf(global_set('NATURAL'), global_set('INTEGER'),_WF))).
4485 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf(global_set('INTEGER'), global_set('INTEGER'),_WF))).
4486 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf([int(1)], [],_WF))).
4487
4488 :- block not_finite_subset_of_wf(-,?,?).
4489 not_finite_subset_of_wf(Set1,Set2,WF) :- test_finite_set_wf(Set1,Finite,WF),
4490 not_finite_subset_of_wf_aux(Finite,Set1,Set2,WF).
4491 :- block not_finite_subset_of_wf_aux(-,?,?,?).
4492 not_finite_subset_of_wf_aux(pred_false,_Set1,_Set2,_WF).
4493 not_finite_subset_of_wf_aux(pred_true,Set1,Set2,WF) :- not_subset_of_wf(Set1,Set2,WF).
4494
4495 :- block not_subset_of_wf(-,?,?).
4496 not_subset_of_wf([],_,_WF) :- !, fail.
4497 not_subset_of_wf(Set1,Set2,WF) :- Set2==[],!, not_empty_set_wf(Set1,WF).
4498 not_subset_of_wf(Set1,Set2,WF) :-
4499 (both_global_sets(Set1,Set2,G1,G2) % also catches intervals
4500 -> check_not_subset_of_global_sets(G1,G2)
4501 ? ; not_subset_of_wf1(Set1,Set2,WF)
4502 ).
4503 not_subset_of_wf1(_Set1,Set2,_WF) :-
4504 nonvar(Set2), is_definitely_maximal_set(Set2),!,fail.
4505 not_subset_of_wf1(Set1,Set2,_WF) :- quick_same_value(Set1,Set2),
4506 !, fail.
4507 not_subset_of_wf1(Set1,Set2,WF) :- custom_explicit_sets:singleton_set(Set1,El),!,
4508 ? not_element_of_wf(El,Set2,WF).
4509 ?not_subset_of_wf1(Set1,Set2,WF) :- not_subset_of_explicit_set(Set1,Set2,Code,WF),!,
4510 call(Code).
4511 not_subset_of_wf1(Set1,Set2,WF) :-
4512 expand_custom_set_to_list_wf(Set1,ESet1,_,not_subset_of_wf1,WF),
4513 ? not_subset_of2(ESet1,Set2,WF).
4514
4515
4516 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(0,2),interval(1,3))).
4517 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(1,2),interval(0,-1))).
4518 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(1,2),interval(4,3))).
4519 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(1,3))).
4520 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(1,9000),interval(2,9999))).
4521 :- assert_must_succeed((kernel_objects:check_not_subset_of_global_sets(interval(X2,X4),interval(1,3)),
4522 X2=2, X4=4)).
4523 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(1,4))).
4524 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(2,4))).
4525 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(0,10))).
4526 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(0,2),interval(1,inf))).
4527 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(-1,2),interval(0,inf))).
4528 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,2),interval(1,inf))).
4529 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(0,2),interval(0,inf))).
4530 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(-1,2),interval(minus_inf,inf))).
4531 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(0,inf),interval(1,inf))).
4532 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(minus_inf,inf),interval(1,inf))).
4533 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(minus_inf,inf),interval(0,inf))).
4534 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,inf),interval(minus_inf,inf))).
4535 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,inf),interval(1,inf))).
4536 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,inf),interval(0,inf))).
4537 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(0,inf),interval(0,inf))).
4538
4539 :- block check_not_subset_of_global_sets(-,?), check_not_subset_of_global_sets(?,-).
4540 check_not_subset_of_global_sets(interval(Low1,Up1),G2) :- !,
4541 safe_less_than_equal_with_inf_clpfd(Low1,Up1), % Set 1 is not empty; otherwise it will always be a subset
4542 not_subset_interval_gs_aux(G2,Low1,Up1).
4543 check_not_subset_of_global_sets(G1,G2) :-
4544 \+ check_subset_of_global_sets(G1,G2).
4545
4546 not_subset_interval_gs_aux(interval(Low2,Up2),Low1,Up1) :-
4547 finite_interval(Low1,Up1), finite_interval(Low2,Up2),
4548 !,
4549 % post_constraint2((Low1 #<Low2 #\/ Up1 #> Up2 #\/ Up2 #< Low1),Posted), %% X #<100 #\/ X#<0. does not constraint X ! but X #<max(100,0) does
4550 post_constraint2((Low1 #<Low2 #\/ Up2 #< max(Up1,Low1)),Posted),
4551 (Posted==true -> true ; not_interval_subset(Low1,Up1,Low2,Up2)).
4552 not_subset_interval_gs_aux(interval(Low2,Up2),Low1,Up1) :- !, not_interval_subset(Low1,Up1,Low2,Up2).
4553 not_subset_interval_gs_aux(GS2,Low1,Up1) :-
4554 when((nonvar(Low1),nonvar(Up1)), \+ check_subset_of_global_sets(interval(Low1,Up1),GS2)).
4555
4556 not_interval_subset(Val1,Up1,Low2,Up2) :- var(Val1), Val1==Up1,
4557 !, % better propagation for singleton set
4558 (Up2==inf -> Low2\==minus_inf, less_than_direct(Val1,Low2)
4559 ; Low2==minus_inf -> less_than_direct(Up2,Val1)
4560 ; not_in_nat_range(int(Val1),int(Low2),int(Up2))).
4561 not_interval_subset(Low1,_,Low2,Up2) :- Up2==inf, finite_val(Low2), finite_val(Low1),
4562 % typical case x..y /<: NATURAL <==> x < 0
4563 !,
4564 less_than_direct(Low1,Low2).
4565 not_interval_subset(_,Up1,Low2,Up2) :- Low2==minus_inf, finite_val(Up2), finite_val(Up1),
4566 % covers x..y /<: {x|x<=0} <==> y > 0
4567 !,
4568 less_than_direct(Up2,Up1).
4569 not_interval_subset(Low1,Up1,Low2,Up2) :- not_interval_subset_block(Low1,Up1,Low2,Up2).
4570 :- block not_interval_subset_block(-,?,?,?), not_interval_subset_block(?,-,?,?),
4571 not_interval_subset_block(?,?,-,?), not_interval_subset_block(?,?,?,-).
4572 not_interval_subset_block(Low1,Up1,Low2,Up2) :- % this could be decided earlier, e.g. 1..n /<: 1..inf is false
4573 ? \+ interval_subset(Low1,Up1,Low2,Up2).
4574
4575
4576 :- block not_subset_of2(-,?,?).
4577 not_subset_of2([H|T],Set2,WF) :-
4578 (T==[]
4579 ? -> not_element_of_wf(H,Set2,WF)
4580 ; membership_test_wf(Set2,H,MemRes,WF),
4581 propagate_empty_set_to_pred_false(T,MemRes), % if T becomes empty, we know that H must not be in Set2
4582 ? not_subset_of3(MemRes,T,Set2,WF)
4583 ).
4584
4585 :- block not_subset_of3(-,?,?,?).
4586 not_subset_of3(pred_false,_T,_Set2,_WF).
4587 ?not_subset_of3(pred_true,T,Set2,WF) :- not_subset_of2(T,Set2,WF).
4588
4589 :- block propagate_empty_set_to_pred_false(-,-).
4590 propagate_empty_set_to_pred_false(X,PredRes) :- X==[],!,PredRes=pred_false.
4591 propagate_empty_set_to_pred_false(_,_).
4592
4593 :- assert_must_succeed(exhaustive_kernel_check_wf(not_both_subset_of([int(1),int(2),int(5)], []
4594 ,[int(2),int(4),int(1),int(3)],[],WF),WF)).
4595 :- assert_must_succeed(exhaustive_kernel_check_wf(not_both_subset_of([int(1),int(2),int(5)], [int(3)],
4596 [int(2),int(5),int(1),int(3)],[int(1),int(4)],WF),WF)).
4597
4598 not_both_subset_of(Set1A,Set1B, Set2A,Set2B, WF) :-
4599 kernel_equality:subset_test(Set1A,Set2A,Result,WF), % not yet implemented ! % TODO ! -> sub_set,equal,super_set
4600 not_both_subset_of_aux(Result,Set1B,Set2B,WF).
4601
4602 :- block not_both_subset_of_aux(-,?,?,?).
4603 not_both_subset_of_aux(pred_false,_Set1B,_Set2B,_WF).
4604 not_both_subset_of_aux(pred_true,Set1B,Set2B,WF) :-
4605 not_subset_of_wf(Set1B,Set2B,WF).
4606
4607 /***********************************/
4608 /* not_strict_subset_of(Set1,Set2) */
4609 /* Set1 /<<: Set2 */
4610 /**********************************/
4611
4612
4613 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_strict_subset_of([int(1),int(2),int(5)], [int(2),int(4),int(1),int(3)]))).
4614 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_strict_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1)]))).
4615 :- assert_must_succeed(exhaustive_kernel_fail_check(not_strict_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1),int(3)]))).
4616 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [int(1)], X=[int(2),int(1)])).
4617 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [], X=[int(2),int(1)])).
4618 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [[int(1),int(2)]], X=[[int(2)],[int(2),int(1)]])).
4619 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [fd(1,'Name')], X=global_set('Name'))).
4620 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4621 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4622 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name')], X=global_set('Name'))).
4623 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(1)], X=[int(2),int(1)])).
4624 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(1),int(2)], X=[int(2),int(1)])).
4625 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(2)], X=[int(2)])).
4626 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(2)], X=[int(1)])).
4627 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [], X=[int(1)])).
4628
4629 not_strict_subset_of(Set1,Set2) :-
4630 (preference(use_chr_solver,true) -> chr_not_subset_strict(Set1,Set2) ; true),
4631 init_wait_flags(WF,[not_strict_subset_of]),
4632 not_strict_subset_of_wf(Set1,Set2,WF),
4633 ground_wait_flags(WF).
4634
4635 :- block not_strict_subset_of_wf(-,?,?),not_strict_subset_of_wf(?,-,?).
4636 not_strict_subset_of_wf(Set1,Set2,WF) :-
4637 (both_global_sets(Set1,Set2,G1,G2)
4638 -> not_strict_subset_of_global_sets(G1,G2)
4639 ; not_strict_subset_of_wf1(Set1,Set2,WF)
4640 ).
4641 ?not_strict_subset_of_wf1(Set1,Set2,WF) :- not_subset_of_explicit_set(Set1,Set2,Code,WF),!,
4642 equality_objects_wf(Set1,Set2,EqRes,WF),
4643 not_strict_eq_check(EqRes,Code).
4644 not_strict_subset_of_wf1(Set1,Set2,WF) :-
4645 % OLD VERSION: not_subset_of(Set1,Set2) ; check_equal_object(Set1,Set2).
4646 expand_custom_set_to_list_wf(Set1,ESet1,_,not_strict_subset_of_wf1,WF),
4647 (nonvar(Set2),is_infinite_explicit_set(Set2) -> Inf=infinite ; Inf=unknown),
4648 not_strict_subset_of2(ESet1,Set2,Inf,WF).
4649
4650 :- block not_strict_eq_check(-,?).
4651 not_strict_eq_check(pred_true,_). % if equal then not strict subset is true
4652 not_strict_eq_check(pred_false,Code) :- call(Code). % check if not subset
4653
4654 :- block not_strict_subset_of2(-,?,?,?).
4655 not_strict_subset_of2([],R,_,WF) :- empty_set_wf(R,WF).
4656 not_strict_subset_of2([H|T],Set2,Inf,WF) :-
4657 membership_test_wf(Set2,H,MemRes,WF),
4658 not_strict_subset_of3(MemRes,H,T,Set2,Inf,WF).
4659
4660 :- block not_strict_subset_of3(-,?,?,?,?,?).
4661 not_strict_subset_of3(pred_false,_H,_T,_Set2,_,_WF).
4662 not_strict_subset_of3(pred_true,H,T,Set2,Inf,WF) :-
4663 (Inf=infinite
4664 -> RS2=Set2 % Set1 is finite; we just have to check that all elements are in Set2 and we have a strict subset
4665 ; remove_element_wf(H,Set2,RS2,WF)),
4666 not_strict_subset_of2(T,RS2,Inf,WF).
4667
4668
4669 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,2),interval(1,3))).
4670 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,2),interval(0,-1))).
4671 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,2),interval(4,3))).
4672 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(1,3))).
4673 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,9000),interval(2,9999))).
4674 :- assert_must_succeed((kernel_objects:not_strict_subset_of_global_sets(interval(X2,X4),interval(1,3)),
4675 X2=2, X4=4)).
4676 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(1,4))).
4677 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(2,4))).
4678 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(0,10))).
4679 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,2),interval(1,inf))).
4680 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(-1,2),interval(0,inf))).
4681 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(1,2),interval(1,inf))).
4682 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(0,2),interval(0,inf))).
4683 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(-1,2),interval(minus_inf,inf))).
4684 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,inf),interval(1,inf))).
4685 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(minus_inf,inf),interval(1,inf))).
4686 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(minus_inf,inf),interval(0,inf))).
4687 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(1,inf),interval(minus_inf,inf))).
4688 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,inf),interval(1,inf))).
4689 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(1,inf),interval(0,inf))).
4690 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,inf),interval(0,inf))).
4691
4692 :- block not_strict_subset_of_global_sets(-,?), not_strict_subset_of_global_sets(?,-).
4693 not_strict_subset_of_global_sets(interval(Low1,Up1),interval(Low2,Up2)) :- !,
4694 % Note: if Low2>Up2 then nothing is a strict subset of the empty set, i.e., everything is not a strict subset
4695 (finite_interval(Low1,Up1), finite_interval(Low2,Up2)
4696 -> clpfd_interface:post_constraint2(((Low2 #=< Up2) #=> (Low1 #=< Up1 #/\ ((Low2 #> Low1) #\/ (Up1 #> Up2) #\/ ((Low1 #= Low2 #/\ Up1 #= Up2))))),Posted)
4697 ; Posted=false),
4698 (Posted==true -> true ; not_strict_subset_intervals(Low1,Up1,Low2,Up2)).
4699 not_strict_subset_of_global_sets(G1,G2) :-
4700 when((ground(G1),ground(G2)), \+check_strict_subset_of_global_sets(G1,G2)).
4701
4702 :- block not_strict_subset_intervals(?,?,-,?), not_strict_subset_intervals(?,?,?,-).
4703 % Instead of blocking on Low2,Up2 we could post bigger constraint (Low2 <= Up2 => (Low1 <= Up1 /\ ....
4704 not_strict_subset_intervals(_Low1,_Up1,Low2,Up2) :- safe_less_than_with_inf(Up2,Low2),!.
4705 not_strict_subset_intervals(Low1,Up1,Low2,Up2) :-
4706 safe_less_than_equal_with_inf_clpfd(Low1,Up1), % if Low1..Up1 is empty then it would be a strict subset
4707 not_check_strict_subset_intervals2(Low1,Up1,Low2,Up2).
4708 :- block not_check_strict_subset_intervals2(-,?,?,?),not_check_strict_subset_intervals2(?,-,?,?),
4709 not_check_strict_subset_intervals2(?,?,-,?).
4710 ?not_check_strict_subset_intervals2(Low1,Up1,Low2,Up2) :- \+ check_strict_subset_intervals2(Low1,Up1,Low2,Up2).
4711
4712
4713 /* Set1 /: FIN1(Set2) */
4714 :- assert_must_succeed((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(2)])).
4715 :- assert_must_succeed((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X=[int(1)], Y=[int(1),int(2)])).
4716 :- assert_must_succeed((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[])).
4717 :- assert_must_fail((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(1)])).
4718
4719 :- block not_non_empty_finite_subset_of_wf(-,?,?).
4720 not_non_empty_finite_subset_of_wf(Set1,Set2,WF) :- test_finite_set_wf(Set1,Finite,WF),
4721 not_non_empty_finite_subset_of_aux(Finite,Set1,Set2,WF).
4722 :- block not_non_empty_finite_subset_of_aux(-,?,?,?).
4723 not_non_empty_finite_subset_of_aux(pred_false,_Set1,_Set2,_WF).
4724 not_non_empty_finite_subset_of_aux(pred_true,Set1,Set2,WF) :- not_non_empty_subset_of_wf(Set1,Set2,WF).
4725
4726 /* Set1 /: POW1(Set2) */
4727 :- assert_must_succeed(exhaustive_kernel_check_wf(not_non_empty_subset_of_wf([int(1)], [int(2),int(3)],WF),WF)).
4728 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(not_non_empty_subset_of_wf([int(2)], [int(2),int(3)],WF),WF)).
4729 :- assert_must_succeed((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(2)])).
4730 :- assert_must_succeed((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X=[int(1)], Y=[int(1),int(2)])).
4731 :- assert_must_succeed((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[])).
4732 :- assert_must_fail((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(1)])).
4733
4734 % Set1 /: POW1(Set2)
4735 :- block not_non_empty_subset_of_wf(-,?,?).
4736 not_non_empty_subset_of_wf(Set1,_,_WF) :- Set1==[],!.
4737 not_non_empty_subset_of_wf(Set1,Set2,WF) :- % Maybe introduce binary choice point ?
4738 empty_set_wf(Set1,WF) ;
4739 not_subset_of_wf(Set1,Set2,WF).
4740
4741
4742 /* min, max */
4743
4744 :- assert_must_succeed(exhaustive_kernel_check(minimum_of_set([int(1)],int(1),unknown,_WF))).
4745 :- assert_must_succeed(exhaustive_kernel_check(minimum_of_set([int(2),int(3),int(1)],int(1),unknown,_WF))).
4746 :- assert_must_succeed(exhaustive_kernel_fail_check(minimum_of_set([int(2),int(3),int(1)],int(2),unknown,_WF))).
4747 :- assert_must_succeed((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(1)])).
4748 :- assert_must_succeed((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(2),int(1)])).
4749 :- assert_must_succeed((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(1),int(2),int(1),int(3)])).
4750 :- assert_must_fail((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(2), Y=[int(1),int(2),int(1),int(3)])).
4751 :- assert_must_abort_wf(kernel_objects:minimum_of_set([],_R,unknown,WF),WF).
4752 %:- must_succeed(kernel_waitflags:assert_must_abort2_wf(kernel_objects:minimum_of_set([],_R,WF),WF)).
4753
4754 :- block minimum_of_set_extension_list(-,?,?,?).
4755 minimum_of_set_extension_list(ListOfValues,int(Min),Span,WF) :-
4756 minimum_of_set2(ListOfValues,Min,Span,WF).
4757
4758 :- block minimum_of_set(-,?,?,?).
4759 minimum_of_set(Set1,Res,_Span,WF) :- is_custom_explicit_set(Set1,minimum_of_set),
4760 min_of_explicit_set_wf(Set1,Min,WF), !,
4761 equal_object_wf(Min,Res,minimum_of_set,WF).
4762 minimum_of_set(Set1,int(Min),Span,WF) :-
4763 expand_custom_set_to_list_wf(Set1,ESet1,_,minimum_of_set,WF),
4764 (var(ESet1),Set1=closure(_,_,_)
4765 -> quick_propagation_element_information(Set1,int(Min),WF,_) ; true),
4766 minimum_of_set2(ESet1,Min,Span,WF).
4767 :- block minimum_of_set2(-,?,?,?).
4768 minimum_of_set2([],Res,Span,WF) :-
4769 add_wd_error_set_result('min applied to empty set','',Res,int(0),Span,WF).
4770 minimum_of_set2([int(N)|T],Min,_,_) :- clpfd_geq2(N,Min,_),minimum_of_set3(T,N,Min,[N]).
4771
4772 :- block minimum_of_set3(-,?,?,?). % with CLPFD: makes sense to also unfold if Min Variable; hence no longer block on : minimum_of_set3(?,-,-).
4773 minimum_of_set3([],MinSoFar,MinSoFar,ListOfValues) :-
4774 (var(MinSoFar) -> clpfd_minimum(MinSoFar,ListOfValues) ; true).
4775 minimum_of_set3([int(M)|T],MinSoFar,Min,ListOfValues) :- clpfd_geq2(M,Min,_),
4776 minimum(M,MinSoFar,NewMinSoFar),
4777 minimum_of_set3(T,NewMinSoFar,Min,[M|ListOfValues]).
4778
4779
4780 :- block minimum(-,?,?), minimum(?,-,?).
4781 minimum(M1,M2,Min) :- M1<M2 -> Min=M1 ; Min=M2.
4782
4783 :- assert_must_succeed(exhaustive_kernel_check(maximum_of_set([int(1)],int(1),unknown,_WF))).
4784 :- assert_must_succeed(exhaustive_kernel_check(maximum_of_set([int(2),int(3),int(1)],int(3),unknown,_WF))).
4785 :- assert_must_succeed(exhaustive_kernel_fail_check(maximum_of_set([int(2),int(3),int(1)],int(2),unknown,_WF))).
4786 :- assert_must_succeed((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(1)])).
4787 :- assert_must_succeed((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(2), Y=[int(2),int(1)])).
4788 :- assert_must_succeed((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(3), Y=[int(1),int(2),int(1),int(3)])).
4789 :- assert_must_fail((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(2), Y=[int(1),int(2),int(1),int(3)])).
4790 :- assert_must_fail((preferences:preference(use_clpfd_solver,true),
4791 kernel_objects:maximum_of_set([int(X),int(_Y)],int(3),unknown,_WF), X = 4)). % in CLPFD modus
4792 :- assert_must_fail((preferences:preference(use_clpfd_solver,true),
4793 kernel_objects:maximum_of_set([int(_),int(X)],int(3),unknown,_WF), X = 4)).% in CLPFD modus
4794 :- assert_must_abort_wf(kernel_objects:maximum_of_set([],_R,unknown,WF),WF).
4795
4796 :- block maximum_of_set_extension_list(-,?,?,?).
4797 maximum_of_set_extension_list(ListOfValues,int(Max),Span,WF) :-
4798 maximum_of_set2(ListOfValues,Max,Span,WF).
4799
4800 :- block maximum_of_set(-,?,?,?).
4801 maximum_of_set(Set1,Res,_Span,WF) :-
4802 is_custom_explicit_set(Set1,maximum_of_set),
4803 max_of_explicit_set_wf(Set1,Max,WF), !,
4804 equal_object_wf(Max,Res,maximum_of_set,WF).
4805 maximum_of_set(Set1,int(Max),Span,WF) :-
4806 expand_custom_set_to_list_wf(Set1,ESet1,_,maximum_of_set,WF),
4807 (var(ESet1),Set1=closure(_,_,_)
4808 -> quick_propagation_element_information(Set1,int(Max),WF,_) ; true),
4809 maximum_of_set2(ESet1,Max,Span,WF).
4810 :- block maximum_of_set2(-,?,?,?).
4811 maximum_of_set2([],Res,Span,WF) :-
4812 add_wd_error_set_result('max applied to empty set','',Res,int(0),Span,WF). %preferences:get_preference(maxint,R))). %R=abort(maximum_of_empty_set))).
4813 maximum_of_set2([int(N)|T],Max,_Span,_) :- clpfd_geq2(Max,N,_),
4814 maximum_of_set3(T,N,Max,[N]).
4815
4816 :- block maximum_of_set3(-,?,?,?). % with CLPFD: makes sense to also unfold if Max Variable; hence no longer block on : maximum_of_set3(?,-,-).
4817 maximum_of_set3([],MaxSoFar,MaxSoFar,ListOfValues) :-
4818 (var(MaxSoFar) -> clpfd_maximum(MaxSoFar,ListOfValues) ; true).
4819 maximum_of_set3([int(M)|T],MaxSoFar,Max,ListOfValues) :- clpfd_geq2(Max,M,_),
4820 maximum(M,MaxSoFar,NewMaxSoFar),
4821 maximum_of_set3(T,NewMaxSoFar,Max,[M|ListOfValues]).
4822
4823 :- block maximum(-,?,?), maximum(?,-,?).
4824 maximum(M1,M2,Max) :- M1>M2 -> Max=M1 ; Max=M2.
4825
4826 % card(ran(Function)); useful e.g. for q : 1 .. 16 --> 1 .. 16 & card(ran(q))=16
4827 :- block cardinality_of_range(-,?,?).
4828 cardinality_of_range(CS,Card,WF) :-
4829 is_custom_explicit_set(CS,cardinality_of_range),
4830 range_of_explicit_set_wf(CS,Res,WF),!,
4831 cardinality_as_int_wf(Res,Card,WF).
4832 cardinality_of_range(Function,Card,WF) :-
4833 expand_custom_set_to_list_wf(Function,EF1,Done,cardinality_of_range,WF),
4834 project_on_range(EF1,ERange),
4835 % when Done is set: we have a complete list and can compute MaxCard; TODO: maybe provide a version that can trigger earlier
4836 when(nonvar(Done),cardinality_of_set_extension_list(ERange,Card,WF)).
4837
4838 :- block project_on_range(-,?).
4839 project_on_range([],[]).
4840 project_on_range([(_,Ran)|T],[Ran|TR]) :- project_on_range(T,TR).
4841
4842
4843 :- assert_must_succeed((cardinality_of_set_extension_list([fd(1,'Name')],R,_WF), R = int(1))).
4844 :- assert_must_succeed((cardinality_of_set_extension_list([int(X),int(Y)],int(1),_WF), X=22, Y==22)).
4845
4846 cardinality_of_set_extension_list(List,int(Card),WF) :-
4847 length(List,MaxCard), less_than_equal_direct(Card,MaxCard),
4848 cardinality_of_set_extension_list2(List,[],0,MaxCard,Card,WF).
4849
4850 :- block cardinality_of_set_extension_list2(-,?,?,?,?,?).
4851 cardinality_of_set_extension_list2([],_,AccSz,_MaxCard,Res,_WF) :- Res=AccSz.
4852 cardinality_of_set_extension_list2([H|T],Acc,AccSz,MaxCard,Res,WF) :-
4853 membership_test_wf(Acc,H,MemRes,WF),
4854 (MaxCard==Res -> /* only solution is for H to be not in Acc */ MemRes=pred_false
4855 ; AccSz==Res -> /* only solution is for H to be in Acc */ MemRes=pred_true
4856 ; (var(Res),var(MemRes)) -> kernel_equality:equality_int(MaxCard,Res,EqMaxC),prop_if_pred_true(EqMaxC,MemRes,pred_false),
4857 kernel_equality:equality_int(AccSz,Res,EqAccSz),prop_if_pred_true(EqAccSz,MemRes,pred_true)
4858 ; true),
4859 cardinality_of_set_extension_list3(MemRes,H,T,Acc,AccSz,MaxCard,Res,WF).
4860
4861 :- block prop_if_pred_true(-,?,?).
4862 prop_if_pred_true(pred_true,X,X).
4863 prop_if_pred_true(pred_false,_,_).
4864
4865 :- block cardinality_of_set_extension_list3(-,?,?,?,?,?,?,?).
4866 cardinality_of_set_extension_list3(pred_true,_,T,Acc,AccSz,MaxCard,Res,WF) :-
4867 % H is a member of Acc, do not increase Acc nor AccSz; however MaxCard now decreases
4868 less_than_direct(Res,MaxCard), M1 is MaxCard-1,
4869 cardinality_of_set_extension_list2(T,Acc,AccSz,M1,Res,WF).
4870 cardinality_of_set_extension_list3(pred_false,H,T,Acc,AccSz,MaxCard,Res,WF) :-
4871 A1 is AccSz+1, less_than_equal_direct(A1,Res),
4872 cardinality_of_set_extension_list2(T,[H|Acc],A1,MaxCard,Res,WF).
4873
4874 :- assert_must_succeed(exhaustive_kernel_check(is_finite_set_wf([fd(1,'Name'),fd(2,'Name')],_WF))).
4875 :- assert_must_succeed((is_finite_set_wf(Y,_WF), Y = [])).
4876 :- assert_must_succeed((is_finite_set_wf(Y,_WF), Y = [int(1),int(2)])).
4877 :- use_module(typing_tools,[contains_infinite_type/1]).
4878 :- use_module(custom_explicit_sets,[card_for_specific_custom_set/3]).
4879
4880 is_finite_set_wf(Set,WF) :- test_finite_set_wf(Set,pred_true,WF).
4881
4882 :- assert_must_succeed(exhaustive_kernel_fail_check(is_infinite_set_wf([fd(1,'Name'),fd(2,'Name')],_WF))).
4883 :- assert_must_fail((is_infinite_set_wf(Y,_WF), Y = [int(1),int(2)])).
4884
4885 is_infinite_set_wf(Set,WF) :- test_finite_set_wf(Set,pred_false,WF).
4886
4887 %! test_finite_set_wf(+Set,?X,+WF)
4888 :- block test_finite_set_wf(-,?,?).
4889 %test_finite_set_wf(A,B,C) :- print(test_finite_set_wf(A,B,C)),nl,fail.
4890 test_finite_set_wf([],X,_WF) :- !, X=pred_true.
4891 test_finite_set_wf([_|T],X,WF) :- !, test_finite_set_wf(T,X,WF). % what if Tail contains closure ??
4892 test_finite_set_wf(avl_set(_),X,_WF) :- !, X=pred_true.
4893 test_finite_set_wf(closure(_P,T,_B),X,_WF) :- \+ contains_infinite_type(T), !, X=pred_true.
4894 test_finite_set_wf(closure(P,T,B),X,WF) :- !, test_finite_closure(P,T,B,X,WF).
4895 test_finite_set_wf(Set,X,WF) :- /* also deals with global_set(_) */
4896 /* explicit_set_cardinality may trigger an enum warning */
4897 explicit_set_cardinality_wf(Set,Card,WF),
4898 set_finite_result(Card,Set,explicit_set,X).
4899
4900 :- use_module(bsyntaxtree,[is_a_disjunct/3]).
4901 % we already check that contains_infinite_type above
4902 test_finite_closure(P,T,B,Res,WF) :- is_a_disjunct(B,D1,D2),!,
4903 test_finite_closure(P,T,D1,IsFinite1,WF), % TODO: we could conjoin IsFinite1 & IsFinite2
4904 test_finite_disj2(IsFinite1,P,T,D2,Res,WF).
4905 % TO DO: add is_closure1_value_closure
4906 test_finite_closure(P,T,B,X,WF) :- when(ground(B), test_finite_closure_ground(P,T,B,X,WF)).
4907
4908 :- block test_finite_disj2(-,?,?,?,?,?).
4909 test_finite_disj2(pred_false,_P,_T,_D2,X,_WF) :- X=pred_false.
4910 test_finite_disj2(pred_true,P,T,D2,X,WF) :- test_finite_closure(P,T,D2,X,WF).
4911
4912
4913 % first: we need to check all constructors such as POW, FIN, ... which card_for_specific_custom_set supports
4914 % problem: if card becomes very large it is replaced by inf, which may give wrong results here (for card(.) we just get a spurious WD warning, here we may get wrong results)
4915 test_finite_closure_ground(P,T,B,X,WF) :-
4916 is_powerset_closure(closure(P,T,B),_Type,Subset),
4917 % note: whether Type is fin, fin1, pow, or pow1 does not matter
4918 !,
4919 test_finite_set_wf(Subset,X,WF).
4920 test_finite_closure_ground(P,T,B,X,WF) :-
4921 custom_explicit_sets:is_lambda_value_domain_closure(P,T,B, Subset,_Expr), !,
4922 test_finite_set_wf(Subset,X,WF).
4923 test_finite_closure_ground(P,T,B,X,WF) :-
4924 custom_explicit_sets:is_cartesian_product_closure(closure(P,T,B), A1,B2), !,
4925 test_finite_set_wf(A1,AX,WF),
4926 test_finite_set_wf(B2,BX,WF),
4927 test_finite_cartesian_product_wf(AX,BX,A1,B2,X,WF).
4928 test_finite_closure_ground(Par,Typ,Body, X,_WF) :-
4929 ? custom_explicit_sets:is_geq_leq_interval_closure(Par,Typ,Body,Low,Up), !,
4930 custom_explicit_sets:card_of_interval_inf(Low,Up,Card),
4931 set_finite_result_no_warn(Card,X).
4932 test_finite_closure_ground(P,T,B,X,WF) :-
4933 closures:is_member_closure(P,T,B,_,SET), nonvar(SET),
4934 unary_member_closure_for_finite(SET,Check,SET1),
4935 !,
4936 (Check==finite -> test_finite_set_wf(SET1,X,WF)
4937 ; Check==always -> X=pred_true
4938 ; kernel_equality:empty_set_test_wf(SET1,X,WF)).
4939 % TO DO: catch other special cases : relations, struct,...
4940 test_finite_closure_ground(P,T,B,X,_WF) :-
4941 custom_explicit_sets:card_for_specific_closure(closure(P,T,B),ClosureKind,Card,Code),!,
4942 call(Code), % TO DO: catch if we convert large integer due to overflow to inf !
4943 % maybe we can set / transmit a flag for is_overflowcheck ? overflow_float_pown ? factorial ?
4944 set_finite_result(Card,closure(P,T,B),ClosureKind,X).
4945 test_finite_closure_ground(P,T,B,X,WF) :-
4946 on_enumeration_warning(expand_only_custom_closure_global(closure(P,T,B),Result,check,WF),fail),
4947 !,
4948 test_finite_set_wf(Result,X,WF).
4949 test_finite_closure_ground(P,T,B,X,WF) :- X==pred_true, !,
4950 get_enumeration_finished_wait_flag(WF,AWF), % only add warning if indeed we find a solution
4951 finite_warning(AWF,P,T,B,is_finite_set_closure(P)).
4952 test_finite_closure_ground(P,T,B,_X,_WF) :- !,
4953 finite_warning(now,P,T,B,test_finite_closure(P)),
4954 fail. % now we fail; used to be X=pred_true. % we assume set to be finite, but print a warning
4955 % we could set up the closure and do a deterministic phase: if it fails or all variables become bounded, then it is finite
4956
4957 unary_member_closure_for_finite(seq(b(value(SET1),_,_)),empty,SET1). % finite if SET1 is empty
4958 unary_member_closure_for_finite(seq1(b(value(SET1),_,_)),empty,SET1).
4959 unary_member_closure_for_finite(perm(_),always,_). % always finite: card(S)! elements if S is finite, empty if S is infinite
4960 unary_member_closure_for_finite(iseq(b(value(SET1),_,_)),finite,SET1).
4961 unary_member_closure_for_finite(iseq1(b(value(SET1),_,_)),finite,SET1).
4962 unary_member_closure_for_finite(identity(b(value(SET1),_,_)),finite,SET1).
4963 % we could deal with POW/POW1... here
4964 % succ/pred?
4965
4966 :- block test_finite_cartesian_product_wf(-,?,?,?,?,?), test_finite_cartesian_product_wf(?,-,?,?,?,?).
4967 test_finite_cartesian_product_wf(pred_true, pred_true, _,_,X,_) :- !, X=pred_true. % both finite
4968 test_finite_cartesian_product_wf(pred_false,pred_false,_,_,X,_) :- !, X=pred_false. % both infinite
4969 test_finite_cartesian_product_wf(pred_false,pred_true, _,B,X,WF) :- !,
4970 kernel_equality:empty_set_test_wf(B,X,WF). % only finite if B empty
4971 test_finite_cartesian_product_wf(pred_true, pred_false,A,_,X,WF) :- !,
4972 kernel_equality:empty_set_test_wf(A,X,WF). % only finite if A empty
4973
4974
4975 :- block set_finite_result_no_warn(-,?).
4976 set_finite_result_no_warn(inf,X) :- !, X=pred_false.
4977 set_finite_result_no_warn(_,pred_true).
4978
4979 :- block set_finite_result(-,?,?,?).
4980 set_finite_result(inf,_Set,_ClosureKind,X) :- !,
4981 %(Set=closure(P,T,B), \+ precise_closure_kind(ClosureKind)
4982 % -> finite_warning(now,P,T,B,test_finite_closure(P)) % we sometimes return inf for very large sets % TO DO: fix
4983 % ; true),
4984 X=pred_false.
4985 set_finite_result(_,_,_,pred_true).
4986
4987 % inf is now always real infinity; inf_overflow is finite very large cardinality not representable as number
4988 %precise_closure_kind(special_closure). % is_special_infinite_closure is precise, inf is real infinity %%%
4989 %precise_closure_kind(interval_closure). % here we also should never produce inf for a finite but large set
4990
4991
4992 :- assert_must_succeed(exhaustive_kernel_check(cardinality_as_int([int(2),int(4),int(1)],int(3)))).
4993 :- assert_must_succeed((V1 = term(floating(1.0)), V2 = term(floating(2.0)), V3 = term(floating(-1.0)),
4994 exhaustive_kernel_check(cardinality_as_int([V1,V3,V2],int(3))))).
4995 :- assert_must_succeed((cardinality_as_int(Y,int(2)), Y = [fd(1,'Name'),fd(2,'Name')])).
4996 :- assert_must_succeed((cardinality_as_int(Y,int(2)),
4997 nonvar(Y), Y = [H1|YY], nonvar(YY), YY=[H2], H1=int(0), H2=int(3) )).
4998 :- assert_must_succeed((cardinality_as_int([A|Y],int(3)),
4999 nonvar(Y), Y = [B|YY], nonvar(YY), YY=[C], A=int(1),B=int(3),C=int(2) )).
5000 :- assert_must_succeed((cardinality_as_int(Y,int(1)), Y = [fd(1,'Name')])).
5001 :- assert_must_succeed((cardinality_as_int(Y,int(0)), Y = [])).
5002 :- assert_must_succeed((cardinality_as_int(X,int(3)), equal_object(X,global_set('Name')))).
5003 :- assert_must_fail((cardinality_as_int(Y,int(X)), Y = [fd(1,'Name'),fd(2,'Name')],dif(X,2))).
5004 :- assert_must_succeed_any((preferences:preference(use_clpfd_solver,false) ;
5005 cardinality_as_int_wf(S,int(C),WF), clpfd_interface:try_post_constraint('#>='(C,2)), kernel_waitflags:ground_wait_flags(WF), nonvar(S),S=[_|T],nonvar(T))).
5006 :- assert_must_succeed((cardinality_as_int([int(1)|avl_set(node(int(3),true,0,empty,empty))],int(2)))).
5007 :- assert_must_succeed((cardinality_as_int([int(1)|avl_set(node(int(3),true,0,empty,empty))],X),X==int(2))).
5008 % check that we deal with repeated elements, in case no other predicate sets up a list !
5009 :- assert_must_fail((cardinality_as_int([int(1),int(1)],int(2)))).
5010 :- assert_must_fail((cardinality_as_int([int(1),int(1)],_))).
5011 :- assert_must_fail((cardinality_as_int(X,int(2)),X=[int(1),int(1)])).
5012 :- assert_must_fail((cardinality_as_int([int(3)|avl_set(node(int(3),true,0,empty,empty))],_))).
5013 :- assert_must_fail((cardinality_as_int([X|avl_set(node(int(3),true,0,empty,empty))],int(2)),X=int(3))).
5014
5015
5016 cardinality_as_int(S,I) :- cardinality_as_int_wf(S,I,no_wf_available). % TO DO: remove this predicate ?
5017 %:- load_files(library(system), [when(compile_time), imports([environ/2])]).
5018 %:- if(environ(prob_data_validation_mode,true)).
5019 %:- block cardinality_as_int_wf(-,?,?). % avoid instantiating list skeletons; cause backtracking in unifications,...
5020
5021 % can return inf !
5022 :- block cardinality_as_int_wf(-,-,?).
5023 cardinality_as_int_wf(Set,int(Card),WF) :-
5024 cardinality_as_int1(Set,Card,Card,WF).
5025
5026 cardinality_as_int1(Set,Card,ResCard,WF) :-
5027 (number(Card)
5028 -> cardinality_as_int1b(Set,Card,ResCard,WF)
5029 ; cardinality_as_int1b(Set,Card,ResCard,WF),
5030 (var(Set) ->
5031 (clpfd_domain(Card,Low,_Up),
5032 number(Low), Low>1,
5033 unbound_variable_for_card(Set)
5034 % TO DO: also use this optimization later in cardinality_as_int2
5035 -> setup_ordered_list_skeleton(Low,Skel,open,WF),
5036 Skel=Set
5037 ; get_wait_flag(1,force_non_empty(Set,Card),WF,LWF),
5038 force_non_empty0(Set,Card,LWF)
5039 )
5040 ; true)
5041 ).
5042 % tests 1418, 1419, 1628, 1776 require that cardinality_as_int1b be triggered quickly
5043 :- block cardinality_as_int1b(-,-,?,?). % with this the self-check with post_constraint('#>='(C,2) fails
5044 % cardinality_as_int1(Set, CardValue, ComputedCardValue) : CardValue should be unified with ComputedCardValue afterwards
5045 cardinality_as_int1b(Set,Card,ResCard,WF) :-
5046 %portray_waitflags(WF),nl,
5047 number(Card), unbound_variable_for_card(Set),
5048 !, % we know the cardinality and the set is not yet bound; this improvement is tested in tests 1417, 1418
5049 setup_ordered_list_skeleton(Card,Skel,closed,WF),
5050 (Card,Set) = (ResCard,Skel). % bypass equal_object: assign variable in one-go
5051 cardinality_as_int1b(Set,Card,ResCard,WF) :- nonvar(Set),!,
5052 cardinality_as_int2(Set,0,Card,ResCard,[],WF).
5053 cardinality_as_int1b(Set,Card,ResCard,WF) :-
5054 % Set is a variable but not unbound_variable_for_cons
5055 % Unifications can be very expensive when we set up long lists
5056 % Idea: multiply Card by a factor and delay instantiating; maybe we get a avl_set; see test 456
5057 Prio is Card*100,
5058 get_wait_flag(Prio,cardinality_as_int1(Set,Card),WF,LWF2),
5059 when((nonvar(Set) ; nonvar(LWF2)),
5060 cardinality_as_int2(Set,0,Card,ResCard,[],WF)).
5061 %force_non_empty0(Set,Card,1).
5062
5063 %:- if(environ(prob_data_validation_mode,true)).
5064 %:- block cardinality_as_int2(-,?,?,?,?,?). % avoid instantiating list skeletons; cause backtracking in unifications,...
5065
5066 :- block cardinality_as_int2(-,?,-,?,?,?).
5067 cardinality_as_int2(X,C,Res,ResultValue,_,WF) :-
5068 C==Res,!,empty_set_wf(X,WF),ResultValue=Res. % avoid choice point below
5069 cardinality_as_int2(X,C,Res,ResultValue,SoFar,WF) :- nonvar(X), X \= [], X\= [_|_],!,
5070 (is_custom_explicit_set(X)
5071 -> explicit_set_cardinality_wf(X,ESC,WF), blocking_add_card(C,ESC,ResultValue),
5072 disjoint_sets(X,SoFar,WF)
5073 ; add_error_fail(cardinality_as_int2,'First argument not set: ',cardinality_as_int2(X,C,Res))
5074 ).
5075 cardinality_as_int2([],C,Res,ResultValue,_,_WF) :- C=ResultValue, Res=ResultValue.
5076 cardinality_as_int2([H|T],C,Res,ResultValue,SoFar,WF) :-
5077 C1 is C+1,
5078 not_element_of_wf(H,SoFar,WF), % do we always need to check this ? relevant for test 1828
5079 add_new_element_wf(H,SoFar,SoFar2,WF),
5080 (ground(Res) -> safe_less_than_equal(cardinality_as_int2,C1,Res)
5081 /* check consistency so far if cardinality provided */
5082 ; clpfd_geq(Res,C1,_)
5083 ),
5084 force_non_empty(T,C1,Res,1), % Use WF ?
5085 cardinality_as_int2(T,C1,Res,ResultValue,SoFar2,WF).
5086
5087 % setup an list skeleton with ordering constraints to avoid duplicate solutions
5088 setup_ordered_list_skeleton(0,R,Closed,_WF) :- !, (Closed=closed -> R=[] ; true).
5089 setup_ordered_list_skeleton(N,[H|T],Closed,WF) :-
5090 all_different_wf([H|T],WF),
5091 N1 is N-1, setup_list_skel_aux(N1,H,T,Closed).
5092
5093
5094 :- use_module(kernel_ordering,[ordered_value/2]).
5095 %setup_list_skel_aux(0,_,R,Closed) :- !, (Closed=closed -> R=[] ; true). % if open: TO DO: impose ordering on rest using lazy_ordered_value ? done in next clause below
5096 setup_list_skel_aux(0,Prev,R,Closed) :- !, (Closed=closed -> R=[] ; lazy_ordered_value(R,Prev)).
5097 setup_list_skel_aux(N,Prev,[H|T],Closed) :- ordered_value(Prev,H),
5098 N>0, N1 is N-1, setup_list_skel_aux(N1,H,T,Closed).
5099
5100 :- block lazy_ordered_value(-,?).
5101 lazy_ordered_value([H|T],Prev) :- !, ordered_value(Prev,H), lazy_ordered_value(T,H).
5102 lazy_ordered_value(_,_).
5103
5104
5105 % TO DO: use clpfd all_different for integers !?
5106 % get_integer_list(Set,IntList), clpfd_alldifferent(IntList).
5107 % ensure we have all different constraint in case ordered_value does not succeed in enforcing order!
5108 all_different_wf(ListOfValues,WF) :-
5109 all_different2(ListOfValues,[],WF).
5110 :- block all_different2(-,?,?).
5111 all_different2([],_,_) :- !.
5112 all_different2([H|T],SoFar,WF) :- !, all_different3(SoFar,H,WF), all_different2(T,[H|SoFar],WF).
5113 all_different2(CS,SoFar,WF) :- is_custom_explicit_set(CS),
5114 disjoint_sets(CS,SoFar,WF). % already done above by cardinality_as_int2 ?
5115 all_different3([],_,_).
5116 all_different3([H|T],X,WF) :- not_equal_object_wf(H,X,WF), all_different3(T,X,WF).
5117
5118 :- block force_non_empty0(-,-,-).
5119 force_non_empty0(Set,Card,LWF) :- var(Set), var(Card),
5120 clpfd_domain(Card,Low,Up),
5121 (integer(Low) ; integer(Up)), !, % we know we have a finite cardinality
5122 clpfd_interface:try_post_constraint((Card#=0) #<=> EmptyR01),
5123 prop_non_empty(EmptyR01,Set,LWF).
5124 force_non_empty0(_,_,_).
5125
5126 % here we assume that the cardinalities cannot be infinite inf
5127 :- block force_non_empty(-,?,-,-).
5128 force_non_empty(Set,CSoFar,TotalCard,LWF) :-
5129 var(Set), var(TotalCard),
5130 preference(data_validation_mode,false),!,
5131 clpfd_interface:try_post_constraint((TotalCard#=CSoFar) #<=> EmptyR01),
5132 prop_non_empty(EmptyR01,Set,LWF).
5133 force_non_empty(_,_,_,_).
5134 :- block prop_non_empty(-,-,?).
5135 prop_non_empty(_,X,_) :- nonvar(X),!. % do nothing; cardinality_as_int2 will be called anyway
5136 prop_non_empty(0,X,LWF) :- /* X is var; first arg nonvar */ !, not_empty_set_lwf(X,LWF).
5137 %prop_non_empty(1,X,_). % empty_set not really required: TotalCard is now instantiated; cardinality_as_int2 will get called
5138 prop_non_empty(_,_,_).
5139
5140
5141
5142 :- assert_must_succeed(exhaustive_kernel_check(cardinality_as_int_for_wf(global_set('NATURAL'),inf))).
5143 :- assert_must_succeed(exhaustive_kernel_check(cardinality_as_int_for_wf([],0))).
5144 :- assert_must_succeed(exhaustive_kernel_check_opt(cardinality_as_int_for_wf([int(2)],1),
5145 preferences:get_preference(convert_comprehension_sets_into_closures,false))). % in this case inf returned for closures
5146 :- assert_must_succeed(exhaustive_kernel_check_opt(cardinality_as_int_for_wf([int(3),int(1),int(-1),int(100)],4),
5147 preferences:get_preference(convert_comprehension_sets_into_closures,false))).
5148 :- assert_must_succeed(exhaustive_kernel_fail_check_opt(cardinality_as_int_for_wf([int(3),int(1),int(-1),int(100)],1000),
5149 preferences:get_preference(convert_comprehension_sets_into_closures,false))).
5150 :- assert_must_succeed(exhaustive_kernel_fail_check_opt(cardinality_as_int_for_wf(global_set('NATURAL'),1000),
5151 preferences:get_preference(convert_comprehension_sets_into_closures,false))).
5152 % a simpler version without propagation to result; for waitflag priority computation or similar
5153 % it may return inf for closures marked as symbolic !
5154 cardinality_as_int_for_wf(Set,Card) :- cardinality_as_int_for_wf0(Set,0,Card).
5155 :- block cardinality_as_int_for_wf0(-,?,-).
5156 cardinality_as_int_for_wf0(X,C,Res) :-
5157 ? (nonvar(X) -> cardinality_as_int_for_wf1(X,C,Res)
5158 ; Res==inf -> cardinality_as_int_for_inf(X,C)
5159 % TODO: what about inf_overflow here
5160 ; cardinality_as_int_for_wf2(X,C,Res)).
5161
5162 :- block cardinality_as_int_for_inf(-,?).
5163 cardinality_as_int_for_inf(X,C) :- cardinality_as_int_for_wf1(X,C,inf).
5164
5165 cardinality_as_int_for_wf1([],C,Res) :- !,C=Res.
5166 cardinality_as_int_for_wf1([_H|T],C,Res) :- !,C1 is C+1,
5167 ? cardinality_as_int_for_wf0(T,C1,Res).
5168 cardinality_as_int_for_wf1(X,C,Res) :- is_custom_explicit_set(X),!,
5169 ? explicit_set_cardinality_for_wf(X,ESC), blocking_add_card(C,ESC,Res).
5170 cardinality_as_int_for_wf1(term(T),C,Res) :- nonvar(T), T=no_value_for(ID),
5171 format_with_colour(user_error,[bold,red],'~nNo value for ~w for cardinality_as_int_for_wf1!~n',[ID]), % can happen with partial_setup_constants
5172 !, C=Res.
5173 cardinality_as_int_for_wf1(X,C,Res) :-
5174 add_internal_error('First arg is not a set: ',cardinality_as_int_for_wf1(X,C,Res)),fail.
5175
5176 % first argument was var, third argument not inf hence third arg must be set
5177 %cardinality_as_int_for_wf2([],C,C).
5178 cardinality_as_int_for_wf2([],C,Res) :- (C==Res -> ! ; C=Res).
5179 cardinality_as_int_for_wf2([_H|T],C,Res) :- C<Res, C1 is C+1,
5180 (var(T) -> cardinality_as_int_for_wf2(T,C1,Res) ; cardinality_as_int_for_wf1(T,C1,Res)).
5181
5182
5183
5184 :- assert_must_succeed(exhaustive_kernel_check_wf(same_cardinality_wf(global_set('NATURAL'),global_set('NATURAL'),WF),WF)).
5185 :- assert_must_succeed(exhaustive_kernel_check_wf(same_cardinality_wf(global_set('NATURAL'),global_set('NATURAL1'),WF),WF)).
5186 :- assert_must_succeed(exhaustive_kernel_check_wf(same_cardinality_wf([int(2),int(1)],[int(11),int(22)],WF),WF)).
5187 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(same_cardinality_wf([],[int(11),int(22)],WF),WF)).
5188 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(same_cardinality_wf([int(11),int(22),int(33)],[int(11),int(22)],WF),WF)).
5189 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(same_cardinality_wf(global_set('NATURAL1'),[int(11),int(22)],WF),WF)).
5190
5191 :- block same_cardinality_wf(-,-,?).
5192 same_cardinality_wf(Set1,Set2,WF) :-
5193 (var(Set1) -> same_card_aux(Set2,Set1,WF) ; same_card_aux(Set1,Set2,WF)).
5194
5195 same_card_aux(Set1,Set2,WF) :-
5196 (nonvar(Set1),is_custom_explicit_set(Set1,cardinality)
5197 -> explicit_set_cardinality_wf(Set1,Card,WF),
5198 (Card==inf -> is_infinite_set_wf(Set2,WF)
5199 % assumption: if inf then immediately infinite; TO DO: distinguish between infinite(s) and very large
5200 ; cardinality_as_int_wf(Set2,int(Card),WF)
5201 )
5202 ; cardinality3(Set1,PCard,WF),
5203 cardinality_peano_wf(Set2,PCard,WF)
5204 ).
5205
5206 :- assert_must_succeed(exhaustive_kernel_check(cardinality_peano_wf([],0,no_wf_available))).
5207 :- assert_must_succeed(exhaustive_kernel_check(cardinality_peano_wf([int(11)],s(0),no_wf_available))).
5208 :- assert_must_succeed(exhaustive_kernel_check(cardinality_peano_wf([int(11),int(22)],s(s(0)),no_wf_available))).
5209 % cardinality as peano number
5210 :- block cardinality_peano_wf(-,-,?).
5211 cardinality_peano_wf(Set,PCard,WF) :-
5212 (nonvar(Set),is_custom_explicit_set(Set,cardinality)
5213 -> explicit_set_cardinality_wf(Set,Card,WF),
5214 card_convert_int_to_peano(Card,PCard)
5215 ; cardinality3(Set,PCard,WF)
5216 ).
5217
5218 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(3,s(s(s(0)))))).
5219 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(2,S),S==s(s(0)))).
5220 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(X,s(s(s(0)))),X==3)).
5221 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(X,s(s(s(Y)))),X=4,Y==s(0))).
5222 :- assert_must_fail((kernel_objects:card_convert_int_to_peano(X,s(s(s(_Y)))),X=2)).
5223
5224 :- block card_convert_int_to_peano(-,-).
5225 card_convert_int_to_peano(X,S0) :- var(X), !,
5226 peel_s(S0,SX,RemS),
5227 (RemS==0 -> X=SX
5228 ; int_plus(int(X1),int(SX),int(X)),
5229 greater_than_equal(int(X1),int(0)),
5230 card_convert_int_to_peano(X1,RemS)).
5231 card_convert_int_to_peano(inf,X) :- !,
5232 infinite_peano(X),
5233 add_message(cardinality,'*** WARNING: Large or infinite Cardinality.').
5234 %convert_int_to_peano(100,X). % used to limit to 100
5235 card_convert_int_to_peano(X,P) :- convert_int_to_peano(X,P).
5236
5237 :- block infinite_peano(-).
5238 infinite_peano(inf).
5239 infinite_peano(0) :- fail.
5240 infinite_peano(s(X)) :- infinite_peano(X).
5241
5242 peel_s(0,0,0).
5243 peel_s(s(X),Res,SX) :- (var(X) -> Res=1, SX=X ; peel_s(X,RX,SX), Res is RX+1).
5244
5245 :- block cardinality3(-,?,?). % avoids instantiating set; to do: use kernel_cardinality instead
5246 % relevant, e.g., for "BK-ANT-N-2013" for SlotSolver_v7; but makes 'axm2/WD' fail for test 1448; TO DO: hopefully fixed with kernel_cardinality
5247 % :- block cardinality3(-,-,?).
5248 cardinality3(Set,SC,WF) :- var(Set),!,
5249 (SC=0 -> Set=[] ; SC=s(C),Set=[_|T],cardinality3(T,C,WF)).
5250 cardinality3([],0,_).
5251 ?cardinality3([_|T],s(C),WF) :- cardinality3(T,C,WF).
5252 cardinality3(avl_set(AVL),Res,WF) :- cardinality_peano_wf(avl_set(AVL),Res,WF).
5253 cardinality3(closure(P,T,B),Res,WF) :- cardinality_peano_wf(closure(P,T,B),Res,WF).
5254
5255
5256
5257
5258
5259
5260 :- assert_must_succeed(exhaustive_kernel_check(card_geq([int(2),int(4),int(1)],s(s(s(0)))))).
5261 :- assert_must_succeed((kernel_objects:card_geq(global_set('Name'),s(s(s(0)))))).
5262 :- assert_must_succeed((kernel_objects:card_geq([int(1),int(2)],s(s(0))))).
5263 :- assert_must_succeed((kernel_objects:card_geq([int(1),int(2)],s(0)))).
5264 :- assert_must_fail((kernel_objects:card_geq(global_set('Name'),s(s(s(s(0))))))).
5265 :- assert_must_fail((kernel_objects:card_geq([int(1),int(2)],s(s(s(0)))))).
5266
5267 ?card_geq(Set,Card) :- card_geq_wf(Set,Card,no_wf_available).
5268
5269 :- block card_geq_wf(-,-,?).
5270 card_geq_wf(Set,Card,WF) :-
5271 (nonvar(Set),is_custom_explicit_set(Set,card_geq)
5272 ? -> explicit_set_cardinality_wf(Set,CCard,WF), geq_int_peano(CCard,Card)
5273 ; card_geq2(Set,Card,WF) ).
5274 % should we call setup_ordered_list_skeleton(Card,Set,open)
5275 :- block card_geq2(?,-,?).
5276 card_geq2(_,C,_) :- C==0,!.
5277 card_geq2(S,C,_) :- S==[],!,C=0.
5278 card_geq2(S,s(C),WF) :- var(S),!,S=[_|T],card_geq2(T,C,WF).
5279 card_geq2([_|T],s(C),WF) :- card_geq2(T,C,WF).
5280 card_geq2(avl_set(A),s(C),WF) :- card_geq_wf(avl_set(A),s(C),WF).
5281 card_geq2(closure(P,T,B),s(C),WF) :- card_geq_wf(closure(P,T,B),s(C),WF).
5282 card_geq2(global_set(G),s(C),WF) :- card_geq_wf(global_set(G),s(C),WF).
5283
5284 :- block geq_int_peano(-,-).
5285 geq_int_peano(_,0).
5286 ?geq_int_peano(X,s(C)) :- geq_int_peano1(X,C).
5287 :- block geq_int_peano1(-,?).
5288 geq_int_peano1(inf,_) :- !.
5289 geq_int_peano1(inf_overflow,_) :- !.
5290 ?geq_int_peano1(X,C) :- X>0, X1 is X-1, geq_int_peano(X1,C).
5291
5292 :- block convert_int_to_peano(-,?).
5293 convert_int_to_peano(X,Y) :- convert_int_to_peano2(X,Y).
5294 convert_int_to_peano2(inf,P) :- infinite_peano(P).
5295 convert_int_to_peano2(inf_overflow,P) :- infinite_peano(P).
5296 convert_int_to_peano2(X,R) :- number(X),
5297 (X>100000
5298 -> write('*** Warning: converting large integer to peano: '),write(X),nl,
5299 (X>1000000 % limit was 1000000000, but now we instantiate lazily
5300 -> debug_println(19,'*** leaving it unbounded'), % no hope of ever finishing, do not instantiate the peano number
5301 convert_large_int_to_peano(X,R,1000) % but check lazily that the peano number is compatible
5302 ; convert_int_to_peano3(X,R))
5303 ; convert_int_to_peano3(X,R)
5304 ).
5305
5306 convert_large_int_to_peano(X,P,_) :- X=0, !, P=0.
5307 convert_large_int_to_peano(X,P,Lim) :- Lim>1, !, % we instantiate up until limit
5308 X1 is X-1,L1 is Lim-1, P = s(Y),
5309 convert_large_int_to_peano(X1,Y,L1).
5310 convert_large_int_to_peano(X,Peano,_) :- lazy_convert_large_int_to_peano(X,Peano).
5311 % lazily check that a peano number corresponds to the (large) integer X, without instantiating the peano number
5312 % previously the peano number was left unconstrained, e.g., f : {x,y} >->> 1..2000000000 had a solution
5313 :- block lazy_convert_large_int_to_peano(?,-).
5314 lazy_convert_large_int_to_peano(X,0) :- !, X=0. % will in practice never be reached, because X is so large
5315 lazy_convert_large_int_to_peano(X,s(P)) :- X>0, X1 is X-1, lazy_convert_large_int_to_peano(X1,P).
5316
5317 convert_int_to_peano3(0,R) :- !, R=0.
5318 convert_int_to_peano3(X,s(P)) :-
5319 (X>0 -> X1 is X-1, convert_int_to_peano3(X1,P)
5320 ; X<0 -> add_error_and_fail(convert_int_to_peano,'Negative nr cannot be converted to peano: ',X)
5321 ).
5322
5323 % not used:
5324 %:- block convert_peano_to_int(-,?).
5325 %convert_peano_to_int(0,0).
5326 %convert_peano_to_int(s(P),X) :- convert_peano_to_int(P,X1), X is X1+1.
5327
5328 :- assert_must_succeed((kernel_objects:cardinality_greater_equal(Set,set(integer),int(X),integer,_WF), X=3,
5329 nonvar(Set),Set=[_|S2],nonvar(S2),S2=[_|S3],nonvar(S3),S3=[_|S4],var(S4), Set=[int(1),int(2),int(3)] )).
5330 :- assert_must_succeed((kernel_objects:cardinality_greater(Set,set(integer),int(X),integer,_WF), X=2,
5331 nonvar(Set),Set=[_|S2],nonvar(S2),S2=[_|S3],nonvar(S3),S3=[_|S4],var(S4), Set=[int(1),int(2),int(3)] )).
5332 /* special predicates called for e.g. card(Set)>X */
5333 cardinality_greater(Set,TypeSet,int(X),_,WF) :-
5334 kernel_objects:max_cardinality(TypeSet,MaxCard),
5335 (number(MaxCard) -> less_than(int(X),int(MaxCard)) ; true),
5336 ? card_greater2(Set,X,WF).
5337 :- block card_greater2(?,-,?).
5338 ?card_greater2(Set,X,WF) :- X1 is X+1, card_greater_equal2(Set,X1,WF).
5339
5340 cardinality_greater_equal(Set,TypeSet,int(X),_,WF) :-
5341 kernel_objects:max_cardinality(TypeSet,MaxCard),
5342 (number(MaxCard) -> less_than_equal(int(X),int(MaxCard)) ; true),
5343 ? card_greater_equal2(Set,X,WF).
5344 :- block card_greater_equal2(?,-,?).
5345 card_greater_equal2(Set,X,WF) :-
5346 (X<1 -> true % potential WD issue, hence this predicate should only be called when no wd issue
5347 ; X=1 -> not_empty_set_wf(Set,WF) % ditto: Set could be infinite
5348 ; var(Set) -> setup_ordered_list_skeleton(X,Set,open,WF)
5349 ; convert_int_to_peano(X,Peano), % for large X this leaves Peano partially unconstrained
5350 ? card_geq_wf(Set,Peano,WF)).
5351
5352
5353
5354 %is_cartesian_pair_or_times(P,X,Y) :- is_cartesian_pair(P,X,Y).
5355 %is_cartesian_pair_or_times(int(Z),int(X),int(Y)) :- times(int(X),int(Y),int(Z)).
5356
5357 is_cartesian_pair_wf((X,Y),XType,YType,WF) :-
5358 ? check_element_of_wf(X,XType,WF), check_element_of_wf(Y,YType,WF).
5359
5360 :- assert_must_succeed(exhaustive_kernel_check_wf(kernel_objects:not_is_cartesian_pair((int(1),int(1)),
5361 [int(1),int(2)],[int(2),int(3)],WF),WF)).
5362 :- assert_must_succeed(exhaustive_kernel_check_wf(kernel_objects:not_is_cartesian_pair((int(3),int(2)),
5363 [int(1),int(2)],[int(2),int(3)],WF),WF)).
5364 :- assert_must_succeed((kernel_objects:not_is_cartesian_pair((int(1),int(1)),
5365 [int(1),int(2)],[int(2),int(3)],_WF))).
5366 :- assert_must_succeed((kernel_objects:not_is_cartesian_pair((int(3),int(1)),
5367 [int(1),int(2)],[int(2),int(3)],_WF))).
5368 :- assert_must_fail((kernel_objects:not_is_cartesian_pair((int(1),int(3)),
5369 [int(1),int(2)],[int(2),int(3)],_WF))).
5370 :- assert_must_succeed((kernel_objects:not_is_cartesian_pair((X,int(3)),
5371 [int(1),int(2)],[int(2),int(3)],_WF),X=int(4))).
5372
5373
5374 not_is_cartesian_pair((X,Y),XType,YType,WF) :-
5375 ? not_is_cartesian_pair0(X,Y,XType,YType,WF).
5376
5377 :- block not_is_cartesian_pair0(-,-,?,?,?).
5378 not_is_cartesian_pair0(X,Y,XType,YType,WF) :-
5379 ? (nonvar(X) -> not_is_cartesian_pair1(X,Y,XType,YType,WF)
5380 ; not_is_cartesian_pair1(Y,X,YType,XType,WF)).
5381
5382 not_is_cartesian_pair1(X,Y,XType,YType,WF) :-
5383 membership_test_wf(XType,X,MemResX,WF),
5384 (var(MemResX) -> membership_test_wf(YType,Y,MemResY,WF) ; true),
5385 ? not_is_cartesian_pair3(MemResX,X,XType,MemResY,Y,YType,WF).
5386
5387 :- block not_is_cartesian_pair3(-,?,?, -,?,?, ?).
5388 not_is_cartesian_pair3(MemResX,X,XType, MemResY,Y,YType, WF) :-
5389 (MemResX==pred_false -> true
5390 ; MemResY==pred_false -> true
5391 ? ; MemResX==pred_true -> not_element_of_wf(Y,YType,WF)
5392 ; not_element_of_wf(X,XType,WF)
5393 ).
5394
5395
5396
5397 /***************************/
5398 /* power_set(Set,TypeSet) */
5399 /* Set : POW(TypeSet) */
5400 /***************************/
5401
5402 :- assert_must_succeed(exhaustive_kernel_check(power_set([int(2),int(4)],[[int(2)],
5403 [int(4)],[],[int(4),int(2)]]))).
5404 :- assert_must_succeed(power_set([int(1)],[[int(1)],[]])).
5405 :- assert_must_succeed((power_set([int(1),int(2)],R),
5406 equal_object(R,[[],[int(1)],[int(2)],[int(1),int(2)]]))).
5407 :- assert_must_succeed(power_set([],[[]])).
5408
5409 % not used anymore, except for empty set and singleton sets (see do_not_keep_symbolic_unary)
5410 :- block power_set(-,?).
5411 power_set([],Res) :- !,equal_object_optimized([[]],Res,power_set).
5412 power_set(Set1,Res) :- custom_explicit_sets:singleton_set(Set1,El),!,
5413 equal_object_optimized([[],[El]],Res,power_set).
5414 power_set(S,Res) :-
5415 cardinality_peano_wf(S,Card,no_wf_available),
5416 when(ground(Card), /* when all elements are known */
5417 (expand_custom_set_to_list_wf(S,SE,Done,power_set,no_wf_available),
5418 when(nonvar(Done),
5419 (gen_all_subsets(SE,PowerS),
5420 equal_object_optimized(PowerS,Res,power_set) )
5421 )
5422 )).
5423
5424 :- assert_must_succeed((kernel_objects:gen_all_subsets([X],R), R== [[],[X]])).
5425 :- assert_must_succeed((kernel_objects:gen_all_subsets([X,Y],R), R== [[],[Y],[X],[Y,X]])).
5426 % we do not use findall to keep variable links, see test 2103
5427 gen_all_subsets(List,AllSubLists) :- gen_all_subsets(List,[[]],AllSubLists).
5428 add_el(H,T,[H|T]).
5429 gen_all_subsets([],Acc,Acc).
5430 gen_all_subsets([H|T],Acc,Res) :- gen_all_subsets(T,Acc,R1),
5431 append(R1,R2,Res), % DCG would be better; but power_set is not really used anymore for longer lists
5432 maplist(add_el(H),Acc,Acc2), gen_all_subsets(T,Acc2,R2).
5433
5434
5435 :- assert_must_succeed(exhaustive_kernel_check(non_empty_power_set([int(2),int(4)],[[int(2)],
5436 [int(4)],[int(4),int(2)]]))).
5437 :- assert_must_succeed(non_empty_power_set([int(1)],[[int(1)]])).
5438 :- assert_must_succeed((non_empty_power_set([int(1),int(2)],R),
5439 equal_object(R,[[int(1)],[int(2)],[int(1),int(2)]]))).
5440 :- assert_must_succeed(non_empty_power_set([],[])).
5441
5442 :- block non_empty_power_set(-,?).
5443 non_empty_power_set([],Res) :- !,equal_object_optimized([],Res,non_empty_power_set).
5444 non_empty_power_set(Set1,Res) :- custom_explicit_sets:singleton_set(Set1,El),!,
5445 equal_object_optimized([[El]],Res,non_empty_power_set).
5446 non_empty_power_set(S,Res) :-
5447 cardinality_peano_wf(S,Card,no_wf_available),
5448 when(ground(Card), /* when all elements are known */
5449 (expand_custom_set_to_list_wf(S,SE,Done,non_empty_power_set,no_wf_available),
5450 when(nonvar(Done),
5451 (gen_all_subsets(SE,PowerS),
5452 delete(PowerS,[],NE_PowerS),
5453 equal_object_optimized(NE_PowerS,Res,non_empty_power_set) )
5454 )
5455 )).
5456
5457
5458
5459 /* ------- */
5460 /* BOOLEAN */
5461 /* ------- */
5462
5463 % following predicates are not used:
5464 %is_boolean(pred_true /* bool_true */).
5465 %is_boolean(pred_false /* bool_false */).
5466 %is_not_boolean(X) :- dif(X,pred_true /* bool_true */), dif(X,pred_false /* bool_false */).
5467
5468 /* ------- */
5469 /* NUMBERS */
5470 /* ------- */
5471
5472
5473 is_integer(int(X),_WF) :- when(ground(X),integer(X)).
5474 :- block is_not_integer(-).
5475 is_not_integer(X) :- X \= int(_), % will be called for x /: INTEGER; should always fail.
5476 add_internal_error('Wrong type argument: ',is_not_integer(X)),fail.
5477
5478 is_natural(int(X),_WF) :- clpfd_geq2(X,0,Posted), (Posted==true -> true ; number_geq(X,0)).
5479 is_natural1(int(X),_WF) :- clpfd_geq2(X,1,Posted), (Posted==true -> true ; number_geq(X,1)).
5480 :- block number_geq(-,?).
5481 number_geq(X,N) :- X>=N.
5482 :- block number_leq(-,?).
5483 number_leq(X,N) :- X=<N.
5484
5485 :- assert_must_succeed(is_implementable_int(int(0),_WF)).
5486 :- assert_must_fail(is_not_implementable_int(int(0))).
5487
5488
5489 is_implementable_int(int(X),WF) :- element_of_global_integer_set_wf('INT',X,WF,unknown).
5490 is_implementable_nat(int(X),WF) :- element_of_global_integer_set_wf('NAT',X,WF,unknown).
5491 is_implementable_nat1(int(X),WF) :- element_of_global_integer_set_wf('NAT1',X,WF,unknown).
5492 is_not_implementable_int(X) :- not_element_of_global_set(X,'INT').
5493 is_not_implementable_nat(X) :- not_element_of_global_set(X,'NAT').
5494 is_not_implementable_nat1(X) :- not_element_of_global_set(X,'NAT1').
5495
5496 is_not_natural(int(X)) :- clpfd_geq2(-1,X,Posted), (Posted=true -> true ; number_leq(X,-1)).
5497 is_not_natural1(int(X)) :- clpfd_geq2(0,X,Posted), (Posted==true -> true ; number_leq(X,0)).
5498
5499 :- assert_must_succeed(exhaustive_kernel_check(less_than(int(2),int(3)))).
5500 :- assert_must_succeed(( safe_less_than(A,B),A=3,B=5 )).
5501 :- assert_must_succeed(( safe_less_than(A,B),B=5,A=3 )).
5502 :- assert_must_fail(( safe_less_than(A,B),A=5,B=3 )).
5503 :- assert_must_fail(( safe_less_than(A,B),B=3,A=5 )).
5504 :- assert_must_fail(( safe_less_than(A,B),A=5,B=5 )).
5505 :- assert_must_fail(( safe_less_than(A,B),B=5,A=5 )).
5506
5507 less_than(int(X),int(Y)) :-
5508 (number(X),number(Y) -> X < Y
5509 ; clpfd_lt(X,Y,Posted),
5510 (Posted=true -> true ; safe_less_than(X,Y))).
5511 less_than_direct(X,Y) :-
5512 (number(X),number(Y) -> X < Y
5513 ; clpfd_lt(X,Y,Posted),
5514 (Posted=true -> true ; safe_less_than(X,Y))).
5515 :- block safe_less_than(-,?), safe_less_than(?,-).
5516 safe_less_than(X,Y) :-
5517 (number(X),number(Y) -> X<Y
5518 ; add_internal_error('Arguments not numbers: ',safe_less_than(X,Y))).
5519
5520 :- assert_must_succeed(exhaustive_kernel_check(less_than_equal(int(33),int(33)))).
5521 less_than_equal(int(X),int(Y)) :-
5522 (number(X),number(Y) -> X =< Y
5523 ; clpfd_leq(X,Y,Posted),
5524 (Posted=true -> true ; safe_less_than_equal(less_than_equal,X,Y))).
5525 less_than_equal_direct(X,Y) :-
5526 (number(X),number(Y) -> X =< Y
5527 ? ; clpfd_leq(X,Y,Posted),
5528 (Posted=true -> true ; safe_less_than_equal(less_than_equal_direct,X,Y))).
5529
5530 safe_less_than_equal(X,Y) :-
5531 safe_less_than_equal(safe_less_than_equal,X,Y).
5532 :- block safe_less_than_equal(?,-,?), safe_less_than_equal(?,?,-).
5533 safe_less_than_equal(PP,X,Y) :-
5534 (number(X),number(Y) -> X=<Y
5535 ; add_internal_error('Arguments not numbers: ',safe_less_than_equal(PP,X,Y))).
5536
5537 :- assert_must_succeed(exhaustive_kernel_check(greater_than(int(2),int(1)))).
5538 :- assert_must_succeed(exhaustive_kernel_fail_check(greater_than(int(2),int(2)))).
5539 greater_than(int(X),int(Y)) :- less_than_direct(Y,X).
5540 :- assert_must_succeed(exhaustive_kernel_check(greater_than(int(2),int(1)))).
5541 :- assert_must_succeed(exhaustive_kernel_check(greater_than_equal(int(2),int(2)))).
5542 :- assert_must_succeed(exhaustive_kernel_fail_check(greater_than_equal(int(1),int(2)))).
5543 greater_than_equal(int(X),int(Y)) :- less_than_equal_direct(Y,X).
5544
5545
5546
5547
5548
5549 :- assert_must_succeed(exhaustive_kernel_check([commutative],int_plus(int(2),int(3),int(5)))).
5550 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],int_plus(int(2),int(3),int(6)))).
5551
5552 :- assert_must_succeed(int_plus(int(1),int(2),int(3))).
5553 :- assert_must_succeed(( int_plus2(A,B,C),A=3,B=2,C==5 )).
5554 :- assert_must_succeed(( int_plus2(A,B,C),A=3,C=5,B==2 )).
5555 :- assert_must_succeed(( int_plus2(A,B,C),B=2,A=3,C==5 )).
5556 :- assert_must_succeed(( int_plus2(A,B,C),B=2,C=5,A==3 )).
5557 :- assert_must_succeed(( int_plus2(A,B,C),C=5,A=3,B==2 )).
5558 :- assert_must_succeed(( int_plus2(A,B,C),C=5,B=2,A==3 )).
5559 :- assert_must_succeed(( int_plus2(A,B,C),A=0,B==C )).
5560 :- assert_must_succeed(( int_plus2(A,B,C),B=0,A==C )).
5561
5562 int_plus(int(X),int(Y),int(Plus)) :-
5563 ? (two_vars_or_more(X,Y,Plus)
5564 -> clpfd_eq(Plus,X+Y) % can have performance problems
5565 ; true % otherwise we can compute the value directly below; we could skip the block declaration
5566 ),
5567 ? int_plus2(X,Y,Plus).
5568 two_vars_or_more(X,Y,Z) :- var(X),!, (var(Y) ; var(Z)).
5569 two_vars_or_more(_X,Y,Z) :- var(Y) , var(Z).
5570
5571 :- block int_plus2(-,-,-).
5572 int_plus2(X,Y,Plus) :-
5573 ? ( ground(X) -> int_plus3(X,Y,Plus)
5574 ; ground(Y) -> int_plus3(Y,X,Plus)
5575 ; int_minus3(Plus,X,Y)).
5576
5577 % int_plus3/3: the first argument must be ground when called
5578 int_plus3(0,Y,Plus) :- !, Y=Plus. % not inferred by CLP(FD): Z #= Y+X, X=0. does not infer Y==Z
5579 int_plus3(X,Y,Plus) :- % integer_dif(Y,Plus), % this generates overflows for test 1353, 1014
5580 ? int_plus4(X,Y,Plus).
5581
5582 % int_plus4/3: the first argument must be ground when called
5583 :- block int_plus4(?,-,-).
5584 int_plus4(X,Y,Plus) :-
5585 ( var(Plus) -> Plus is X+Y
5586 ; Y is Plus-X).
5587
5588 :- assert_must_succeed(exhaustive_kernel_check(int_minus(int(2),int(3),int(-1)))).
5589 :- assert_must_succeed(exhaustive_kernel_fail_check(int_minus(int(2),int(3),int(1)))).
5590 :- assert_must_succeed(int_minus(int(3),int(1),int(2))).
5591 :- assert_must_succeed(( int_minus2(A,B,C),A=3,B=2,C==1 )).
5592 :- assert_must_succeed(( int_minus2(A,B,C),A=3,C=1,B==2 )).
5593 :- assert_must_succeed(( int_minus2(A,B,C),B=2,A=3,C==1 )).
5594 :- assert_must_succeed(( int_minus2(A,B,C),B=2,C=1,A==3 )).
5595 :- assert_must_succeed(( int_minus2(A,B,C),C=1,A=3,B==2 )).
5596 :- assert_must_succeed(( int_minus2(A,B,C),C=1,B=2,A==3 )).
5597 :- assert_must_succeed(( int_minus2(A,B,C),B=0,A==C )).
5598 :- assert_must_succeed(( int_minus2(A,B,C),B=0,C=5,A==5 )).
5599 :- assert_must_succeed(( int_minus2(A,B,5),B=0,A==5 )).
5600
5601 int_minus(int(X),int(Y),int(Minus)) :-
5602 ? int_minus2(X,Y,Minus),
5603 ? (two_vars_or_more(X,Y,Minus) -> clpfd_eq(Minus,X-Y) % can have performance problems.
5604 % we could also set Minus to 0 if X==Y; this is done in CHR (chr_integer_inequality)
5605 ; true). % we can compute the value directly anyway
5606 :- block int_minus2(-,-,-).
5607 int_minus2(X,Y,Minus) :-
5608 ( ground(Y) ->
5609 ( Y=0 -> X=Minus
5610 ? ; Y2 is -Y, int_plus3(Y2,X,Minus))
5611 ; ground(X) ->
5612 ? int_minus3(X,Y,Minus)
5613 ; int_plus3(Minus,Y,X) % will infer that Y=X if Minus=0
5614 ).
5615
5616 % int_minus3/3: the first argument must be ground when called
5617 :- block int_minus3(?,-,-).
5618 int_minus3(X,Y,Minus) :-
5619 ( var(Minus) -> Minus is X-Y
5620 ; Y is X-Minus).
5621
5622 :- assert_must_succeed(exhaustive_kernel_check(division(int(2),int(3),int(0),unknown,_WF))).
5623 :- assert_must_succeed(exhaustive_kernel_check(division(int(7),int(2),int(3),unknown,_WF))).
5624 :- assert_must_succeed(exhaustive_kernel_check(division(int(8),int(2),int(4),unknown,_WF))).
5625 :- assert_must_succeed(exhaustive_kernel_check(division(int(9),int(2),int(4),unknown,_WF))).
5626 :- assert_must_succeed(exhaustive_kernel_check(division(int(2),int(-1),int(-2),unknown,_WF))).
5627 :- assert_must_succeed(exhaustive_kernel_check(division(int(9),int(-2),int(-4),unknown,_WF))).
5628 :- assert_must_succeed(exhaustive_kernel_check(division(int(-9),int(-3),int(3),unknown,_WF))).
5629 :- assert_must_succeed(exhaustive_kernel_check(division(int(-1),int(4),int(0),unknown,_WF))).
5630 :- assert_must_succeed((platform_is_64_bit
5631 -> exhaustive_kernel_check(division(int(4294967296),int(2),int(2147483648),unknown,_WF))
5632 ; exhaustive_kernel_check(division(int(134217728),int(2),int(67108864),unknown,_WF)))).
5633 :- assert_must_succeed((platform_is_64_bit
5634 -> exhaustive_kernel_check(division(int(4294967296),int(2147483648),int(2),unknown,_WF))
5635 ; exhaustive_kernel_check(division(int(134217728),int(67108864),int(2),unknown,_WF)))).
5636 :- assert_must_succeed(exhaustive_kernel_fail_check(division(int(2),int(3),int(1),unknown,_WF))).
5637 :- assert_must_succeed(( division3(A,B,C,unknown,_),A=15,B=4,C==3 )).
5638 :- assert_must_succeed(( division3(A,B,C,unknown,_),B=4,A=15,C==3 )).
5639
5640 division(int(X),int(Y),int(XDY),Span,WF) :- var(Y), (var(X) ; var(XDY)),
5641 preferences:preference(use_clpfd_solver,true),!,
5642 (preferences:preference(disprover_mode,true)
5643 -> clpfd_eq_div(XDY,X,Y) /* we can assume well-definedness */
5644 ; clpfd_eq_guarded_div(XDY,X,Y),
5645 % TO DO: we could set up a choice point just before enumeration of infinite types for Y=0 & Y/=0;
5646 % same for modulo
5647 check_nonzero(X,Y,XDY,Span,WF)
5648 ).
5649 division(int(X),int(Y),int(XDY),Span,WF) :-
5650 %% clpfd_eq_expr(XDY,X/Y), % can have performance problems; could hide division by 0 !
5651 division3(X,Y,XDY,Span,WF).
5652
5653 :- block check_nonzero(?,-,?,?,?).
5654 check_nonzero(X,Y,XDY,Span,WF) :-
5655 (Y=0 -> add_wd_error_set_result('division by zero','/'(X,Y),XDY,0,Span,WF)
5656 ; true).
5657
5658 :- block division3(?,-,?,?,?).
5659 division3(X,Y,XDY,Span,WF) :-
5660 ( Y==0 -> add_wd_error_set_result('division by zero','/'(X,Y),XDY,0,Span,WF)
5661 ; nonvar(X) -> XDY is X // Y
5662 ; Y == 1 -> X=XDY
5663 ; Y == -1,nonvar(XDY) -> X is -XDY
5664 ; clpfd_eq_div(XDY,X,Y)). % we could setup constraint before Y is known; could hide division by 0 ?
5665
5666
5667
5668 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(2),int(3),int(0),unknown,_WF))).
5669 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(7),int(2),int(3),unknown,_WF))).
5670 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(-1),int(4),int(-1),unknown,_WF))).
5671 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(-9),int(-3),int(3),unknown,_WF))).
5672 floored_division(int(X),int(Y),int(XDY),Span,WF) :- var(Y), (var(X) ; var(XDY)),
5673 preferences:preference(use_clpfd_solver,true),!,
5674 (preferences:preference(disprover_mode,true)
5675 -> clpfd_eq_fdiv(XDY,X,Y) /* we can assume well-definedness */
5676 ; clpfd_eq_guarded_fdiv(XDY,X,Y),
5677 check_nonzero(X,Y,XDY,Span,WF)
5678 ).
5679 floored_division(int(X),int(Y),int(XDY),Span,WF) :-
5680 %% clpfd_eq_expr(XDY,X/Y), % can have performance problems; could hide division by 0 !
5681 floored_division3(X,Y,XDY,Span,WF).
5682 :- block floored_division3(?,-,?,?,?).
5683 floored_division3(X,Y,XDY,Span,WF) :-
5684 ( Y==0 -> add_wd_error_set_result('division by zero','/'(X,Y),XDY,0,Span,WF)
5685 ; nonvar(X) -> XDY is X div Y
5686 ; Y == 1 -> X=XDY
5687 ; (Y == -1,nonvar(XDY)) -> X is -XDY
5688 ; clpfd_eq_guarded_fdiv(XDY,X,Y)). % we could setup constraint before Y is known; could hide division by 0 ?
5689
5690 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(2),int(3),int(2),unknown,WF),WF)).
5691 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(7),int(2),int(1),unknown,WF),WF)).
5692 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(8),int(2),int(0),unknown,WF),WF)).
5693 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(9),int(2),int(1),unknown,WF),WF)).
5694 :- assert_must_succeed((platform_is_64_bit
5695 -> exhaustive_kernel_check_wfdet(modulo(int(4294967296),int(2147483648),int(0),unknown,WF),WF)
5696 ; exhaustive_kernel_check_wfdet(modulo(int(134217728),int(67108864),int(0),unknown,WF),WF))).
5697 :- assert_must_succeed((platform_is_64_bit
5698 -> exhaustive_kernel_check_wfdet(modulo(int(4294967299),int(2147483648),int(3),unknown,WF),WF)
5699 ; exhaustive_kernel_check_wfdet(modulo(int(134217731),int(67108864),int(3),unknown,WF),WF))).
5700 :- assert_must_succeed(( modulo2(A,B,C,unknown,_),A=7,B=5,C==2 )).
5701 :- assert_must_fail(( modulo2(A,B,C,unknown,_),A=7,B=5,C==3 )).
5702
5703 modulo(int(X),int(Y),int(Modulo),Span,WF) :-
5704 %% clpfd_eq(Modulo,X mod Y), % can have performance problems; could hide division by 0 !
5705 modulo2(X,Y,Modulo,Span,WF),
5706 % assert that Modulo<Y, Modulo>=0
5707 (nonvar(X),nonvar(Y) -> true % we already have computed Modulo using modulo2
5708 ; nonvar(Modulo), Modulo < 0 -> true % we will generate well-definedness error; see comment next line
5709 ; number(Y),Y =< 0 -> true % in this case we will generate a well-definedness error; it would be more efficient from a constraint solving perspective to assume that there are no well-definedness errors and remove this case !!
5710 ; clpfd_modulo_prop(X,Y,Modulo,WF)
5711 ).
5712 :- use_module(specfile,[z_or_tla_minor_mode/0]).
5713 :- block modulo2(-,?,?,?,?), modulo2(?,-,?,?,?).
5714 modulo2(X,Y,Modulo,Span,WF) :-
5715 ( Y>0 -> (X<0 -> (z_or_tla_minor_mode -> Modulo is X mod Y
5716 ; add_wd_error_set_result('mod not defined for negative numbers in B:',mod(X,Y),Modulo,0,Span,WF))
5717 ; Modulo is X mod Y)
5718 ; Y==0 -> add_wd_error_set_result('mod by zero:',mod(X,Y),Modulo,0,Span,WF)
5719 ; Y<0 -> add_wd_error_set_result('mod not defined for negative numbers:',mod(X,Y),Modulo,0,Span,WF)). % there seems to be a definition in Z ? at least for Z Live ?
5720
5721 % propagate information about Modulo result if part of the information known
5722 clpfd_modulo_prop(X,Y,Modulo,WF) :- %preferences:preference(use_clpfd_solver,true),!,
5723 % in CLP(FD) this is sufficient; for non-CLPFD mode it is better to call in_nat_range to restrict enumeration
5724 less_than_direct(Modulo,Y),
5725 less_than_equal_direct(0,Modulo), % 0 <= Modulo < Y -> by transitivity this forces Y>0 and we no longer detect wd-errors
5726 %less_than_equal_direct(Modulo,X). % by transitivity this imposes X >= 0 and we will never find WD problems with negative X
5727 (preference(use_clpfd_solver,true)
5728 -> get_wait_flag0(WF,WF0),
5729 % avoid propagating complex too early, e.g., for x>2 & x:3..10 & x mod 3 = 1 & x mod 3 = 2 in test 2126
5730 % also see test 1959 which was initially failing due to adding WF0 delay
5731 clpfd_modulo_prop2(X,Y,Modulo,WF0)
5732 ; true).
5733
5734 :- block clpfd_modulo_prop2(?,?,?,-).
5735 clpfd_modulo_prop2(X,Y,Modulo,_WF0) :-
5736 number(Modulo), % this test is required for test 1009, 417 : TO DO : investigate cause
5737 var(X), % or should this be var(X) ; var(Y) ??
5738 fd_min(Y,MinY), number(MinY), MinY>0,
5739 fd_min(X,MinX), number(MinX), MinX>=0, % modulo is well-defined
5740 !,
5741 clpfd_interface:clpfd_leq_expr(Modulo,X),
5742 clpfd_interface:try_post_constraint(Modulo #= X mod Y).
5743 %clpfd_modulo_prop2(X,Y,Modulo,_WF0) :- number(Y),!,
5744 % % also makes tests 1009, 417 fail, but would enable solving x mod 256 = 0 & x>0
5745 % clpfd_interface:try_post_constraint(X#>=0 #=> Modulo #= X mod Y). % will also assert X#>Modulo
5746 clpfd_modulo_prop2(X,_Y,_Modulo,_WF0) :- X==0,!. % no need to propagate, we already assert 0 <= Modulo above
5747 clpfd_modulo_prop2(X,_Y,Modulo,_WF0) :-
5748 clpfd_interface:try_post_constraint(X#>=0 #=> X#>=Modulo). % this would be faster (e.g., {y|y:100000..200000 & y mod 2 = 0}), but would not catch some WD errors: clpfd_interface:try_post_constraint(X#>=Modulo).
5749 % we could reify: Y>0 => Modulo <Y ? Is it worth it ?
5750 % we could also use the CLP(FD) modulo operator X in 3..100, 1 #= X mod 20 infers X in 21..81
5751 % try_post_constraint((X#>=0 #/\ Y#>0) #=> Modulo #= X mod Y)
5752 % what is still missing is that if Y < Modulo => X=Y (CLP(FD) does this X in 0..100 , Y in 2..20 , X #= Y mod 30.)
5753 /* clpfd_modulo_prop(X,Y,Modulo,WF) :- clpfd_modulo_noclp(X,Y,Modulo,WF).
5754 :- block clpfd_modulo_noclp(-,-,-,?).
5755 clpfd_modulo_noclp(X,Y,Modulo,WF) :- print(mod(X,Y,Modulo,WF)),nl,
5756 var(X),var(Modulo),number(Y),!,
5757 Y1 is Y-1,
5758 in_nat_range_wf(int(Modulo),int(0),int(Y1),WF). % problem: could enumerate lambda return variables !!
5759 clpfd_modulo_noclp(_X,_Y,_Modulo,_WF).
5760 */
5761
5762
5763 :- assert_must_succeed(exhaustive_kernel_check(unary_minus_wf(int(2),int(-2),_WF))).
5764 :- assert_must_succeed(exhaustive_kernel_fail_check(unary_minus_wf(int(2),int(2),_WF))).
5765 :- assert_must_succeed(( unary_minus2(A,B),A=7,B== -7 )).
5766 :- assert_must_succeed(( unary_minus2(A,B),A= -7,B==7 )).
5767 :- assert_must_succeed(( unary_minus2(B,A),A=7,B== -7 )).
5768 :- assert_must_succeed(( unary_minus2(B,A),A= -7,B==7 )).
5769 :- assert_must_fail(( unary_minus2(B,A),A= -7,B=6 )).
5770 :- assert_must_fail(( unary_minus2(A,B),A= -7,B=6 )).
5771
5772 unary_minus_wf(int(X),int(MX),_WF) :-
5773 unary_minus2(X,MX),
5774 (var(X),var(MX) -> clpfd_eq(MX,0 - X) % can have performance problems
5775 ; true % we can compute the value without CLPFD
5776 ).
5777 :- block unary_minus2(-,-).
5778 unary_minus2(X,MX) :-
5779 ( ground(X) -> MX is -X
5780 ; X is -MX).
5781
5782 :- assert_must_succeed(exhaustive_kernel_check(first_of_pair_wf((int(1),int(2)),int(1),_WF))).
5783 :- assert_must_succeed(exhaustive_kernel_check(second_of_pair_wf((int(1),int(2)),int(2),_WF))).
5784
5785 ?first_of_pair_wf((A,_B),R,WF) :- equal_object_wf(R,A,first_of_pair,WF).
5786 ?second_of_pair_wf((_A,B),R,WF) :- equal_object_wf(R,B,second_of_pair,WF).
5787
5788
5789
5790 :- assert_must_succeed(exhaustive_kernel_check(cartesian_product([int(2),int(4)],[int(3),int(1)],
5791 [(int(2),int(1)),(int(2),int(3)),(int(4),int(3)),(int(4),int(1))]))).
5792 :- assert_must_succeed(exhaustive_kernel_check(cartesian_product([],[int(3),int(1)],[]))).
5793 :- assert_must_succeed(exhaustive_kernel_check(cartesian_product([int(3)],[],[]))).
5794 :- assert_must_succeed(exhaustive_kernel_fail_check(cartesian_product([int(3)],[int(2)],[]))).
5795 :- assert_must_succeed((cartesian_product(global_set('NAT'),[int(2)],_Res))).
5796 :- assert_must_succeed((cartesian_product([int(1)],[int(2)],Res),
5797 equal_object(Res,[(int(1),int(2))]))).
5798 :- assert_must_succeed((cartesian_product([int(1)],[int(2)],[(int(1),int(2))]))).
5799 :- assert_must_succeed((cartesian_product([],[int(1),int(2)],Res),
5800 equal_object(Res,[]))).
5801 :- assert_must_succeed((cartesian_product([int(1),int(2)],[],Res),
5802 equal_object(Res,[]))).
5803 :- assert_must_succeed((cartesian_product([int(1),int(2)],[int(2),int(3)],Res),
5804 equal_object(Res,[(int(1),int(2)),(int(1),int(3)),(int(2),int(2)),(int(2),int(3))]))).
5805 :- assert_must_succeed((cartesian_product([int(1)|T],[int(2)|T2],Res),
5806 T = [int(2)], T2 = [int(3)],
5807 equal_object(Res,[(int(1),int(2)),(int(1),int(3)),(int(2),int(2)),(int(2),int(3))]))).
5808 :- assert_must_fail((cartesian_product([int(1)],[int(2),int(3)],Res),(Res=[_];
5809 equal_object(Res,[_,_,_|_])))).
5810
5811
5812 cartesian_product(Set1,Set2,Res) :- cartesian_product_wf(Set1,Set2,Res,no_wf_available).
5813
5814 :- block cartesian_product_wf(-,?,?,?), cartesian_product_wf(?,-,?,?).
5815 cartesian_product_wf(Set1,Set2,Res,WF) :-
5816 expand_custom_set_to_list_wf(Set1,ESet1,_,cartesian_product1,WF),
5817 (ESet1==[] -> empty_set_wf(Res,WF)
5818 ; expand_custom_set_to_list_wf(Set2,ESet2,_,cartesian_product2,WF),
5819 (var(Res)
5820 -> cartesian_product2(ESet1,ESet2,CRes,WF),
5821 equal_object_optimized_wf(CRes,Res,cart_product,WF)
5822 ; cartesian_product2(ESet1,ESet2,Res,WF))
5823 ).
5824
5825 :- block cartesian_product2(-,?,?,?).
5826 cartesian_product2([],_,Res,WF) :- empty_set_wf(Res,WF).
5827 cartesian_product2([H|T],Set2,Res,WF) :-
5828 cartesian_el_product(Set2,H,Res,InnerRes,WF),
5829 cartesian_product2(T,Set2,InnerRes,WF).
5830
5831 :- block cartesian_el_product(-,?,?,?,?).
5832 cartesian_el_product([],_El,Res,InnerRes,WF) :- equal_object_optimized_wf(Res,InnerRes,cartesian_el_product_1,WF).
5833 cartesian_el_product([H|T],El,ResSoFar,InnerRes,WF) :-
5834 equal_object_wf(ResSoFar,[(El,H)|NewResSoFar],cartesian_el_product_2,WF),
5835 cartesian_el_product(T,El,NewResSoFar,InnerRes,WF).
5836
5837
5838
5839 :- assert_must_succeed(exhaustive_kernel_check(in_nat_range(int(2),int(2),int(3)))).
5840 :- assert_must_succeed(exhaustive_kernel_check(in_nat_range_wf(int(2),int(2),int(3),_WF))).
5841 :- assert_must_succeed(exhaustive_kernel_fail_check(in_nat_range_wf(int(2),int(3),int(2),_WF))).
5842 :- assert_must_succeed((in_nat_range_wf(X,int(11),int(12),WF),
5843 kernel_waitflags:ground_wait_flags(WF), X==int(12) )).
5844 :- assert_must_fail((in_nat_range_wf(X,int(11),int(12),_WF), X=int(10) )).
5845 :- assert_must_fail((in_nat_range_wf(X,int(11),int(12),_WF), X=int(13) )).
5846 :- assert_must_succeed((in_nat_range_wf(X,int(11),int(12),_WF), X=int(11) )).
5847 :- assert_must_fail((in_nat_range_wf(X,int(11),int(10),_WF), X=int(11) )).
5848 :- assert_must_fail((in_nat_range_wf(X,int(11),int(10),_WF), X=int(10) )).
5849 :- assert_must_fail((in_nat_range_wf(X,int(11),int(10),_WF), X=int(12) )).
5850
5851 in_nat_range(int(X),int(Y),int(Z)) :- % does not enumerate, in contrast to in_nat_range_wf
5852 clpfd_inrange(X,Y,Z,Posted), % better to call inrange rather than leq twice, avoids unecessary propagation
5853 (Posted==true -> true
5854 ; safe_less_than_equal(in_nat_range,Y,X),
5855 safe_less_than_equal(in_nat_range,X,Z)
5856 ).
5857 in_nat_range_wf(int(X),int(Y),int(Z),WF) :-
5858 ? clpfd_inrange(X,Y,Z,Posted), % better to call inrange rather than leq twice, avoids unecessary propagation
5859 (Posted==true, WF \== no_wf_available ->
5860 % if the constraint was posted: we do not need to add safe_less_than_equal,...:
5861 % if overflow happes whole computation will fail anyway
5862 block_add_fd_variable_for_labeling(X,Y,Z,WF) % do we really need to do this ? maybe add just before enum finished ?, see also test 328
5863 ; safe_less_than_equal(in_nat_range_wf,Y,X),
5864 safe_less_than_equal(in_nat_range_wf,X,Z),
5865 (ground(X) -> true
5866 ; get_int_domain(X,Y,Z,RL,RU),get_nat_range_prio(X,RL,RU,WF,LWF),
5867 ? call_enumerate_int(X,RL,RU,LWF))
5868 ).
5869
5870 :- block block_add_fd_variable_for_labeling(-,-,?,?), block_add_fd_variable_for_labeling(?,-,-,?).
5871 block_add_fd_variable_for_labeling(X,_Y,_Z,_WF) :- nonvar(X),!. % no need to label it
5872 block_add_fd_variable_for_labeling(X,_Y,_Z,WF) :- try_add_fd_variable_for_labeling(X,WF).
5873
5874 :- block get_nat_range_prio(?,-,?,?,?), get_nat_range_prio(?,?,-,?,?).
5875 get_nat_range_prio(_Variable,Y,Z,WF,LWF) :- Size is Z+1-Y,
5876 (Size>1 ->
5877 % we do not use try_add_fd_variable_for_labeling(Variable,Size,WF,LWF) % will use CLP(FD) labeling
5878 % either clpfd is off or we had a time-out or overflow; so labeling may generate instantiation error
5879 get_wait_flag(Size,get_nat_range_prio(Y,Z),WF,LWF)
5880 ; LWF=Size /* Size=0 or 1 -> we can either fail or determine variable */).
5881
5882 :- assert_must_succeed((kernel_objects:call_enumerate_int(X,1,2,g), X==2)).
5883 :- block call_enumerate_int(-,?,?,-).
5884 call_enumerate_int(X,RL,RU,_LWF) :-
5885 (ground(X) -> true
5886 ; % get_int_domain(X,RL,RU,RLL,RUU) : if clp(fd) active then CLP(FD) labeling is used anyway
5887 ? enumerate_int(X,RL,RU)).
5888
5889
5890
5891
5892 :- assert_must_succeed(exhaustive_kernel_check(not_in_nat_range(int(2),int(3),int(2)))).
5893 :- assert_must_succeed(exhaustive_kernel_fail_check(not_in_nat_range(int(2),int(2),int(3)))).
5894 :- assert_must_succeed((not_in_nat_range(X,int(11),int(12)), X=int(10) )).
5895 :- assert_must_succeed((not_in_nat_range(X,int(11),int(12)), X=int(13) )).
5896 :- assert_must_fail((not_in_nat_range(X,int(11),int(12)), X=int(11) )).
5897 :- assert_must_succeed((not_in_nat_range(X,int(11),int(10)), X=int(11) )).
5898 :- assert_must_succeed((not_in_nat_range(X,int(11),int(10)), X=int(10) )).
5899 :- assert_must_succeed((not_in_nat_range(X,int(11),int(10)), X=int(12) )).
5900
5901 ?not_in_nat_range_wf(X,Y,Z,_WF) :- not_in_nat_range(X,Y,Z).
5902 not_in_nat_range(int(X),int(Y),int(Z)) :-
5903 (number(Y),number(Z)
5904 ? -> (Z>=Y -> clpfd_not_in_non_empty_range(X,Y,Z) ; true /* interval empty */)
5905 ; clpfd_not_inrange(X,Y,Z)
5906 ).
5907
5908
5909 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(1),int(0),int(10),pred_true,WF),WF)).
5910 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(10),int(10),int(10),pred_true,WF),WF)).
5911 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(1),int(1),int(10),pred_true,WF),WF)).
5912 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(10),int(0),int(10),pred_true,WF),WF)).
5913 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(11),int(10),int(9),pred_false,WF),WF)).
5914 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(11),int(13),int(12),pred_false,WF),WF)).
5915 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(11),int(13),int(15),pred_false,WF),WF)).
5916
5917 % reified version
5918 :- block test_in_nat_range_wf(-,-,?,-,?), test_in_nat_range_wf(-,?,-,-,?), test_in_nat_range_wf(?,-,-,-,?).
5919 test_in_nat_range_wf(X,Y,Z,PredRes,WF) :- PredRes==pred_true,!,
5920 in_nat_range_wf(X,Y,Z,WF).
5921 test_in_nat_range_wf(X,Y,Z,PredRes,WF) :- PredRes==pred_false,!,
5922 ? not_in_nat_range_wf(X,Y,Z,WF).
5923 test_in_nat_range_wf(int(X),int(Low),int(Up),PredRes,WF) :-
5924 clpfd_interface:post_constraint2(C1 #<=> (X #>= Low #/\ X #=< Up #/\ Low #=< Up),Posted1),
5925 (Posted1 == true -> prop_01(C1,PredRes) ; test_in_nat_range_no_clpfd(X,Low,Up,PredRes,WF)).
5926
5927 % Note: A #<=> (X #>= Low #/\ X#=< Up #/\ Low #=< Up), Low in 11..15, Up in 7..8. -> CLPFD infers A=0
5928 % without the redundant Low #=< Up it does not infer it !
5929 :- block prop_01(-,-).
5930 prop_01(0,pred_false).
5931 prop_01(1,pred_true).
5932
5933 :- block test_in_nat_range_no_clpfd(-,?,?,-,?), test_in_nat_range_no_clpfd(?,-,?,-,?),
5934 test_in_nat_range_no_clpfd(?,?,-,-,?).
5935 test_in_nat_range_no_clpfd(X,Y,Z,PredRes,WF) :- PredRes==pred_true,!,
5936 in_nat_range_wf(int(X),int(Y),int(Z),WF).
5937 test_in_nat_range_no_clpfd(X,Y,Z,PredRes,WF) :- PredRes==pred_false,!,
5938 not_in_nat_range_wf(int(X),int(Y),int(Z),WF).
5939 test_in_nat_range_no_clpfd(X,Y,Z,PredRes,_WF) :- % X,Y,Z must be ground integers
5940 (X >= Y, X =< Z, Y =< Z -> PredRes=pred_true ; PredRes=pred_false).
5941
5942 :- assert_must_succeed(exhaustive_kernel_check_wf(square(int(3),int(9),WF),WF)).
5943 % is now only called when CLPFD is FALSE
5944 square(int(X),int(Sqr),WF) :-
5945 int_square(X,Sqr,WF),
5946 (var(X) -> clpfd_eq(Sqr,X * X)
5947 ; true). % we can compute the value directly
5948
5949 :- block int_square(-,-,?).
5950 int_square(X,Sqr,_) :- ground(X),!, Sqr is X*X.
5951 int_square(X,Sqr,WF) :- get_binary_choice_wait_flag(int_square,WF,WF2), int_square2(X,Sqr,WF2).
5952 :- block int_square2(-,?,-).
5953 int_square2(X,Sqr,_) :- ground(X),!, Sqr is X*X.
5954 int_square2(X,Sqr,_WF2) :-
5955 integer_square_root(Sqr,X).
5956
5957 :- assert_must_succeed(( kernel_objects:integer_square_root(0,X),X==0 )).
5958 :- assert_must_succeed(( kernel_objects:integer_square_root(1,X),X==1 )).
5959 :- assert_must_succeed(( kernel_objects:integer_square_root(4,X),X==2 )).
5960 :- assert_must_succeed(( kernel_objects:integer_square_root(49,X),X==7 )).
5961 :- assert_must_succeed(( kernel_objects:integer_square_root(49,X),X==(-7) )).
5962 :- assert_must_fail(( kernel_objects:integer_square_root(5,_) )).
5963 :- assert_must_succeed(( X= 123456789, Y is X*X, kernel_objects:integer_square_root(Y,Z),Z==X)).
5964 :- assert_must_fail(( X= 123456789, Y is 1+X*X, kernel_objects:integer_square_root(Y,_Z))).
5965 :- assert_must_succeed(( X= 12345678900, Y is X*X, kernel_objects:integer_square_root(Y,Z),Z==X)).
5966
5967 integer_square_root(0,Root) :- !, Root = 0.
5968 :- if(current_prolog_flag(dialect, swi)).
5969 % SWI's behavior when converting bigint to float is suboptimal -
5970 % the value is always truncated toward zero instead of rounded to the nearest value,
5971 % which introduces slight inaccuracies that don't happen on SICStus.
5972 % See: https://github.com/SWI-Prolog/swipl-devel/issues/545
5973 % As a workaround, use CLP(FD) to calculate integer square roots.
5974 % On SWI, CLP(FD) works with unlimited size integers and can calculate exact integer n-th roots.
5975 :- use_module(library(clpfd), [(#=)/2, (#>)/2, (#=<)/2]).
5976 integer_square_root(Sqr,Root) :-
5977 Root*Root #= Sqr,
5978 (Root #> 0 ; Root #=< 0).
5979 :- else.
5980 integer_square_root(Sqr,PMRoot) :-
5981 Sqr>0, exact_integer_floor_sqrt(Sqr,Root), Sqr is Root*Root,
5982 (PMRoot = Root ; PMRoot is -(Root)).
5983
5984 % compute floor of square root using Newton's method on integers only
5985 % Note: truncate(sqrt(Sqr)) is not precise for integers above 2^53 and raises a float overflow for very large integers
5986 exact_integer_floor_sqrt(Sqr,Root) :-
5987 R0 is 1 << ((msb(Sqr)//2)+1), % R0 is strictly larger than the square root
5988 exact_integer_floor_sqrt_newton(Sqr,R0,Root).
5989 exact_integer_floor_sqrt_newton(Sqr,R0,Root) :-
5990 R1 is (R0 + Sqr//R0)//2,
5991 (R1 >= R0 -> Root=R0 ; exact_integer_floor_sqrt_newton(Sqr,R1,Root)).
5992 :- endif.
5993
5994 % integer multiplication
5995 times(int(X),int(Y),int(Times)) :-
5996 int_times2(X,Y,Times),
5997 ? (two_vars_or_more(X,Y,Times) -> clpfd_eq(Times,X * Y) % can have performance problems.
5998 ; true). % we can compute the value directly
5999
6000 :- assert_must_succeed(exhaustive_kernel_check([commutative],times(int(2),int(3),int(6)))).
6001 :- assert_must_succeed(exhaustive_kernel_check([commutative],times(int(2),int(1),int(2)))).
6002 :- assert_must_succeed(exhaustive_kernel_check([commutative],times(int(2),int(0),int(0)))).
6003 :- assert_must_succeed(exhaustive_kernel_check(times(int(0),int(1),int(0)))).
6004 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],times(int(2),int(3),int(5)))).
6005 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],times(int(1),int(3),int(2)))).
6006 :- assert_must_succeed((A is -10, B is -30,
6007 exhaustive_kernel_check([commutative],times(int(A),int(B),int(300))))).
6008 :- assert_must_succeed(( int_times2(A,B,C),A=3,B=2,C==6 )).
6009 :- assert_must_succeed(( int_times2(A,B,C),A=3,C=6,B==2 )).
6010 :- assert_must_succeed(( int_times2(A,B,C),B=2,A=3,C==6 )).
6011 :- assert_must_succeed(( int_times2(A,B,C),B=2,C=6,A==3 )).
6012 :- assert_must_succeed(( int_times2(A,B,C),C=6,A=3,B==2 )).
6013 :- assert_must_succeed(( int_times2(A,B,C),C=6,B=2,A==3 )).
6014 :- assert_must_succeed(( int_times2(A,_,C),A=0,C==0 )).
6015 :- assert_must_succeed(( int_times2(_,B,C),B=0,C==0 )).
6016 :- assert_must_succeed(( int_times2(A,B,C),A=1,B==C )).
6017 :- assert_must_succeed(( int_times2(A,B,C),B=1,A==C )).
6018 :- assert_must_succeed(( int_times2(A,1,C),A=2,C==2 )).
6019 :- assert_must_succeed(( int_times2(_A,0,C),C==0 )).
6020 :- assert_must_succeed(( int_times2(A,_,C),C=0,A=0 )).
6021 :- assert_must_succeed(( int_times2(_,B,C),C=0,B=0 )).
6022 :- assert_must_succeed(( int_times2(A,B,0),A=0,B=2 )).
6023 :- assert_must_succeed(( int_times2(A,B,0),B=2,A=0 )).
6024 :- assert_must_succeed(( int_times2(B,A,0),A=0,B=2 )).
6025 :- assert_must_succeed(( int_times2(B,A,0),B=2,A=0 )).
6026 :- assert_must_fail(( int_times2(A,_,C),A=3,C=7 )).
6027 :- assert_must_fail(( int_times2(A,_,C),C=7,A=3 )).
6028 :- assert_must_fail(( int_times2(_,B,C),B=2,C=7 )).
6029 :- assert_must_fail(( int_times2(_,B,C),C=7,B=2 )).
6030 :- assert_must_fail(( int_times2(A,_,C),C=7,A=0 )).
6031 :- assert_must_fail(( int_times2(_,B,C),C=7,B=0 )).
6032 :- assert_must_fail(( int_times2(B,A,0),B=2,A=1 )).
6033
6034 :- block int_times2(-,-,-).
6035 int_times2(X,Y,Times) :-
6036 ( ground(X) ->
6037 ( X==1 -> Y=Times
6038 ; X==0 -> Times=0
6039 ; int_times3(X,Y,Times))
6040 ; ground(Y) ->
6041 ( Y==1 -> X=Times
6042 ; Y==0 -> Times=0
6043 ; int_times3(Y,X,Times))
6044 ; int_times4(X,Y,Times)).
6045 % int_times3/3: First argument must be ground when called and non-zero
6046 :- block int_times3(?,-,-).
6047 int_times3(X,Y,Times) :-
6048 ( ground(Y) -> Times is X*Y
6049 ; Y is Times // X, Times is X*Y).
6050 % int_times4/3: Third argument must be ground when called
6051 :- block int_times4(-,-,?).
6052 int_times4(X,Y,Times) :-
6053 ( Times==0 ->
6054 ( ground(X) -> (X==0 -> true; Y=0 )
6055 ; /* ground(Y) -> */ (Y==0 -> true; X=0 ))
6056 ; /* Times /== 0 */
6057 ( ground(X) -> X\==0, Y is Times // X, Times is X*Y
6058 ; /* ground(Y) -> */ Y\==0, X is Times // Y, Times is X*Y)).
6059
6060
6061 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(2),int(3),int(8),unknown,_))).
6062 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(2),int(1),int(2),unknown,_))).
6063 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(3),int(0),int(1),unknown,_))).
6064 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(1),int(3),int(1),unknown,_))).
6065 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(0),int(3),int(0),unknown,_))).
6066 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(0),int(0),int(1),unknown,_))).
6067 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(2),int(10),int(1024),unknown,_))).
6068 :- assert_must_succeed(exhaustive_kernel_fail_check(int_power(int(2),int(3),int(6),unknown,_))).
6069 :- assert_must_succeed(exhaustive_kernel_fail_check(int_power(int(0),int(0),int(0),unknown,_))).
6070 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=2,B=5,C==32 )).
6071 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A= -2,B=5,C== -32 )).
6072 %:- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=1,B= -5,C==1 )). % now aborts !
6073 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=1,C=1, B= -5 )).
6074 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=1,C= 1,B = -5 )).
6075 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=2,C=32,B==5 )).
6076 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=10,C=1000,B==3 )).
6077 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A= -2,C= -32,B==5 )).
6078 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A= -2,C= 16,B==4 )).
6079 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=2,C=1,B==0 )).
6080 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,B=2,C==0 )).
6081 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,C=0,B=2 )).
6082 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,B=0,C==1 )).
6083 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,C=1,B==0 )).
6084 :- assert_must_succeed(( int_power2(17,13,C,unknown,_),C==9904578032905937 )).
6085 :- assert_must_succeed((platform_is_64_bit
6086 -> int_power2(A,13,C,unknown,_),C=9904578032905937,A=17
6087 ; int_power2(A,9,C,unknown,_),C=134217728,A=8 )).
6088 :- assert_must_fail((platform_is_64_bit
6089 -> int_power2(A,13,C,unknown,_),C=9904578032905936,A=17
6090 ; int_power2(A,9,C,unknown,_),C=134217727,A=8 )).
6091 :- assert_must_succeed((platform_is_64_bit
6092 -> int_power2(A,10,C,unknown,_),C=576650390625,A=15
6093 ; true)).
6094 :- assert_must_fail((platform_is_64_bit
6095 -> int_power2(A,10,C,unknown,_),C=576650390626,A=15
6096 ; false)).
6097 :- assert_must_succeed(( int_power2(A,100,C,unknown,_),A=2,C==1267650600228229401496703205376 )).
6098 :- assert_must_fail(( int_power2(A,100,C,unknown,_),C=1267650600228229401496703205375,A=2 )).
6099 :- assert_must_fail(( int_power2(A,100,C,unknown,_),C=1267650600228229401496703205377,A=2 )).
6100
6101 :- assert_must_fail(( int_power2(A,B,C,unknown,_),A=2,B=5,C=33 )).
6102 :- assert_must_abort_wf(( int_power2(A,B,_,unknown,WF),A=2,B= -5 ),WF).
6103 :- assert_must_fail(( int_power2(A,_,C,unknown,_),A= -2,C=32 )).
6104 :- assert_must_fail(( int_power2(A,_,C,unknown,_),A= -2,C= -16 )).
6105 % Note: 0**0=1 (see SIMP_SPECIAL_EXPN_0 in https://wiki.event-b.org/index.php/All_Rewrite_Rules)
6106 % TODO: in TLA+ it is undefined (TLC says 0^0 is undefined.)
6107
6108 :- use_module(specfile,[eventb_mode/0]).
6109 % TODO: calculate X from Y und Pow (i.e., Yth root of Pow); in CLPFD mode this is more or less done
6110 int_power(int(X),int(Y),int(Pow),Span,WF) :- % power_of AST node
6111 ( preferences:preference(use_clpfd_solver,true)
6112 -> int_power2(X,Y,Pow,Span,WF), int_power_clpfd_propagation(X,Y,Pow)
6113 ; int_power1(X,Y,Pow,Span,WF)).
6114 % TO DO ?: if all are variables we can still infer some knowledge
6115 % e.g. if X is positive then Pow must be positive; but it is probably quite rare that we have models with unknown exponent ?
6116 :- block int_power1(-,?,?,?,?). % ensure that Base X is known if CLPFD off
6117 int_power1(X,Y,Pow,Span,WF) :-
6118 int_power2(X,Y,Pow,Span,WF).
6119 :- block int_power2(-,-,?,?,?), int_power2(?,-,-,?,?). % we know Y or both X&Pow
6120 int_power2(X,Y,Pow,Span,WF) :-
6121 ( ground(Y) ->
6122 ( Y>=0 -> (integer(X) -> safe_int_power0(X,Y,PowXY,Span,WF),
6123 clpfd_nr_eq(PowXY,Pow) % try and prevent overflow if PowXY is large
6124 ; safe_int_power0(X,Y,Pow,Span,WF))
6125 ; add_wd_error_set_result('power with negative exponent','**'(X,Y),Pow,1,Span,WF))
6126 ; /* X & POW are ground */
6127 ( X==1 -> Pow==1 /* 1**Y = 1 */
6128 ; X==0, Pow==1 -> Y=0
6129 ; X==0 -> (Pow==1 -> Y=1 /* 0**0=1 */ ; Pow==0 -> integer_dif(Y,0))
6130 ; X>0, Pow>0 ->
6131 checked_precise_log(X,Y,Pow,Span,WF)
6132 % TO DO: X<0 should raise WD error for Event-B ?
6133 ; X<0, eventb_mode -> add_wd_error_set_result('power with negative base','^'(X,Y),Pow,1,Span,WF)
6134 ; X<0, Pow<0 ->
6135 PosPow is -(Pow),
6136 NegX is -(X),
6137 checked_precise_log(NegX,Y,PosPow,Span,WF),
6138 odd(Y)
6139 ; X<0, Pow>0 ->
6140 NegX is -(X),
6141 checked_precise_log(NegX,Y,Pow,Span,WF),
6142 even(Y))).
6143
6144 :- assert_must_succeed(( integer_log(3,59049,Log),Log==10 )).
6145 :- assert_must_succeed(( integer_log(2,1024,Log),Log==10 )).
6146 :- assert_must_succeed(( integer_log(4,1024,Log),Log==5 )).
6147 :- assert_must_succeed(( integer_log(10,1,Log),Log==0 )).
6148 :- assert_must_succeed(( integer_log(10,2,Log),Log==0 )).
6149 :- assert_must_succeed(( integer_log(10,10,Log),Log==1 )).
6150 :- assert_must_succeed(( integer_log(10,11,Log),Log==1 )).
6151 :- assert_must_succeed(( integer_log(10,1000,Log),Log==3 )).
6152 :- use_module(tools_portability, [check_arithmetic_function/1]).
6153 integer_log(Base,Power,_Exp) :- (Base =< 0 ; Power =< 0), !,
6154 add_error_and_fail(integer_log,'Logarithm only defined for positive values: ',log(Base,Power)).
6155 % for very large numbers the floating point logarithm raises a float overflow (e.g., for 2**1030)
6156 % (in SWI-Prolog a representation_error):
6157 % compute an approximation using the number of bits (msb(X) =< log2(X) < msb(X)+1), which is then corrected below
6158 integer_log(Base, Power, Exp) :- (msb(Power) >= 1000 ; msb(Base) >= 1000),!,
6159 (msb(Base) >= 1000 -> ApproximateExp is msb(Power) // (msb(Base)+1)
6160 ; ApproximateExp is truncate(msb(Power) * log(2) / log(Base))), % portable: no log/2 in SWI-Prolog
6161 correct_integer_log_approximation(Base,Power,ApproximateExp,_,Exp).
6162 :- if(check_arithmetic_function(log(2, 4))).
6163 % Native log(Base, Power) function is available - use it. is available in SICStus
6164 integer_log(Base, Power, Exp) :- ApproximateExp is truncate(log(Base, Power)),
6165 % it is precise for power of 2 it seems, but not for 3
6166 % | ?- X is log(3,59049). X = 9.999999999999998 ? -> truncate gives 9, correct value is 10
6167 correct_integer_log_approximation(Base,Power,ApproximateExp,_,Exp).
6168 :- else.
6169 % No native log(Base, Power) support, so construct it using natural logarithms.
6170 integer_log(Base, Power, Exp) :- ApproximateExp is truncate(log(Power) / log(Base)),
6171 correct_integer_log_approximation(Base,Power,ApproximateExp,_,Exp).
6172 :- endif.
6173
6174 correct_integer_log_approximation(Base,Power,Exp,Correction,Res) :-
6175 BE is Base ^ Exp,
6176 (Correction=decreasing, BE > Power % not sure this case will ever trigger
6177 -> Exp1 is Exp-1, %write(dec(Base,Bower,Exp1)),nl,
6178 correct_integer_log_approximation(Base,Power,Exp1,Correction,Res)
6179 ; Correction=increasing, BE*Base =< Power
6180 -> Exp1 is Exp+1, %write(inc(Base,Bower,Exp1)),nl,
6181 correct_integer_log_approximation(Base,Power,Exp1,Correction,Res)
6182 ; Res=Exp).
6183
6184 % TO DO for checked_precise_log: we should take pre-cautions with try_find_abort
6185 % 2**x + y = 1024 & y:0..100 -> will give x=10, y=0 but not give rise to possible WD error
6186 checked_precise_log(1,Exp,Pow,_,_) :- !, % the SICStus Prolog log function does not work for Base=1
6187 Pow=1, less_than_equal_direct(0,Exp).
6188 checked_precise_log(Base,Exp,Pow,Span,WF) :-
6189 integer_log(Base,Pow,Exp),
6190 safe_int_power(Base,Exp,Pow,Span,WF). % we have the perfect solution
6191 % ; Exp is Try+1, write(inc(Base,Pow,Try)),nl, safe_int_power(Base,Exp,Pow,Span,WF) ,write(pow(Base,Exp,Pow)),nl).
6192
6193 :- block even(-).
6194 even(X) :- 0 is X mod 2.
6195 :- block odd(-).
6196 odd(X) :- 1 is X mod 2.
6197
6198 % propagation rules if only one of the args known
6199 :- block int_power_clpfd_propagation(-,-,-).
6200 int_power_clpfd_propagation(Base,Exp,Pow) :- Exp==0, var(Base),var(Pow),!, % B**0 = 1
6201 Pow = 1.
6202 int_power_clpfd_propagation(Base,Exp,Pow) :- Exp==1, var(Base),var(Pow),!, % B**1 = B
6203 Pow = Base.
6204 int_power_clpfd_propagation(Base,Exp,Pow) :- Base==1, var(Exp),var(Pow),!, % 1**E = 1
6205 Pow = Base.
6206 int_power_clpfd_propagation(Base,Exp,Pow) :- Base==0, var(Exp),var(Pow),!, % 0**E = 0 if E>0
6207 (fd_min(Exp,MinExp), number(MinExp), MinExp>0 -> Pow=0
6208 ; true). % case Exp=0 is treated in int_power itself
6209 %int_power_clpfd_propagation(Base,Exp,Pow) :- number(Base), Base>0,var(Exp),var(Pow),!,
6210 % clpfd_leq(1,Pow,_). % causes problem with test 305
6211 int_power_clpfd_propagation(X,Y,Pow) :-
6212 fd_min(X,MinX), number(MinX), MinX>0,
6213 fd_min(Y,MinY), number(MinY), MinY>0, % ensures no WD problem possible
6214 power_not_obviously_too_large_for_clpfd(MinX,MinY),
6215 MinPow is MinX^MinY,
6216 \+ integer_too_large_for_clpfd(MinPow),
6217 fd_max(X,MaxX), number(MaxX),
6218 fd_max(Y,MaxY), number(MaxY),
6219 power_not_obviously_too_large_for_clpfd(MaxX,MaxY),
6220 MaxPow is MaxX^MaxY,
6221 \+ integer_too_large_for_clpfd(MaxPow),
6222 % only do propagation if we are sure not to produce a CLPFD overflow
6223 !,
6224 clpfd_inrange(Pow,MinPow,MaxPow),
6225 (number(X), fd_max(Pow,MaxPow2), number(MaxPow2), get_new_upper_bound(X,MaxPow2,NewMaxExp,NewMaxPow)
6226 -> clpfd_leq(Pow,NewMaxPow,_),
6227 clpfd_leq(Y,NewMaxExp,_)
6228 ; true),
6229 (number(X), fd_min(Pow,MinPow2), number(MinPow2), get_new_lower_bound(X,MinPow2,NewMinExp,NewMinPow)
6230 -> clpfd_leq(NewMinPow,Pow,_),
6231 clpfd_leq(NewMinExp,Y,_)
6232 ; true),
6233 true.
6234 %result of this propagation: x = 3**y & y:3..5 & x /= 27 & x /= 243 -> deterministically forces x=81, y=4
6235 int_power_clpfd_propagation(Base,Exp,Pow) :- number(Base), Base>1, var(Exp), var(Pow),
6236 fd_max(Pow,MaxPow), number(MaxPow),!,
6237 (MaxPow =< 0 -> fail % Base^Exp will always be strictly positive
6238 ; integer_log(Base,MaxPow,Log)
6239 -> clpfd_leq(Exp,Log,_)
6240 ; add_internal_error('Failed:',integer_log(Base,MaxPow,_)),
6241 clpfd_lt(Exp,MaxPow,_Posted)).
6242 int_power_clpfd_propagation(_,_,_).
6243
6244 % check that X^Y is not obviously too large for CLPFD, without computing it:
6245 % X^Y >= 2^(msb(X)*Y); avoids memory overflow when computing e.g. 2^100000000000000 for y:1..100000000000000 & 2**y = z
6246 power_not_obviously_too_large_for_clpfd(X,Y) :- X>0, msb(X)*Y =< 64.
6247 % TO DO: maybe implement custom CLPFD propagators; above does not trigger for x>0 & y:0..500 & 2**x + y = 1500 or x>0 & x<20 & y:0..500 & 2**x + y = 1500
6248
6249 :- assert_must_succeed((kernel_objects:get_new_lower_bound(2,3,E,P),E==2,P==4)).
6250 :- assert_must_succeed((kernel_objects:get_new_lower_bound(2,11,E,P),E==4,P==16)).
6251 :- assert_must_fail((kernel_objects:get_new_lower_bound(2,16,_,_))).
6252 % given Base and Power, determine if Power is a proper power of Exp, if not determine the next possible power of Base
6253 get_new_lower_bound(Base,Power,MinExp,MinPower) :- Base > 1, Power> 0,
6254 integer_log(Base,Power,Exp),
6255 BE is Base^Exp,
6256 BE < Power,
6257 MinPower is Base*BE,
6258 MinPower>Power,
6259 MinPower < 1125899906842624, % 2^50 \+ integer_too_large_for_clpfd(MinPower),
6260 MinExp is Exp+1.
6261 :- assert_must_succeed((kernel_objects:get_new_upper_bound(2,3,E,P),E==1,P==2)).
6262 :- assert_must_succeed((kernel_objects:get_new_upper_bound(2,11,E,P),E==3,P==8)).
6263 :- assert_must_fail((kernel_objects:get_new_upper_bound(2,16,_,_))).
6264 get_new_upper_bound(Base,Power,MaxExp,MaxPower) :- Base > 1, Power> 0,
6265 integer_log(Base,Power,MaxExp),
6266 MaxPower is Base^MaxExp,
6267 MaxPower < Power,
6268 \+ integer_too_large_for_clpfd(MaxPower),
6269 MaxPower*Base > Power.
6270
6271 % safe exponentiation using the squaring algorithm (CLPFD supports exponentiation only for SICStus 4.9 or later)
6272 % Note: in TLA mode 0^0 is undefined according to TLC; for B/Rodin it is 1
6273 safe_int_power0(Base,Exp,Result,Span,WF) :- var(Base),
6274 Exp>30,!, % Exp>59 % 2**59 no overflow; but everything above that is guaranteed to generate an overflow unless Base is 0 or 1 or -1
6275 % 3**38 generates overflow; 4**30 generates overflow on 64-bit systems
6276 % To do: examine whether we should already delay with a smaller or larger exponent
6277 when(nonvar(Base),safe_int_power(Base,Exp,Result,Span,WF)). % wait until Base is known to avoid CLPFD overflow
6278 safe_int_power0(Base,Exp,Result,Span,WF) :- safe_int_power(Base,Exp,Result,Span,WF).
6279
6280 :- assert_must_succeed(( safe_int_power(0,0,P,unknown,_),P==1 )).
6281 safe_int_power(Base,Exp,Result,Span,WF) :- number(Base), Base<0, eventb_mode,!,
6282 add_wd_error_set_result('power with negative base','^'(Base,Exp),Result,1,Span,WF).
6283 safe_int_power(_Base,0,Result,_,_WF) :- !, Result = 1.
6284 safe_int_power(Base,Exp,Result,_,_) :- number(Base),!,
6285 Result is Base^Exp. % new integer exponentiation operator in SICStus 4.3, Note: X is 0^0. -> X=1
6286 safe_int_power(Base,Exp,Result,_,_) :-
6287 Msb is msb(Exp), % most significant bit
6288 ExpMask is 1<<Msb,
6289 safe_int_power_clpfd2(ExpMask,Exp,Base,1,Result).
6290
6291 :- use_module(clpfd_interface,[clpfd_eq_expr/2]).
6292 safe_int_power_clpfd2(0,_,_,Prev,Result) :- !, Prev=Result.
6293 safe_int_power_clpfd2(Mask,Exp,Base,Prev,Result) :-
6294 P is Exp /\ Mask, % P is Exp's highest bit
6295 Mask2 is Mask>>1,
6296 clpfd_eq_expr(Quad,Prev*Prev),
6297 ( P==0 -> Next = Quad
6298 ; clpfd_eq_expr(Next,Quad*Base) ),
6299 safe_int_power_clpfd2(Mask2,Exp,Base,Next,Result).
6300 %% -------------------------------------------------------
6301
6302 :- assert_must_succeed(( singleton_set_element([int(1)],E,unknown,_WF), E==int(1) )).
6303 :- assert_must_succeed(( singleton_set_element([int(X)],int(1),unknown,_WF), X==1 )).
6304 :- assert_must_fail(singleton_set_element([int(1)],int(2),unknown,_WF) ).
6305 :- assert_must_abort_wf(kernel_objects:singleton_set_element([int(1),int(2)],_E,unknown,WF),WF).
6306 % This predicate computes the effect of the MU operator.
6307 % Set should be a singleton set and Elem its only element.
6308 % In case Set is empty or has more than one element, an error
6309 % message is generated.
6310 :- block singleton_set_element(-,?,?,?).
6311 singleton_set_element([],_,Span,WF) :- !,
6312 add_wd_error_span('argument of MU expression must have cardinality 1, but is empty ', '', Span,WF).
6313 singleton_set_element([H|T],Elem,Span,WF) :- !,
6314 empty_set_test_wf(T,Empty,WF),
6315 when(nonvar(Empty),
6316 (Empty=pred_true -> equal_object_wf(Elem,H,singleton_set_element,WF)
6317 ; add_wd_error_span('argument of MU expression has more than one element ',
6318 b(value([H|T]),set(any),[]), Span,WF))).
6319 singleton_set_element(avl_set(A),Elem,Span,WF) :- !,
6320 (is_one_element_avl(A,AEl) -> equal_object_wf(Elem,AEl,singleton_set_element,WF)
6321 ; add_wd_error_span('argument of MU expression has more than one element ',
6322 b(value(avl_set(A)),set(any),[]), Span,WF)).
6323 singleton_set_element(Set,Elem,Span,WF) :-
6324 cardinality_as_int_wf(Set,Card,WF), % we have a comprehension set; could return inf !
6325 singleton_set_element1(Card,Set,Elem,Span,WF).
6326 :- block singleton_set_element1(-,?,?,?,?).
6327 singleton_set_element1(int(Card),Set,Elem,Span,WF) :- !,
6328 % we could check if fd_dom of Card is set up and call equality_objects_lwf(Card,int(1),IsSingleton,LWF,WF) if it is
6329 singleton_set_element2(Card,Set,Elem,Span,WF).
6330 singleton_set_element1(XX,_Set,_Elem,Span,WF) :-
6331 add_wd_error_span('argument of MU expression must have cardinality 1, but has ', XX, Span,WF).
6332
6333 :- block singleton_set_element2(-,?,?,?,?).
6334 singleton_set_element2(1,Set,Elem,_Span,_WF) :- !,
6335 exact_element_of(Elem,Set).
6336 singleton_set_element2(Card,_Set,_Elem,Span,WF) :-
6337 add_wd_error_span('argument of MU expression must have cardinality 1, but has ', Card, Span,WF).
6338
6339 :- assert_must_succeed(( singleton_set_element_wd([int(1)],E,unknown,_WF), E==int(1) )).
6340 :- assert_must_succeed(( singleton_set_element_wd([int(X)],int(1),unknown,_WF), X==1 )).
6341 %:- assert_must_succeed(( singleton_set_element_wd([int(X)|T],int(1),unknown,_WF), X==1, T==[] )).
6342 :- assert_must_fail(singleton_set_element_wd([int(1)],int(2),unknown,_WF) ).
6343 % MU_WD: a version of singleton_set_element which propagates more strongly from result to input
6344 % and thus may not raise WD errors in this case
6345 :- block singleton_set_element_wd(-,-,?,?).
6346 singleton_set_element_wd(Set,Elem,Span,WF) :- nonvar(Set),!, % TODO: first check if Elem is ground
6347 singleton_set_element(Set,Elem,Span,WF).
6348 singleton_set_element_wd(Set,Elem,_,WF) :- % TODO: only propagate if fully known?
6349 %(debug_mode(on) -> add_message_wf('MU_WD','MU_WD result instantiated: ',Elem,Span,WF) ; true),
6350 equal_object_wf(Set,[Elem],singleton_set_element_wd,WF).
6351
6352
6353 %:- print(finished_loading_kernel_objects),nl.