1 % (c) 2009-2025 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(b_global_sets,
6 [b_global_sets_precompiled/0, enumerated_sets_precompiled/0,
7 b_get_global_constants/1, b_get_enumerated_set_constants/1,
8 b_get_global_enumerated_sets/1, b_get_global_sets/1,
9 lookup_global_constant/2,
10 is_b_global_constant/3,
11 is_b_global_constant_hash/3, % a variation with indexing of first two args
12 is_used_b_global_constant/3, is_unused_b_global_constant/2,
13 b_global_constant_or_set_identifier/1,
14 exclude_global_identifiers/2, exclude_global_identifiers/3,
15
16 b_global_set/1, b_non_empty_global_set/1, b_empty_global_set/1,
17 b_global_deferred_set/1,
18 b_global_set_with_potential_symmetry/1, b_global_deferred_set_with_card_gt1/1,
19 b_partially_deferred_set/1,
20
21 enumerated_set/1, % can be checked if this global set is already registered and pre-compiled
22 unfixed_deferred_set/1, unfixed_deferred_set_exists/0,
23 fixed_deferred_set_size/2,
24 provably_finite_global_set/1, infinite_global_set/1,
25 contains_unfixed_deferred_set/1, contains_unfixed_deferred_set/2,
26 b_supplementary_global_set/1, % introduced when untyped ids are allowed
27
28 inferred_minimum_global_set_cardinality/2,
29 inferred_maximum_global_set_cardinality/2,
30 b_exists_global_set_with_potential_symmetry/0,
31 b_global_set_cardinality/2,
32
33 b_clear_global_set_type_definitions/0,
34
35 % three phases of precompilation:
36 b_check_and_precompile_enumerated_sets/0,
37 b_check_and_precompile_deferred_sets/0,
38 b_check_and_precompile_global_set_symmetry/0,
39 % can be called before precompilation:
40 register_enumerated_sets/2,
41
42 b_get_prob_deferred_set_elements/2,
43 add_prob_deferred_set_elements_to_store/3,
44 inline_prob_deferred_set_elements_into_bexpr/2,
45 prob_deferred_set_element/4,
46
47 find_inequal_global_set_identifiers/4,
48 static_symmetry_reduction_for_global_sets/1,
49
50 b_integer_set/1, b_integer_or_real_or_string_set/1, b_integer_or_real_set/1,
51 b_type2_set/2, try_b_type2global_set/2,
52
53 %b_fd_type/3,
54 b_get_fd_type_bounds/3,
55 b_fd_card/2,
56 is_global_set_of_cardinality_one/2, %is_global_set_of_cardinality_two/3,
57 global_type/2, global_type_wf/3,
58 get_global_type_value/3,
59 enum_global_type_limited/2, enumerate_global_type_with_enum_warning/4,
60
61 all_elements_of_type/2, all_elements_of_type_wf/3,
62 all_elements_of_type_rand_wf/3,
63
64 set_user_defined_scope/2, get_user_defined_scope/4,
65
66 generate_fresh_supplementary_global_set/1,
67 register_replaced_global_set/2, b_replaced_global_set/2,
68 %,add_global_set_with_named_constants/2 /* for use by Z,... */
69 list_contains_unfixed_deferred_set_id/1
70 ]).
71
72 :- use_module(debug).
73 :- use_module(tools).
74 :- use_module(library(lists)).
75 :- use_module(library(ordsets)).
76 :- use_module(library(avl)).
77 :- use_module(self_check).
78 :- use_module(preferences).
79 :- use_module(error_manager).
80 :- use_module(bsyntaxtree).
81 :- use_module(library(between),[between/3]).
82 :- use_module(gensym,[gensym/2]).
83
84 :- use_module(module_information,[module_info/2]).
85 :- module_info(group,kernel).
86 :- module_info(description,'This module provides support for deferred/enumerated set elements in B.').
87
88 :- use_module(bmachine,[b_get_properties_from_machine/1,
89 b_get_machine_constants/1, b_get_machine_variables/1,
90 b_get_named_machine_set/2, b_get_machine_set/1,
91 b_get_all_used_identifiers/1, % required for symmetry-related infos
92 b_get_disjoint_constants_of_type/3,
93 b_extract_values_clause_assignment/3,
94 b_get_typed_definition/3, b_get_machine_setscope/2]).
95
96 /* what we call global sets here usually called "given sets", which can be
97 either enumerated or deferred */
98
99
100 :- dynamic b_global_constant/3. % named element of a deferred or enumerated set
101 % for enumerated sets S = {a,b,c} we would have entries a,b,c as b_global_constant
102 % for deferred set S, we may add CONSTANTS which are element of S as b_global_constant
103 :- dynamic used_b_global_constant/3.
104
105 :- dynamic inferred_minimum_global_set_cardinality/2.
106 :- dynamic inferred_maximum_global_set_cardinality/2.
107
108 %% b_get_global_enumerated_sets(-GSets).
109 % Returns all fully and partially enumerated sets.
110 b_get_global_enumerated_sets(GSets) :-
111 findall(GS, (b_global_set(GS), \+ b_global_deferred_set(GS)), GSets).
112 b_get_global_sets(GSets) :-
113 findall(GS, b_global_set(GS), GSets).
114
115 b_get_global_constants(Csts) :- findall(Cst,is_b_global_constant(_,_,Cst),Csts).
116 % only get those elements that have been explicitly marked as enumerated; excludes partially enumerated sets.
117 %b_get_enumerated_set_constants(Set,Csts) :- enumerated_set(Set),findall(Cst,is_b_global_constant(Set,_,Cst),Csts).
118 b_get_enumerated_set_constants(Csts) :- findall(Cst,(enumerated_set(Set),is_b_global_constant(Set,_,Cst)),Csts).
119
120 % getting named elements of SETS:
121 ?is_b_global_constant(Set,Nr,Cst) :- b_global_constant(Set,Nr,Cst).
122
123 :- use_module(library(terms),[term_hash/2]).
124 % efficient indexing if both GS and X are known, useful for large global sets
125 is_b_global_constant_hash(GS,Nr,Name) :-
126 ? term_hash(fd(Nr,GS),Hash), b_global_constant_hash(Hash,GS,Nr,Name).
127
128 is_unused_b_global_constant(Set,Nr) :-
129 b_get_fd_type_bounds_limited(Set,Low,Up),
130 ? between(Low,Up,Nr),
131 \+ used_b_global_constant(Set,Nr,_).
132 is_used_b_global_constant(Set,Nr,Cst) :-
133 used_b_global_constant(Set,Nr,Cst).
134
135 two_unused_b_global_constants_exist(Set) :-
136 b_get_fd_type_bounds_limited(Set,Low,Up),
137 ? between(Low,Up,Nr),
138 \+ used_b_global_constant(Set,Nr,_),
139 !,
140 Nr1 is Nr+1,
141 ? between(Nr1,Up,Nr2),
142 \+ used_b_global_constant(Set,Nr2,_).
143
144 b_get_fd_type_bounds_limited(GlobalSet,Low,UpLimited) :-
145 b_get_fd_type_bounds(GlobalSet,Low,Up),
146 (Up=inf -> add_message(b_global_sets,'Limiting infinite deferred set elements to 999: ',GlobalSet),
147 UpLimited=999
148 ; UpLimited=Up).
149
150 :- dynamic lookup_global_constant/2, b_global_constant_hash/4.
151 %lookup_global_constant(Id,Val) :-
152 % b_global_constant(Set,Nr,Id), % not an indexed lookup ; now we assert lookup_global_constant below
153 % Val = fd(Nr,Set).
154
155 b_global_constant_or_set_identifier(Id) :- lookup_global_constant(Id,_).
156 ?b_global_constant_or_set_identifier(Id) :- b_global_set(Id).
157 % one could also think of freetypes
158
159 % exclude global constants and sets from a list of ids
160 exclude_global_identifiers([],[]).
161 exclude_global_identifiers([TID|T],Res) :-
162 ? (get_id(TID,ID),b_global_constant_or_set_identifier(ID) -> Res=RT ; Res = [TID|RT]),
163 exclude_global_identifiers(T,RT).
164
165 exclude_global_identifiers([],_,[]).
166 exclude_global_identifiers([TID|T],Local,Res) :-
167 ? (get_id(TID,ID), b_global_constant_or_set_identifier(ID),
168 ord_nonmember(ID,Local)
169 -> Res=RT ; Res = [TID|RT]),
170 exclude_global_identifiers(T,Local,RT).
171
172 % works both with typed and untyped ids
173 get_id(b(identifier(ID),_,_), R) :- !, R=ID.
174 get_id(ID,ID) :- (atom(ID) -> true ; add_warning(b_global_sets,'Not an ID: ',ID)).
175
176 :- dynamic b_precompiled_global_set/1.
177 b_precompiled_global_set(_) :- print_error('*** b_global_set not precompiled'),fail.
178
179 ?b_global_set(GS) :- b_precompiled_global_set(GS) ; b_supplementary_global_set(GS).
180
181 % a version of b_global_set which does not leave a trailing choice point for b_supplementary_global_set around
182 % has to be called with GS ground
183 %b_global_set_ground(GS) :- if(b_precompiled_global_set(GS),true,b_supplementary_global_set(GS)).
184
185 % Does not contain partially enumerated sets.
186 b_global_deferred_set(GS) :-
187 ? b_global_set(GS),
188 ? \+ is_b_global_constant(GS,_Nr,_Cst). % note : some deferred sets are translated into partially_deferred_set
189
190 % either an enumerated set with unused constants or a deferred set where some constants were lifted into the deferred set
191 b_partially_deferred_set(GS) :-
192 b_global_set(GS),
193 (is_b_global_constant(GS,_Nr,_Cst) -> true), % GS is in principle enumerated
194 (is_unused_b_global_constant(GS,_X) -> true).
195
196
197 b_global_set_with_potential_symmetry(GS) :-
198 ? b_global_set(GS),
199 ? (b_global_deferred_set_with_card_gt1(GS) -> true
200 ? ; two_unused_b_global_constants_exist(GS) -> true % At least two unused constants exist
201 ; fail).
202
203 b_global_deferred_set_with_card_gt1(GS) :-
204 ? b_global_deferred_set(GS),
205 extract_setsize_from_machine_cache(GS,Low,Up),
206 inf_greater(Up,Low).
207
208 inf_greater(X,Y) :- (X=inf -> integer(Y) ; X>Y).
209 inf_add(X,Y,XY) :- (X=inf -> XY=inf ; Y=inf -> XY=inf ; XY is X+Y).
210
211 :- volatile b_exists_global_set_with_potential_symmetry/0.
212 :- dynamic b_exists_global_set_with_potential_symmetry/0.
213 :- dynamic precompilation_phase/1.
214
215 % -------------------------------------------
216
217 % Phase 1 of precompilation:
218 b_check_and_precompile_enumerated_sets :-
219 b_reset_global_set_type_definitions,
220 retractall(b_exists_global_set_with_potential_symmetry),
221 retractall(precompilation_phase(_)),
222 assertz(precompilation_phase(1)),
223 debug_println(9,'Preprocessing enumerated sets: '),
224 debug_print(9,'% '),
225 ? b_get_named_machine_set(Set,_Els), % treat enumerated sets first; their cardinality is obvious
226 precompile_global_set(Set), % will only require b_get_named_machine_set/2 from bmachine
227 fail.
228 b_check_and_precompile_enumerated_sets :-
229 retractall(precompilation_phase(_)),
230 assertz(precompilation_phase(2)),
231 debug_nl(9).
232
233 % Phase 2 of precompilation:
234 b_check_and_precompile_deferred_sets :-
235 (deferred_sets_precompiled
236 -> add_internal_error('Deferred sets already precompiled',b_check_and_precompile_deferred_sets)
237 ; enumerated_sets_precompiled -> true
238 ; add_internal_error('Enumerated sets not yet precompiled',b_check_and_precompile_deferred_sets)),
239 retractall(precompilation_phase(_)),
240 assertz(precompilation_phase(3)),
241 ? check_enumerated_set_scope(_),
242 fail.
243 b_check_and_precompile_deferred_sets :-
244 debug_println(9,'Inferring cardinality and disjoint elements of deferred sets: '),
245 debug_print(9,'% '),
246 ? b_get_machine_set(Set),
247 \+ b_get_named_machine_set(Set,_), % not enumerated
248 precompile_global_set(Set),
249 fail.
250 b_check_and_precompile_deferred_sets :-
251 retractall(precompilation_phase(_)),
252 assertz(precompilation_phase(4)),
253 debug_nl(9).
254
255 enumerated_sets_precompiled :- precompilation_phase(X), X >= 2.
256 deferred_sets_precompiled :- precompilation_phase(X), X >= 4.
257 b_global_sets_precompiled :- deferred_sets_precompiled.
258
259 precompile_global_set(Set) :-
260 add_new_global_set(Set),
261 ? (b_extract_fd_type(Set,LowBnd,UpBnd) /* also computes & caches the size of the SET */
262 -> debug_print(9,' '),debug_print(9,Set),
263 debug_print(9,'=='),debug_print(9,LowBnd),debug_print(9,'..'),debug_print(9,UpBnd)
264 ; add_internal_error('No b_extract_fd_type/3 solution for global set: ',b_extract_fd_type(Set,_,_))
265 ),debug_print(9,' ').
266
267 % check if there are any conflicts between scope annotations and enumerated set
268 check_enumerated_set_scope(GlobalSetName) :-
269 ? enumerated_set(GlobalSetName),
270 extract_setsize_from_machine_cache(GlobalSetName,LowBound,UpBound),
271 (get_user_defined_scope(GlobalSetName,DL,DU,Span),
272 DU-DL =\= UpBound-LowBound
273 -> UserSize is 1+DU-DL,
274 EnumSize is 1+UpBound-LowBound,
275 ajoin(['Conflict between cardinality of scope_',GlobalSetName,
276 ' DEFINITION (',UserSize,') and enumeration (',EnumSize,') of SET:'],Msg),
277 add_error(extract_setsize_from_machine,Msg,GlobalSetName,Span)
278 ; true
279 ).
280
281 :- use_module(library(avl),[avl_fetch/2]).
282 % Phase 3 of precompilation:
283 % This can be done after bmachine pre-compile is finished
284 b_check_and_precompile_global_set_symmetry :-
285 (retract(precompilation_phase(4)) -> true
286 ; add_internal_error('Deferred sets not yet precompiled',b_check_and_precompile_global_set_symmetry)),
287 assertz(precompilation_phase(5)),
288 find_all_used_enumerated_elements(UsedEnumsAVL),
289 ? b_extract_fd_type(GS,_Low,_Up),
290 ? (is_b_global_constant(GS,_Nr,_Cst) -> true), % GS is in principle enumerated
291 (user_forced_symmetry(GS)
292 -> print('FORCING SYMMETRY: '), print(GS), nl,
293 fail % not asserting used_b_global_constant; every constant becomes "virtually" unused
294 ; true
295 ),
296 ? is_b_global_constant_hash(GS,X,Name),
297 avl_fetch(Name,UsedEnumsAVL),
298 assertz(used_b_global_constant(GS,X,deferred)), % by storing that it is not used, we enable symmetry reduction
299 debug_println(9,used_b_global_constant(GS:Name)),
300 fail.
301 b_check_and_precompile_global_set_symmetry :- %print(precomp_gs_3), debug:nl_time,
302 ? (b_global_set_with_potential_symmetry(_)
303 -> assertz(b_exists_global_set_with_potential_symmetry),
304 debug_println(9,'% Symmetry is potentially useful for this machine')
305 ; true),
306 debug_nl(9),
307 /* clean up: */
308 reset_global_set_user_defined_scope.
309
310 % -------------------------------------------
311
312 % peform MACE style static symmetry reduction for those global constants
313 % that have not already been fixed
314 % e.g., for constants aa,bb,cc,dd of type ID and bb/=cc --> nrs of bb,cc will be fixed as 1 and 2; we will ensure that numbers of aa:1..3 and dd:1..4 and that dd=4 only if aa=3
315
316 static_symmetry_reduction_for_global_sets(_ConstantsState) :-
317 get_preference(use_solver_on_load,kodkod),!. % no idea which numbering Kodkod might return/expect ?!
318 static_symmetry_reduction_for_global_sets(_ConstantsState) :-
319 get_preference(use_static_symmetry_detection,false),!.
320 static_symmetry_reduction_for_global_sets(ConstantsState) :-
321 findall(gs_info(GS,FirstAvailableNewIdx,Low,Up,Other),
322 static_symmetry_reduction_possible(GS,FirstAvailableNewIdx,Low,Up,Other),L),
323 maplist(perform_static_symmetry_reduction(ConstantsState),L).
324
325 :- use_module(static_symmetry_reduction,[static_symmetry_reduction_possible/5, perform_ssr/8]).
326 perform_static_symmetry_reduction(ConstantsState,gs_info(GS,First,Low,Up,Other)) :-
327 if(perform_ssr(Other,[],First,First,GS,Low,Up,ConstantsState),true,
328 add_internal_error('Call failed: ',perform_ssr(Other,[],First,First,GS,Low,Up,ConstantsState))).
329
330
331
332 % --------------------
333
334
335 :- use_module(avl_tools,[ord_domain_list_to_avl/2]).
336 find_all_used_enumerated_elements(ElementsAVL) :-
337 b_get_all_used_identifiers(Identifiers),
338 b_get_machine_variables(TVariables),get_texpr_ids(TVariables,Variables),
339 % We assume that b_get_all_used_identifiers/1 is a proper ordset. (sorted with sort/2)
340 % As an optimisation, we remove the variables, they cannot be enumerated elements.
341 list_to_ord_set(Variables,OVariables),
342 ord_subtract(Identifiers,OVariables,Elements),
343 ord_domain_list_to_avl(Elements,ElementsAVL),!.
344 find_all_used_enumerated_elements(_Elements) :-
345 add_error_and_fail(b_global_sets, 'find_all_used_enumerated_elements failed').
346
347
348 reset_global_set_user_defined_scope :-
349 retract(global_set_user_defined_scope(GS,_Scope)),
350 (is_b_precompiled_globalset(GS)
351 -> true
352 ; add_error(b_global_sets,'Trying to set scope of unknown SET: ',GS)
353 ),fail.
354 reset_global_set_user_defined_scope.
355
356 % Return those constants which are implicitly introduced by ProB, but not really
357 % part of the model. These are the elements of a deferred set.
358 b_get_prob_deferred_set_elements(TIds,AllOrVisible) :-
359 findall( TId,
360 ( prob_deferred_set_element(GS,_Nr,Id,AllOrVisible),
361 create_texpr(identifier(Id),global(GS),[],TId)),
362 TIds).
363
364
365
366 :- use_module(bsyntaxtree,[transform_bexpr_with_scoping/3]).
367 % inline probids (prob deferred set ids) as values into a predicate or expression
368 inline_prob_deferred_set_elements_into_bexpr(Pred,CompiledPred) :-
369 add_prob_deferred_set_elements_to_store([], State, visible), % visible: only those Ids which do not clash with variables, constants, ... are added
370 State \= [], !,
371 sort(State,S),
372 debug_println(19,compiling_probids_into_bexpr(S)),
373 transform_bexpr_with_scoping(b_global_sets:inline_state(S),Pred,CompiledPred).
374 inline_prob_deferred_set_elements_into_bexpr(Pred,Pred).
375
376 :- use_module(tools_lists,[ord_member_nonvar_chk/2]).
377 :- use_module(library(ordsets),[ord_nonmember/2]).
378 % difference with compile from b_compiler: no need to specify parameters, no errors if identifier not found
379 inline_state(State,b(identifier(ID),Type,I),b(value(Val),Type,I),LocalIds) :-
380 ord_member_nonvar_chk(bind(ID,Val),State), % the ID appears in the binding list
381 ord_nonmember(ID,LocalIds). % The ID is not overriden by a locally quantified variable
382
383 add_prob_deferred_set_elements_to_store(OldStore,NewStore,AllOrVisible) :- % add prob_ids
384 is_list(OldStore),!,
385 %print(add_prob_deferred_set_elements_to_store(OldStore)),nl,
386 findall(bind(Id,fd(Nr,GS)),(prob_deferred_set_element(GS,Nr,Id,AllOrVisible),
387 \+ member(bind(Id,_),OldStore)),
388 NewStore, OldStore).
389 add_prob_deferred_set_elements_to_store(OldStore,NewStore,_) :-
390 add_internal_error('Cannot add deferred set elements to this store: ',OldStore),
391 NewStore=OldStore.
392
393 % virtual deferred set elements generated by ProB
394 prob_deferred_set_element(GlobalSet,Elem,Id,AllOrVisible) :-
395 ? b_global_set(GlobalSet),
396 atom_codes(GlobalSet,GlobalSetCodes),append(GlobalSetCodes,ECodes,NameCodes),
397 b_get_fd_type_bounds(GlobalSet,Low,Up),
398 (Up=inf -> UpLimited=999,
399 debug_format(19,'Limiting ProB IDs for deferred set ~w to ~w..~w elements~n',[GlobalSet,Low,UpLimited])
400 ; Up>999 -> UpLimited=999, % TODO: provide preference/option ?
401 debug_format(19,'Limiting ProB IDs for deferred set ~w to ~w..~w elements~n',[GlobalSet,Low,UpLimited])
402 ; UpLimited=Up),
403 ? between(Low,UpLimited,Elem),
404 (AllOrVisible = all -> true
405 ; % only visible ones
406 \+ is_b_global_constant_hash(GlobalSet,Elem,_) % the identifier is not used somewhere else
407 ),
408 number_codes(Elem,ECodes),
409 atom_codes(Id,NameCodes),
410 \+ b_global_set(Id), % not used as another SET name
411 \+ lookup_global_constant(Id,_). % not used as another SET element
412
413
414 user_forced_symmetry(GS) :- % check if the user defined FORCE_SYMMETRY_GS == TRUE
415 string_concatenate('FORCE_SYMMETRY_',GS,DefName),
416 b_get_typed_definition(DefName,[],F), get_texpr_expr(F,boolean_true).
417
418
419 %is_global_set_of_cardinality_two(Type,LowBnd,UpBnd) :-
420 % b_get_fd_type_bounds(Type,LowBnd,UpBnd),
421 % LowBnd+1 =:= UpBnd.
422
423 :- volatile is_global_set_of_cardinality_one/2.
424 :- dynamic is_global_set_of_cardinality_one/2.
425 % should be called when unloading a machine, before type-checking etc...
426 % TO DO: use :- use_module(eventhandling,[register_event_listener/3]).
427 b_clear_global_set_type_definitions :- % nl,print(clearing_gs),nl,
428 retractall(b_supplementary_global_set(_)),
429 retractall(b_replaced_global_set(_,_)),
430 b_reset_global_set_type_definitions,
431 retractall(global_set_user_defined_scope(_,_)).
432
433 b_reset_global_set_type_definitions :- %nl,print(reset_gs),nl,
434 % print_message('resetting global sets'),
435 retractall(precompilation_phase(_)),
436 retractall(b_precompiled_global_set(_)),
437 retractall(enumerated_set(_)),
438 retractall(fixed_deferred_set_size(_,_)),
439 retractall(extract_setsize_from_machine_cache(_,_,_)),
440 retractall(find_minimum_cardinality_cache(_,_)),
441 retractall(is_global_set_of_cardinality_one(_,_)),
442 retractall(b_global_constant(_,_,_)),
443 retractall(b_global_constant_hash(_,_,_,_)),
444 retractall(lookup_global_constant(_,_)),
445 retractall(used_b_global_constant(_,_,_)),
446 retractall(inferred_minimum_global_set_cardinality(_,_)),
447 retractall(inferred_maximum_global_set_cardinality(_,_)).
448
449
450 add_new_global_set(Set) :-
451 (b_precompiled_global_set(Set)
452 -> add_internal_error('Global set already exists: ',add_new_global_set(Set))
453 ; b_integer_or_real_or_string_set(Set)
454 % should only occur in Event-B mode, or possibly in Z, TLA; in Atelier-B these are reserved keywords
455 % this can cause problems as we currently create symbolic set values global_set('STRING'), ...
456 -> add_warning(add_new_global_set,'Global set name can cause internal name clashes: ',Set),
457 assertz(b_precompiled_global_set(Set))
458 ; assertz(b_precompiled_global_set(Set))).
459
460
461 :- dynamic b_supplementary_global_set/1, b_replaced_global_set/2.
462 b_supplementary_global_set(GS) :- b_supplementary_global_set(GS).
463
464 % these should be called before we precompile the global set definitions
465 generate_fresh_supplementary_global_set(FRESHID) :-
466 gensym('__DEFERREDSET__',FRESHID),
467 debug_println(10,generate_fresh_supplementary_global_set(FRESHID)),
468 assertz(b_supplementary_global_set(FRESHID)).
469
470 % called by record construction, when a global deferred set gets replaced by something else
471 % we register it here for safety and better error messages
472 % in some contexts (like freetype constructors/destructors) the old type may accidentally get used; but we should remove all references to old type
473 register_replaced_global_set(ID,_) :-
474 b_global_set(ID),!,
475 add_warning(b_global_sets,'Global set already exists: ',ID).
476 register_replaced_global_set(ID,_) :-
477 b_replaced_global_set(ID,_),!,
478 add_warning(b_global_sets,'Global set already registered as replaced: ',ID).
479 register_replaced_global_set(ID,NewTypeExpr) :-
480 assertz(b_replaced_global_set(ID,NewTypeExpr)).
481
482 /* --------------------------------------------------------- */
483 /* Extracting Finite Domain type information from the B machine */
484 /* --------------------------------------------------------- */
485
486
487
488 /* below treats annotations in the form:
489 DEFINITIONS
490 scope_Name == 1..3;
491 scope_Code == 4..8
492 which inform us about which finidte domain ranges we should
493 give to global sets defined in SETS
494 */
495
496 :- use_module(tools_printing,[print_error/1, format_error_with_nl/2]).
497 :- dynamic extract_setsize_from_machine_cache/3.
498 extract_setsize_from_machine_cache(_,_,_) :-
499 print_error('*** extract_setsize_from_machine not precompiled'),fail.
500
501 try_extract_setsize_from_machine(GlobalSetName,_LowBound,_UpBound) :-
502 start_extracting_setsize(GlobalSetName),!,fail. % cyclic dependency; abort computation
503 try_extract_setsize_from_machine(GlobalSetName,LowBound,UpBound) :-
504 extract_setsize_from_machine(GlobalSetName,LowBound,UpBound).
505
506 % Determine if GlobalSetName is enumerated or deferred and if we can infer cardinality (bounds)
507 extract_setsize_from_machine(GlobalSetName,LowBound,UpBound) :-
508 extract_setsize_from_machine_cache(GlobalSetName,L,U),!,
509 LowBound=L,UpBound=U.
510 extract_setsize_from_machine(GlobalSetName,LowBound,UpBound) :-
511 start_extracting_setsize_from_machine(GlobalSetName),
512 b_get_named_machine_set(GlobalSetName,ListOfConstants), % find explicitly declared ENUMERATED SETS
513 !,
514 assert_enumerated_set(GlobalSetName,ListOfConstants,LowBound,UpBound). % will also assert_extract_setsize_from_machine_cache
515 extract_setsize_from_machine(GlobalSetName,L,U) :-
516 b_supplementary_global_set(GlobalSetName),!, % deferred set that was added for untyped ID,...
517 default_deferred_set_bounds(LowBound,UpBound),
518 assert_extract_setsize_from_machine_cache(GlobalSetName,LowBound,UpBound),
519 (LowBound,UpBound)=(L,U).
520 extract_setsize_from_machine(GlobalSetName,L,U) :-
521 /* we have a DEFERRED SET */
522 extract_DEFERRED_setsize_from_machine(GlobalSetName,LowBound,UpBound),
523 (LowBound=UpBound -> assertz(is_global_set_of_cardinality_one(GlobalSetName,LowBound)) ; true),
524 assert_extract_setsize_from_machine_cache(GlobalSetName,LowBound,UpBound),
525 % determine if some of the elements are ENUMERATED:
526 (b_get_disjoint_constants_of_type(GlobalSetName, DisjointConstants,_)
527 % DISABLE for Disprover ?? what if selected hyps does not contain this
528 -> /* add those constants to the deferred set as though they were enumerated set elements: improves performance by avoiding redundant permutations; is a kind of symmetry breaking */
529 debug_format(19,'Adding enumerated disjoint constants ~w : ~w~n~n',[GlobalSetName,DisjointConstants]),
530 add_named_constants_to_global_set(GlobalSetName,LowBound,DisjointConstants)
531 ; true
532 ),
533 debug_println(9,setsize(GlobalSetName,LowBound,UpBound)),
534 (LowBound,UpBound)=(L,U).
535
536
537 /* for Deferred SETS : */
538 extract_DEFERRED_setsize_from_machine(GlobalSetName,L,U) :-
539 b_extract_values_clause_assignment(GlobalSetName,_Type,TVal), % VALUES clause
540 (get_interval(TVal,Low,Up) -> true
541 ; add_error(b_global_sets,'VALUES clause must set deferred set to an interval: ',GlobalSetName,TVal),fail),
542 (evaluable_integer_expression(Low,[],LowBound) -> true
543 ; add_error(b_global_sets,'Cannot extract lower bound from VALUES interval for: ',GlobalSetName,Low),fail),
544 (evaluable_integer_expression(Up,[],UpBound) -> true
545 ; add_error(b_global_sets,'Cannot extract upper bound from VALUES interval for: ',GlobalSetName,Up),fail),
546 !,
547 check_compatible_with_user_scope(GlobalSetName,UpBound,LowBound),
548 LowBound=L,UpBound=U.
549 extract_DEFERRED_setsize_from_machine(GlobalSetName,L,U) :-
550 ? b_get_properties_from_machine(Properties), member_in_conjunction(C,Properties),
551 (is_equality_card_global_set(C,GlobalSetName,Properties,Card)
552 % check if the PROPERTIES contain an expression of the form card(GS) = Nr
553 -> true
554 ; is_infinite_global_set_pred(C,GlobalSetName)
555 % look for predicates which stipulate that the set is infinite
556 -> Card=inf
557 ),
558 !,
559 assertz(fixed_deferred_set_size(GlobalSetName,Card)),
560 LowBound=1, UpBound = Card,
561 check_compatible_with_user_scope(GlobalSetName,UpBound,LowBound),
562 LowBound=L,UpBound=U.
563 extract_DEFERRED_setsize_from_machine(GlobalSetName,L,U) :- /* check if there is a scope_ DEFINITION */
564 get_user_defined_scope(GlobalSetName,LowBound,UpBound,_),!,
565 LowBound=L,UpBound=U.
566 extract_DEFERRED_setsize_from_machine(GlobalSetName,LowBound,UpBound) :-
567 get_preference(globalsets_fdrange,DefaultUpperBound),
568 find_minimum_cardinality(GlobalSetName,MinCard),
569 assertz(inferred_minimum_global_set_cardinality(GlobalSetName,MinCard)),
570 !,
571 LowBound = 1,
572 (find_maximum_cardinality(GlobalSetName,MaxCard)
573 -> (MaxCard=MinCard -> assertz(fixed_deferred_set_size(GlobalSetName,MinCard)),
574 debug_println(9,fixed_deferred_set_size(GlobalSetName,MinCard)),
575 UpBound = MinCard
576 ; DefaultUpperBound>MaxCard ->
577 debug_println(9,reducing_deferred_set_size(GlobalSetName,MaxCard)),
578 UpBound=MaxCard
579 ; DefaultUpperBound<MinCard ->
580 debug_println(9,inferred_minimum_global_set_cardinality(GlobalSetName,MinCard)),
581 UpBound=MinCard
582 ; UpBound is MinCard
583 )
584 ; MinCard>DefaultUpperBound -> UpBound=MinCard
585 ; UpBound=DefaultUpperBound),
586 debug_println(4,inferred(GlobalSetName,UpBound)).
587 extract_DEFERRED_setsize_from_machine(GlobalSetName,LowBound,UpBound) :-
588 % No Minimum cardinality was inferred
589 LowBound=1, get_preference(globalsets_fdrange,DefaultUpperBound),
590 find_maximum_cardinality(GlobalSetName,MaxCard),
591 !,
592 (MaxCard=1 -> UpBound=1, assertz(fixed_deferred_set_size(GlobalSetName,1))
593 ; inf_greater(DefaultUpperBound,MaxCard) ->
594 debug_println(9,reducing_deferred_set_size(GlobalSetName,MaxCard)),
595 UpBound=MaxCard
596 % does not have the case: DefaultUpperBound<MinCard -> UpBound=MinCard
597 ; UpBound=DefaultUpperBound).
598 extract_DEFERRED_setsize_from_machine(_GlobalSetName,LowBound,UpBound) :-
599 % No Minimum cardinality was inferred
600 default_deferred_set_bounds(LowBound,UpBound).
601
602 default_deferred_set_bounds(1,UpBound) :- get_preference(globalsets_fdrange,UpBound).
603
604 check_compatible_with_user_scope(GlobalSetName,UpBound,LowBound) :-
605 (get_user_defined_scope(GlobalSetName,DL,DU,Span),
606 DU-DL =\= UpBound-LowBound
607 -> add_error(extract_DEFERRED_setsize_from_machine,'Conflict between scope_ Definition and PROPERTIES:',GlobalSetName,Span)
608 ; true
609 ).
610
611
612 find_maximum_cardinality(GlobalSetName,MaxCard) :-
613 find_maximum_cardinality1(GlobalSetName,MaxCard),
614 assertz(inferred_maximum_global_set_cardinality(GlobalSetName,MaxCard)).
615
616 find_maximum_cardinality1(GlobalSetName,MaxCard) :-
617 b_get_machine_constants(Csts),
618 b_get_properties_from_machine(Properties),
619 findall(MC2,find_maximum_cardinality2(Csts,Properties,GlobalSetName,MC2),List),
620 min_member(MaxCard,List).
621 find_maximum_cardinality2(_Csts,Properties,GlobalSetName,MaxCard) :-
622 get_card_upper_bound(Properties,GlobalSetName,MaxCard).
623 find_maximum_cardinality2(_Csts,Properties,GlobalSetName,MaxCard) :-
624 ? get_equality(Properties,GlobalSetName,EXPR,RestProp), % GlobalSetName = EXPR
625 maximum_cardinality_of_expression(EXPR,RestProp,MaxCard).
626 find_maximum_cardinality2(_Csts,Properties,GlobalSetName,MaxCard) :-
627 ? member_in_conjunction(C,Properties),
628 get_texpr_expr(C,partition(Set,DisjSets)), % partition(GlobalSetName, DisjSets)
629 global_set_identifier(Set,GlobalSetName),
630 max_card_of_partition_list(DisjSets,Properties,0,MaxCard).
631
632
633 get_equality(Properties,ID,R,RestProp) :-
634 ? select_member_in_conjunction(C,Properties,RestProp),
635 get_texpr_expr(C,equal(LHS,RHS)),
636 ( get_texpr_expr(LHS,identifier(ID)), R=RHS
637 ; get_texpr_expr(RHS,identifier(ID)), R=LHS ).
638
639 % find card(ID) <= MaxCard
640 get_card_upper_bound(Properties,ID,MaxCard) :-
641 LHS = b(card(TID),_,_),
642 get_texpr_expr(TID,identifier(ID)),
643 ? select_member_in_conjunction(C,Properties,RestProp),
644 ( get_texpr_expr(C,less_equal(LHS,RHS)), Strict=false ;
645 get_texpr_expr(C,greater_equal(RHS,LHS)), Strict=false ;
646 get_texpr_expr(C,less(LHS,RHS)), Strict=true ;
647 get_texpr_expr(C,greater(RHS,LHS)), Strict=true
648 ),
649 evaluable_integer_expression(RHS,RestProp,R),
650 (Strict=true -> MaxCard is R-1 ; MaxCard = R).
651
652 maximum_cardinality_of_expression(b(E,_,_),Props,MC) :- maximum_cardinality_of_expression2(E,Props,MC).
653 maximum_cardinality_of_expression2(set_extension(SetExtElements),_,MaxCard) :-
654 length(SetExtElements,MaxCard).
655 % we assume that all elements in List can be different
656 maximum_cardinality_of_expression2(union(A,B),Props,MaxCard) :-
657 maximum_cardinality_of_expression(A,Props,MA),
658 maximum_cardinality_of_expression(B,Props,MB), MaxCard is MA+MB.
659 maximum_cardinality_of_expression2(intersection(A,B),Props,MaxCard) :-
660 maximum_cardinality_of_expression(A,Props,MA),
661 maximum_cardinality_of_expression(B,Props,MB), MaxCard is min(MA,MB).
662 maximum_cardinality_of_expression2(set_subtraction(A,_),Props,MaxCard) :-
663 maximum_cardinality_of_expression(A,Props,MaxCard).
664 maximum_cardinality_of_expression2(cartesian_product(A,B),Props,MaxCard) :-
665 maximum_cardinality_of_expression(A,Props,MA),
666 maximum_cardinality_of_expression(B,Props,MB), MaxCard is MA*MB.
667 maximum_cardinality_of_expression2(identifier(ID),Props,MaxCard) :- % tested in testcase 1917
668 maximum_cardinality_of_identifier(ID,Props,MaxCard).
669 maximum_cardinality_of_expression2(empty_set,_,0).
670 % TO DO: generalized union...
671 %maximum_cardinality_of_expression2(Ex,_) :- nl, print(uncov_max_partition_card(Ex)),nl,nl,fail.
672 % TO DO: other cases
673
674 maximum_cardinality_of_identifier(ID,Properties,MaxCard) :-
675 TID = b(identifier(ID),_,_),
676 ? member_in_conjunction(EqCardExpr,Properties), % look for card(ID) = MaxCard
677 is_equality_card_expression(EqCardExpr,Properties,TID,MaxCard), % this is actually an exact card
678 !. % TODO: also check for card(ID) <= Bound
679 maximum_cardinality_of_identifier(ID,Properties,MaxCard) :-
680 get_equality(Properties,ID,EXPR,RestProp), % ID = EXPR,
681 % remove equality to avoid loops, TO DO: try several equalities?
682 maximum_cardinality_of_expression(EXPR,RestProp,MaxCard).
683 maximum_cardinality_of_identifier(ID,Properties,MaxCard) :-
684 get_texpr_id(Set,ID),
685 get_texpr_expr(C,partition(Set,DisjSets)), % partition(ID, DisjSets)
686 select_member_in_conjunction(C,Properties,RestProp), % remove partition to avoid loops
687 max_card_of_partition_list(DisjSets,RestProp,0,MaxCard).
688
689 % determine maximum cardinality of partition RHS-List (partition(Set,RHS-List))
690 max_card_of_partition_list([],_,Acc,Acc).
691 max_card_of_partition_list([TPartSet|T],Properties,Acc,Res) :-
692 maximum_cardinality_of_expression(TPartSet,Properties,Max),!,
693 NAcc is Acc+Max,
694 max_card_of_partition_list(T,Properties,NAcc,Res).
695
696
697 :- dynamic find_minimum_cardinality_cache/2.
698 find_minimum_cardinality(GS,MC) :-
699 find_minimum_cardinality_cache(GS,Nr),!, %print(min_card_cache(GS,Nr)),nl,
700 % avoid loops; e.g., if we have N1 >->> N2 and N2 >->> N1
701 number(Nr),
702 MC=Nr.
703 find_minimum_cardinality(GlobalSetName,Res) :- % print(find_min_card(GlobalSetName)),nl,
704 /* try to find out from the Properties whether there is an implied minimum cardinality */
705 b_get_machine_constants(Csts),
706 b_get_properties_from_machine(Properties),
707 assertz(find_minimum_cardinality_cache(GlobalSetName,unknown)),
708 findall(MinCard2,find_minimum_cardinality2(Csts,Properties,GlobalSetName,MinCard2),List),
709 debug_println(9,mincard_list(GlobalSetName,List)),
710 max_member(MinCard,List), % we do not allow empty global sets anymore, allow_empty_global_sets is obsolete
711 inf_greater(MinCard,0),
712 retract(find_minimum_cardinality_cache(GlobalSetName,_)),
713 assertz(find_minimum_cardinality_cache(GlobalSetName,MinCard)),
714 Res=MinCard.
715
716 find_minimum_cardinality2(_,Properties,GlobalSetName,MinCard) :-
717 ? member_in_conjunction(C,Properties),
718 ? find_minimum_cardinality3(C,Properties,GlobalSetName,MinCard).
719 find_minimum_cardinality2(_Constants,_Properties,GlobalSetName,MinCard) :-
720 %print(trying_find_min_card(GlobalSetName,Constants)),nl,
721 b_get_disjoint_constants_of_type(GlobalSetName, DisjointConstants,_),
722 length(DisjointConstants,MinCard), inf_greater(MinCard,1).
723
724
725 :- use_module(partition_detection,[is_disjoint_pred/4]).
726
727 find_minimum_cardinality3(C,Properties,GlobalSetName,MinCard) :-
728 % check if the PROPERTIES contain an expression of the form card(GS) >= Nr or similar
729 is_greaterequalthan_card_global_set(C,GlobalSetName,Properties,MinCard).
730 find_minimum_cardinality3(C,Properties,GlobalSetName,MinCard) :-
731 % find things like partition(GlobalSetName,S1,...,SN)
732 get_texpr_expr(C,partition(Set,DisjSets)),
733 global_set_identifier(Set,GlobalSetName),
734 % print(partition(Set,DisjSets,GlobalSetName)),nl,
735 find_min_card_of_disjoint_sets(DisjSets,Properties,MinCard). % ,print(min(MinCard)),nl.
736 find_minimum_cardinality3(C,_Properties,GlobalSetName,MinCard) :-
737 get_texpr_expr(C,member(_Something,SURJ)),
738 ? is_surjection(SURJ,Set,OTHERSET),
739 global_set_identifier(Set,GlobalSetName),
740 \+ global_set_identifier(OTHERSET,GlobalSetName), % Surjection on itself; no use in narrowing down cardinality
741 (minimum_cardinality(OTHERSET,MinCard)
742 -> true
743 ; print('*** could not compute mincard: '), print(OTHERSET),nl,fail),
744 (MinCard=inf -> add_error(b_global_sets,'Set has to be of infinite cardinality: ',GlobalSetName),fail ; true).
745 find_minimum_cardinality3(C,Properties,GlobalSetName,MinCard) :-
746 is_disjoint_pred(C,set(global(GlobalSetName)),A,B), % A /\ B = {} with A<:GS and B<:GS
747 minimum_cardinality_of_set(A,Properties,MinA), number(MinA), inf_greater(MinA,0),
748 minimum_cardinality_of_set(B,Properties,MinB), number(MinB), inf_greater(MinB,0),
749 inf_add(MinA,MinB,MinCard).
750 % TO DO: store information and try to combine with other disjointedness infos
751
752 % TO DO: detect that if f is total function from non_empty set to set X, then card(X)>0
753
754 % is a surjective function
755 is_surjection(SURJ,FromSet,ToSet) :- get_texpr_expr(SURJ,total_surjection(FromSet,ToSet)).
756 is_surjection(SURJ,FromSet,ToSet) :- get_texpr_expr(SURJ,partial_surjection(FromSet,ToSet)).
757 is_surjection(SURJ,FromSet,ToSet) :- get_texpr_expr(SURJ,total_bijection(FromSet,ToSet)). % here we know the exact cardinality - TO DO: use this fact
758 is_surjection(SURJ,FromSet,ToSet) :- get_texpr_expr(SURJ,partial_bijection(FromSet,ToSet)).
759 is_surjection(SURJ,FromSet,ToSet) :- get_texpr_expr(SURJ,total_injection(ToSet,FromSet)). % inverse is surjective
760
761
762
763 % compute the minmum cardinality of an expression
764 minimum_cardinality(ID,MinCard) :- global_set_identifier(ID,GlobalSet),!,
765 ? (b_extract_fd_type(GlobalSet,LowBnd,UpBnd)
766 -> MinCard is 1+UpBnd-LowBnd
767 ; print('*** Do not know card of : '), print(GlobalSet),nl,
768 % TO DO: do full blown cardinality analysis of deferred sets
769 fail).
770 minimum_cardinality(b(EXPR,TYPE,_INFO),MinCard) :-
771 minimum_cardinality2(EXPR,TYPE,MinCard).
772
773 %minimum_cardinality2(A,T,R) :- print(mincard(A,T,R)),nl,fail.
774 minimum_cardinality2(bool_set,_,2).
775 minimum_cardinality2(cartesian_product(A,B),_,Res) :- minimum_cardinality(A,CA),
776 minimum_cardinality(B,CB), kernel_objects:safe_mul(CA,CB,Res).
777 minimum_cardinality2(interval(A,B),_,Res) :-
778 b_get_properties_from_machine(Properties),
779 evaluable_integer_expression(A,Properties,EA),
780 evaluable_integer_expression(B,Properties,EB),
781 (EB >= EA -> Res is EB+1-EA ; Res=0).
782 % TO DO: enumerated sets, ... seq, relations, ... ?
783
784
785 find_min_card_of_disjoint_sets([],_Properties,0).
786 find_min_card_of_disjoint_sets([H|T],Properties,R) :-
787 find_min_card_of_disjoint_sets(T,Properties,TN),
788 (minimum_cardinality_of_set(H,Properties,MC)
789 -> true %,print(min_card(MC,H)),nl
790 ; add_internal_error('Call failed: ',minimum_cardinality_of_set(H,Properties,MC)), MC=1),
791 R is TN+MC.
792
793
794 minimum_cardinality_of_set(b(Expr,set(Type),_),Properties,MC) :-
795 minimum_cardinality_of_set_aux(Expr,Type,Properties,MC).
796
797 %minimum_cardinality_of_set_aux(P,Type,_,_MC) :- print(min_card(P,Type)),nl,fail.
798 minimum_cardinality_of_set_aux(set_extension(List),GlobalSetName,Properties,MinCard) :- !,
799 get_texpr_ids(List,AtomicIDList),
800 find_inequal_global_set_identifiers(AtomicIDList,GlobalSetName,Properties,DisjointConstants),
801 length(DisjointConstants,MinCard). % , print(disj_set_ext(MinCard,DisjointConstants)),nl,nl.
802 minimum_cardinality_of_set_aux(identifier(CST),_Type,_Properties,MinCard) :-
803 find_minimum_cardinality_cache(CST,Nr),!,
804 number(Nr),
805 MinCard=Nr.
806 minimum_cardinality_of_set_aux(identifier(CST),Type,Properties,MinCard) :-
807 Cst_Template = b(identifier(CST),set(Type),_),
808 min_card_of_identifier(Cst_Template,CST,Type,Properties,MC),
809 !,
810 MinCard=MC,
811 assertz(find_minimum_cardinality_cache(CST,MC)). % global sets and constants cannot have the same name
812 % TO DO: add more cases ? sequence extension cannot appear
813 minimum_cardinality_of_set_aux(_,_,_,0).
814
815 % determine minimum cardinality of an identifier; usually a constant (cannot be another global set due to B typing).
816 min_card_of_identifier(Cst_Template,_CST,_Type,Properties,MinCard) :-
817 ? member_in_conjunction(EqCardExpr,Properties), % look for card(CstTemplate) = MinCard
818 is_equality_card_expression(EqCardExpr,Properties,Cst_Template,MinCard), % this is actually an exact card
819 !.
820 min_card_of_identifier(_Cst_Template,CST,_Type,Properties,MinCard) :-
821 ? member_in_conjunction(EqCardExpr,Properties), % look for card(CstTemplate) = MinCard
822 is_greaterequalthan_card_global_set_id(EqCardExpr,CST,_GS,Properties,MinCard),
823 MinCard > 0, % otherwise not helpful; maybe we can find a better bound below
824 !.
825 min_card_of_identifier(Cst_Template,_,_Type,Properties,MC) :-
826 get_texpr_expr(PT,partition(Cst_Template,DisjSets)),
827 member_in_conjunction(PT,Properties),
828 find_min_card_of_disjoint_sets(DisjSets,Properties,MC),!.
829 min_card_of_identifier(Cst_Template,_,Type,Properties,MinCard) :-
830 % id1:CST ... idk:CST & all_different(id1,...,idk) => card(CST) >= k
831 get_texpr_id(TID,ID),
832 get_texpr_expr(EL,member(TID,Cst_Template)),
833 findall(ID,member_in_conjunction(EL,Properties),AtomicIDList),
834 % find all identifiers such that we have id : CST
835 AtomicIDList \= [],
836 !, % now detect which of these can be inferred to be disjoint
837 find_inequal_global_set_identifiers(AtomicIDList,Type,Properties,DisjointConstants),
838 length(DisjointConstants,MinCard).
839 min_card_of_identifier(Cst_Template,_,_Type,Properties,MC) :- % x:CST => card(CST) >= 1
840 get_texpr_expr(EL,member(_,Cst_Template)),
841 member_in_conjunction(EL,Properties),
842 !,
843 MC=1.
844 min_card_of_identifier(Cst_Template,_,_Type,Properties,MC) :- % ID /= {} => card(ID) >= 1
845 ? member_in_conjunction(Pred,Properties),
846 not_empty(Pred,Cst_Template),
847 !,
848 MC=1.
849
850 not_empty(b(E,pred,_),A) :-
851 not_empty_aux(E,A).
852 not_empty_aux(not_equal(A,B),R) :-
853 (definitely_empty_set(B) -> R=A ; definitely_empty_set(A),R=B).
854 not_empty_aux(negation(b(equal(A,B),pred,_)),R) :- not_empty_aux(not_equal(A,B),R).
855 % card() >= dealt with above
856 % not_empty_aux(member(_,TotalFunction)) x: Dom --> R & Dom /= {} ---> R /={}
857
858
859
860
861 % DETECT ENUMERATED constants part of a deferred set
862 % the following could be further improved
863 % try and find out how many different identifiers are in a list in the context of a predicate Prop
864 % it is also called by b_get_disjoint_constants_of_type_calc in bmachine
865 %find_inequal_global_set_identifiers(L,GS,_P,_R) :- print(find_inequal_global_set_identifiers(L,GS)),nl,fail.
866
867 :- use_module(bsyntaxtree,[conjunction_to_list/2]).
868 find_inequal_global_set_identifiers(IDS,GS,Prop,Res) :-
869 sort(IDS,SIDS),
870 conjunction_to_list(Prop,Preds),
871 find_inequal_global_set_identifiers1(SIDS,GS,Preds,Res).
872 find_inequal_global_set_identifiers1(SIDS,GS,Preds,Res) :-
873 length(SIDS,Card), Card>50,
874 % try find all_different predicate first, especially for very large deferred sets the code below is slow
875 member(b(C,pred,_),Preds),
876 all_different(C,List1,Card,GS,Preds), % we have found an all_different predicate of the right size
877 get_texpr_ids(List1,L1),
878 sort(L1,SIDS),!, % the all_different predicate matches all our identifiers
879 debug_println(9,detected_all_diff_global_set(GS,Card)),
880 Res=SIDS.
881 find_inequal_global_set_identifiers1(SIDS,GS,Preds,Res) :-
882 %format('Finding enumerated elements of ~w (over ~w) in: ',[GS,IDS]),translate:print_bexpr(Prop),nl,
883 % first apply nested partition predicates as much as possible to obtain max. large partitions of distinct elements
884 get_relevant_partition_preds(Preds,GS,RelevantPartitionPreds), % TO DO: cache this computation
885 findall(TP,find_a_transitive_partition(RelevantPartitionPreds,TP),TransitivePartitions),
886 append(TransitivePartitions,Preds,Preds2),
887 add_true(SIDS,TIDS),ord_list_to_avl(TIDS,IDS_AVL),
888 find_inequal_global_set_identifiers2(SIDS,IDS_AVL,GS,Preds2,Res).
889
890 % utility to be able to call list_to_avl
891 add_true([],[]).
892 add_true([H|T],[H-true|TT]) :- add_true(T,TT).
893
894
895 find_inequal_global_set_identifiers2([],_,_,_,[]).
896 find_inequal_global_set_identifiers2([ID|T],AVL,GS,Preds,Res) :-
897 (atomic(ID) -> true
898 ; add_internal_error('Not atomic id: ',find_inequal_global_set_identifiers([ID|T],GS,Preds,Res)),fail),
899 avl_delete(ID,AVL,_,AVL1),
900 findall(ID2, (find_inequality(GS,Preds,ID,ID2),
901 avl_fetch(ID2, AVL1,_)
902 ), DiffIDs),
903 sort(DiffIDs,SortedDiffIDs), % also remove duplicates
904 (SortedDiffIDs=[],T=[_,_|_] % then try to proceed with T, ignoring ID
905 -> find_inequal_global_set_identifiers2(T,AVL1,GS,Preds,Res)
906 ; add_true(SortedDiffIDs,SIDT),ord_list_to_avl(SIDT,AVL2),
907 Res = [ID|RT],
908 find_inequal_global_set_identifiers2(SortedDiffIDs,AVL2,GS,Preds,RT)
909 ).
910
911 %find_inequality(_,_,ID,ID2) :- % TODO: make usable; currently VALUES clause is precompiled after this is used
912 % b_extract_values_clause_assignment(ID,Type,TVal1),
913 % b_extract_values_clause_assignment(ID2,Type,TVal2),
914 % ID \= ID2, TVal1 \= TVal2.
915 find_inequality(GS,Preds,ID,ID2) :-
916 ? member(Conjunct,Preds), %print(chck(C)),nl,
917 %translate:print_bexpr_with_limit(Conjunct,100),debug:nl_time,
918 ? inequality(Conjunct,GS,ID,ID2,Preds).
919
920
921 get_relevant_partition_preds(Preds,GS,SortedRelevantPartitionPreds) :-
922 % detect which partition predicates are relevant for this global set
923 findall(partition(Set,Subsets),
924 (member(C,Preds),
925 is_relevant_partition(C,GS,Set,Subsets)), RelevantPartitionPreds),
926 sort(RelevantPartitionPreds,SortedRelevantPartitionPreds).
927 is_relevant_partition(b(partition(Set,Subsets),pred,_),GS,Set,Subsets) :-
928 get_texpr_type(Set,set(GS)). % , translate:print_bexpr(b(partition(Set,Subsets),pred,[])),nl.
929
930 % if we have partition(A,[B,C]) and partition(B,[E,F]) --> generate partition(A,[E,F,C])
931 find_a_transitive_partition(Preds,b(partition(A,C),pred,[generated])) :-
932 ? member(partition(A,B),Preds),
933 inline_subsets(B,Preds,Inlined,C), Inlined==inlined.
934 inline_subsets([],_,_,[]).
935 inline_subsets([Subset1|TS],Preds,inlined,Result) :- get_texpr_id(Subset1,SubID),
936 %prefix(Pred,[partition(S2,SubList)|Pred2]),
937 ? select(partition(Subset2,SubList),Preds,Pred2),
938 get_texpr_id(Subset2,SubID),
939 debug_format(19,'Inlining nested partition predicate for set ~w~n',[SubID]),
940 !,
941 append(SubList,TS,NewList),
942 inline_subsets(NewList,Pred2,_,Result).
943 inline_subsets([Subset1|TS],Preds,Inlined,[Subset1|TSRes]) :- inline_subsets(TS,Preds,Inlined,TSRes).
944
945
946 inequality(b(P,pred,_),GS,ID,OtherID,FullProps) :-
947 ? inequality_aux(P,GS,ID,OtherID,FullProps).
948 inequality_aux(not_equal(I1,I2),GS,ID,OtherID,_) :-
949 gs_identifier(I1,GS,ID1), gs_identifier(I2,GS,ID2),
950 (ID=ID1 -> OtherID=ID2 ; ID=ID2,OtherID=ID1).
951 inequality_aux(not_equal(I1,I2),GS,ID,OtherID,_) :- % treat {aa} \= {bb} or more generally {aa,bb} \= {aa,cc}
952 % two identifiers of global sets need not be different
953 % in order for two set extensions to be inequal
954 % first we check if I1, I2 are in fact subsets of global sets
955 get_texpr_type(I1,set(global(_))),
956 get_texpr_expr(I1,set_extension(IDs1)), % TODO: is there something more general than a set_extension?
957 get_texpr_expr(I2,set_extension(IDs2)), % should full sets or set identifiers added?
958 % remove the common elements and see if we find a pair of identifiers
959 maplist(remove_all_infos_and_ground,IDs1,IDs1NoInfos),
960 maplist(remove_all_infos_and_ground,IDs2,IDs2NoInfos),
961 % TODO: maybe it is same to assume the order?
962 list_to_ord_set(IDs1NoInfos,IDs1Set), list_to_ord_set(IDs2NoInfos,IDs2Set),
963 ord_subtract(IDs1Set,IDs2Set,[E1]), % each set has one identifier that is not in the other one
964 ord_subtract(IDs2Set,IDs1Set,[E2]),
965 E1 \= E2, % and they are not the same
966 gs_identifier(E1,GS,ID1), gs_identifier(E2,GS,ID2),
967 set_ids(ID1,ID2,ID,OtherID).
968 inequality_aux(negation( b(equal(I1,I2),pred,_)),GS,ID,OtherID,_) :-
969 gs_identifier(I1,GS,ID1), gs_identifier(I2,GS,ID2),
970 set_ids(ID1,ID2,ID,OtherID).
971 inequality_aux(partition(Set,DisjSets),GS,ID,OtherID,Preds) :-
972 get_texpr_type(Set,set(GS)), % only look at relevant partitions of correct type
973 %nl,print(part(_Set,DisjSets,GS,ID,OtherID)),nl,
974 % detect such things as partition(_,{...ID...},...{...OtherID...}...)
975 ? select(Set1,DisjSets,Rest), set_extension_list(Set1,Preds,List1),
976 ? member(O1,List1), gs_identifier(O1,GS,ID),
977 ? member(Set2,Rest), set_extension_list(Set2,Preds,List2),
978 ? member(O2,List2), gs_identifier(O2,GS,OtherID).
979 inequality_aux(member(I1,SetDiff),GS,ID,OtherID,_Preds) :-
980 % detect ID : SUPERSET - { ... OtherID ...} => ID:SUPERSET & ID /= OtherID
981 get_texpr_expr(SetDiff,set_subtraction(_SuperSet,b(OtherSet,_,_))),
982 gs_identifier(I1,GS,ID1),
983 id_element_of_set(OtherSet,GS,ID2),
984 set_ids(ID1,ID2,ID,OtherID).
985 inequality_aux(AllDiff,GS,ID,OtherID,Preds) :-
986 all_different(AllDiff,List1,_Card,GS,Preds),
987 select(O1,List1,RestList), gs_identifier(O1,GS,ID),
988 member(O2,RestList), gs_identifier(O2,GS,OtherID).
989
990 set_ids(ID1,ID2,ID,OtherID) :- (ID=ID1 -> OtherID=ID2 ; ID=ID2,OtherID=ID1).
991
992 id_element_of_set(set_extension(List),GS,ID) :-
993 member(I2,List),
994 gs_identifier(I2,GS,ID).
995
996 % detect card({x1,....,xn}) = n as an all-different predicate
997 all_different(equal(A,B),List,Card,Type,Preds) :-
998 all_diff_aux(A,B,List,Card,Type,Preds) ; all_diff_aux(B,A,List,Card,Type,Preds).
999 all_diff_aux(A,B,List1,Card,Type,Preds) :-
1000 A=b(card(Set1),_,_),
1001 get_texpr_type(Set1,set(Type)), % TO DO: also match seq type ? (in case we use predicate in other context)
1002 set_extension_list(Set1,Preds,List1),
1003 evaluable_integer_expression(B,b(truth,pred,[]),Card),
1004 length(List1,Card).
1005
1006 set_extension_list(b(set_extension(List),_,_),_,List).
1007 set_extension_list(b(identifier(ID),_,_),Preds,List) :-
1008 % accept card(GS) = nr & ... GS = {....}
1009 ? member(Eq,Preds),
1010 equality(Eq,TID,b(set_extension(List),_,_)),
1011 get_texpr_id(TID,ID).
1012
1013 equality(b(equal(LHS,RHS),pred,_),L,R) :- ( (L,R)=(LHS,RHS) ; (L,R)=(RHS,LHS) ).
1014
1015 gs_identifier(b(identifier(ID),GS,_),GS,ID).
1016
1017 :- assert_must_succeed(( b_global_sets:is_equality_card_global_set(b(equal(b(card(b(identifier('FACES'),set(global('FACES')),[])),integer,[]),b(integer(6),integer,[])),pred,[]),GS,[],Card),GS='FACES',Card=6)
1018 ).
1019 :- assert_must_succeed(( b_global_sets:is_equality_card_global_set(b(equal(b(card(b(value(global_set('TITLE')),set(global('TITLE')),[])),integer,[]),b(integer(4),integer,[])),pred,[]),GS,[],Card),
1020 GS=='TITLE', Card=4)
1021 ).
1022
1023 is_equality_card_expression(TE,Properties,Expr,Card) :-
1024 get_texpr_expr(TE,equal(LHS,RHS)),
1025 get_texpr_expr(LHS,L), get_texpr_expr(RHS,R),
1026 ( L=card(Expr), evaluable_integer_expression(R,Properties,Card)
1027 ; R=card(Expr), evaluable_integer_expression(L,Properties,Card)).
1028
1029 is_equality_card_global_set(TE,GlobalSet,Properties,Card) :-
1030 ? is_equality_card_expression(TE,Properties,Expr,Card),
1031 global_set_identifier(Expr,GlobalSet),
1032 get_texpr_type(Expr,set(global(GlobalSet))).
1033
1034 % detect a predicate that stipulates that given Set is infinite
1035 % i.e., we detect not(finite(GS)) which can be rewritten from not(GS:FIN(GS)) in ast_cleanup by introduce_finite rule
1036 is_infinite_global_set_pred(Pred,GlobalSetName) :-
1037 get_texpr_expr(Pred,negation(Pred2)),
1038 get_texpr_expr(Pred2,finite(ID)),
1039 get_texpr_id(ID,GlobalSetName).
1040
1041 %evaluable_integer_expression(X,_Y,_) :- print(ev(X)),nl,fail.
1042 % TO DO: maybe we should do some kind of constant folding or call b_compile ??
1043 evaluable_integer_expression(b(E,integer,_),Properties,R) :-
1044 evaluable_integer_expression(E,Properties,R).
1045 evaluable_integer_expression(max_int,_,R) :- preferences:preference(maxint,R).
1046 evaluable_integer_expression(min_int,_,R) :- preferences:preference(minint,R).
1047 evaluable_integer_expression(identifier(ID),Properties,R) :-
1048 get_texpr_expr(Eq,equal(LHS,RHS)), get_texpr_id(LHS,ID),
1049 select_member_in_conjunction(Eq,Properties,RestProp), % avoids loops; but an identifier cannot be used multiple times N+N
1050 evaluable_integer_expression(RHS,RestProp,R).
1051 evaluable_integer_expression(card(Set),Properties,Card) :-
1052 Set = b(identifier(GlobalSetName),set(global(GlobalSetName)),_),
1053 (extract_setsize_from_machine_cache(GlobalSetName,L,U)
1054 -> Card is U+1-L
1055 ; select_member_in_conjunction(Eq,Properties,RestProp),
1056 is_equality_card_global_set(Eq,GlobalSetName,RestProp,Card)
1057 ).
1058 evaluable_integer_expression(integer(Card),_,Card).
1059 evaluable_integer_expression(div(A,B),Properties,Res) :-
1060 evaluable_integer_expression(A,Properties,RA),
1061 evaluable_integer_expression(B,Properties,RB), Res is RA // RB.
1062 evaluable_integer_expression(multiplication(A,B),Properties,Res) :-
1063 evaluable_integer_expression(A,Properties,RA),
1064 evaluable_integer_expression(B,Properties,RB), Res is RA*RB.
1065 evaluable_integer_expression(add(A,B),Properties,Res) :-
1066 evaluable_integer_expression(A,Properties,RA),
1067 evaluable_integer_expression(B,Properties,RB), Res is RA+RB.
1068 evaluable_integer_expression(minus(A,B),Properties,Res) :-
1069 evaluable_integer_expression(A,Properties,RA),
1070 evaluable_integer_expression(B,Properties,RB), Res is RA-RB.
1071 evaluable_integer_expression(unary_minus(A),Properties,Res) :-
1072 evaluable_integer_expression(A,Properties,RA), Res is 0-RA.
1073
1074 % checks if we have an identifier or a precompiled global_set value
1075 global_set_identifier(C,GS) :- get_texpr_expr(C,BE), global_set_identifier2(BE,GS).
1076 global_set_identifier2(identifier(GlobalSet),GlobalSet).
1077 global_set_identifier2(value(global_set(GlobalSet)),GlobalSet). % generated by Z
1078
1079 % check for card(GlobalSet) >= Card or similar
1080 is_greaterequalthan_card_global_set(TE,GlobalSet,Properties,Card) :-
1081 is_greaterequalthan_card_global_set_id(TE,GlobalSet,GlobalSet,Properties,Card).
1082 % check for card(Identifier) >= Card or similar with Identifier of type GlobalSet
1083 is_greaterequalthan_card_global_set_id(TE,Identifier,GlobalSet,Properties,Card) :-
1084 (get_texpr_expr(TE,greater_equal(LHS,RHS)) ;
1085 get_texpr_expr(TE,less_equal(RHS,LHS)) ),
1086 get_texpr_expr(LHS,card(C)),
1087 get_minimum_or_exact_value(RHS,Properties,Card),
1088 global_set_identifier(C,Identifier),
1089 get_texpr_type(C,set(global(GlobalSet))).
1090 is_greaterequalthan_card_global_set_id(TE,Identifier,GlobalSet,Properties,Card1) :-
1091 (get_texpr_expr(TE,greater(LHS,RHS)) ;
1092 get_texpr_expr(TE,less(RHS,LHS)) ),
1093 get_texpr_expr(LHS,card(C)),
1094 get_minimum_or_exact_value(RHS,Properties,Card),
1095 number(Card), Card1 is Card+1,
1096 global_set_identifier(C,Identifier),
1097 get_texpr_type(C,set(global(GlobalSet))).
1098 is_greaterequalthan_card_global_set_id(TE,GlobalSet,GlobalSet,_Properties,2) :-
1099 %% preferences:get_preference(allow_empty_global_sets,false), preference no longer exists
1100 /* GlobalSet /= { ANY } -> as GlobalSet cannot be empty & as ANY must be well-typed:
1101 we need at least one more element of GlobalSet */
1102 get_texpr_expr(TE,not_equal(LHS,RHS)),
1103 ( get_texpr_expr(LHS,identifier(GlobalSet))
1104 -> get_texpr_expr(RHS,set_extension([b(_X,global(GlobalSet),_)]))
1105 ; get_texpr_expr(RHS,identifier(GlobalSet)),
1106 get_texpr_expr(LHS,set_extension([b(_X,global(GlobalSet),_)]))
1107 ).
1108 %%print(not_equal(GlobalSet,_X)),nl.
1109 % not_equal(S_CHEMIN_ID,b(set_extension([b(identifier(C_NULL_CHEMIN_ID),global(S_CHEMIN_ID),[nodeid(pos(35,1,80,27,80,42)),loc(local,emi,concrete_constants)])]),set(global(S_CHEMIN_ID)),[nodeid(pos(34,1,80,26,80,43))]))
1110
1111 % get mininimum or exact value for an expression
1112 get_minimum_or_exact_value(TE,Properties,N) :- %print(get_min(TE,Properties)),nl,nl,
1113 get_texpr_expr(TE,E),
1114 get_minimum_or_exact_value_aux(E,Properties,N).
1115 get_minimum_or_exact_value_aux(integer(N),_,N).
1116 get_minimum_or_exact_value_aux(identifier(ID),Properties,N) :-
1117 %(extract_min_or_exact_value_for_id(ID,Properties,N) -> true). % avoid backtracking; TO DO: in future all this should be part of constraint solving
1118 findall(NVal,extract_min_or_exact_value_for_id(ID,Properties,NVal),NVals),
1119 max_member(N,NVals). % find the maximum value for which we need to be greater(_equal) to
1120
1121 get_minimum_or_exact_value_aux(add(A,B),Properties,Res) :-
1122 get_minimum_or_exact_value(A,Properties,RA),
1123 get_minimum_or_exact_value(B,Properties,RB), Res is RA+RB.
1124 % TO DO: other operators
1125 get_minimum_or_exact_value_aux(card(Set),_Properties,Card) :-
1126 Set = b(identifier(GlobalSetName),set(global(GlobalSetName)),_),
1127 try_extract_setsize_from_machine(GlobalSetName,L,U), % will try extraction; unless a cycle is hit
1128 Card is U+1-L.
1129
1130 extract_min_or_exact_value_for_id(ID,Properties,N) :-
1131 member_in_conjunction(TE,Properties),
1132 get_texpr_expr(TE,E),
1133 get_value_bound(E,ID,N).
1134
1135 % equalities already inlined
1136 get_value_bound(equal(LHS,RHS),ID,N) :- get_texpr_id(LHS,ID), get_texpr_integer(RHS,N).
1137 get_value_bound(equal(RHS,LHS),ID,N) :- get_texpr_id(LHS,ID), get_texpr_integer(RHS,N).
1138 get_value_bound(greater(LHS,RHS),ID,N1) :- get_texpr_id(LHS,ID), get_texpr_integer(RHS,N), N1 is N+1.
1139 get_value_bound(less(RHS,LHS),ID,N1) :- get_texpr_id(LHS,ID), get_texpr_integer(RHS,N), N1 is N+1.
1140 get_value_bound(greater_equal(LHS,RHS),ID,N) :- get_texpr_id(LHS,ID), get_texpr_integer(RHS,N).
1141 get_value_bound(less_equal(RHS,LHS),ID,N) :- get_texpr_id(LHS,ID), get_texpr_integer(RHS,N).
1142
1143 get_texpr_integer(b(integer(N),_,_),N).
1144
1145
1146 :- volatile global_set_user_defined_scope/2.
1147 :- dynamic global_set_user_defined_scope/2.
1148
1149 /* allow to set scope for specific sets, e.g., via command-line */
1150 set_user_defined_scope(GS,X) :-
1151 \+ number(X),!,
1152 add_internal_error('Scope must be number: ',set_user_defined_scope(GS,X)).
1153 set_user_defined_scope(GS,X) :-
1154 format('% Setting user defined scope: ~w == ~w~n',[GS,X]),
1155 assertz(global_set_user_defined_scope(GS,X)).
1156
1157 get_user_defined_scope(GlobalSetName,_,_,_) :- var(GlobalSetName),!,
1158 add_internal_error('Arg is variable: ',get_user_defined_scope(GlobalSetName)).
1159 get_user_defined_scope(GlobalSetName,LowBound,UpBound,Span) :-
1160 (global_set_user_defined_scope(GlobalSetName,UpBound) % from command-line
1161 -> LowBound=1, Span = unknown
1162 ; extract_setsize_from_defs(GlobalSetName,LowBound,UpBound,Span) % scopeSET == Low..Up from DEFINITIONS
1163 ).
1164
1165 :- use_module(translate,[translate_bexpression/2]).
1166 % find scope_NAME == Low..Up in DEFINITIONS
1167 extract_setsize_from_defs(GlobalSetName,LowBound,UpBound,DefTerm) :-
1168 b_get_machine_setscope(GlobalSetName,DefTerm),
1169 get_texpr_expr(DefTerm,DefExpr),
1170 (extract_integer_range(DefExpr,LowBound,UpBound)
1171 -> true
1172 ; translate_bexpression(DefTerm,DS),
1173 add_warning(extract_setsize_from_defs,'scope DEFINITION for deferred set should be number or interval: ',DS,DefTerm),
1174 fail
1175 ).
1176
1177 extract_integer_range(interval(LB,UB), LowBound, UpBound) :-
1178 get_texpr_expr(LB,integer(LowBound)), get_texpr_expr(UB,integer(UpBound)).
1179 %extract_integer_range(set_extension(CstList),LowBound,UpBound) :-
1180 % LowBound = 1, length(CstList,UpBound). % extract names of constants in list for pretty printing; check that different names
1181 %extract_integer_range(value(avl_set(A)),LowBound,UpBound) :-
1182 % LowBound = 1, avl_size(A,UpBound).
1183 extract_integer_range(integer(UpBound),LowBound,UpBound) :-
1184 LowBound = 1, UpBound>0.
1185
1186
1187 :- dynamic start_extracting_setsize/1.
1188
1189 start_extracting_setsize_from_machine(GlobalSetName) :- %print(start(GlobalSetName)),nl,
1190 (start_extracting_setsize(GlobalSetName)
1191 -> add_internal_error('Cyclic computation: ',start_extracting_setsize_from_machine(GlobalSetName))
1192 ; assertz(start_extracting_setsize(GlobalSetName))).
1193
1194 assert_extract_setsize_from_machine_cache(GlobalSetName,LowBound,UpBound) :-
1195 retractall(start_extracting_setsize(GlobalSetName)),
1196 %print(finished(GlobalSetName,LowBound,UpBound)),nl,
1197 (retract(extract_setsize_from_machine_cache(GlobalSetName,L,U))
1198 -> print(overriding_set_size(GlobalSetName,LowBound-UpBound,L-U)),nl
1199 ; true),
1200 assertz(extract_setsize_from_machine_cache(GlobalSetName,LowBound,UpBound)),
1201 (integer(UpBound), UpBound<LowBound
1202 -> format_error_with_nl('*** Illegal empty global set ~w, bounds ~w:~w',[GlobalSetName,LowBound,UpBound])
1203 ; true
1204 ).
1205
1206
1207 %% b_try_update_fd_cardinality has been removed
1208
1209 :- volatile enumerated_set/1, fixed_deferred_set_size/2.
1210 :- dynamic enumerated_set/1, fixed_deferred_set_size/2.
1211 % true if GS is a deferred set whose size was not fixed; i.e., ProB has not inspected all possible instantiations
1212 % TODO: rename to unfixed_or_infinite_deferred_set
1213 unfixed_deferred_set(GS) :-
1214 ? if(b_global_set(GS),
1215 (\+ enumerated_set(GS),
1216 \+ fixed_finite_deferred_set_size(GS,_)),
1217 (debug_println(unknown_global_set(GS)),fail)). % triggered in test 2063
1218
1219 ?unfixed_deferred_set_exists :- b_global_set(GS), unfixed_deferred_set(GS),!.
1220
1221 % a global set that is treated as infinite by ProB
1222 % not unfixed deferred sets may still in principle allowed to be infinite, but could be give a finite card by ProB
1223 infinite_global_set(GlobalSetName) :-
1224 (fixed_deferred_set_size(GlobalSetName,X) -> X=inf
1225 ; inferred_maximum_global_set_cardinality(GlobalSetName,MaxCard) -> MaxCard=inf % should not happen
1226 ; enumerated_set(GlobalSetName) -> false
1227 % ; (precompilation_phase(Phase) -> true ; Phase=0),
1228 % nl,print(not_provably_infinite_global_set(GlobalSetName,Phase)),nl,nl,portray_global_sets,nl,fail
1229 ).
1230
1231 provably_finite_global_set(GlobalSetName) :-
1232 enumerated_set(GlobalSetName),!.
1233 provably_finite_global_set(GlobalSetName) :-
1234 fixed_deferred_set_size(GlobalSetName,X),!, number(X).
1235 provably_finite_global_set(GlobalSetName) :-
1236 inferred_maximum_global_set_cardinality(GlobalSetName,MaxCard),!,
1237 integer(MaxCard).
1238 %provably_finite_global_set(GS) :- (precompilation_phase(Phase) -> true ; Phase=0),
1239 % nl,print(not_provably_finite_global_set(GS,Phase)),nl,nl,portray_global_sets,nl,fail.
1240
1241 fixed_finite_deferred_set_size(Set,Card) :- fixed_deferred_set_size(Set,Card), integer(Card).
1242
1243 ?contains_unfixed_deferred_set(Type) :- (contains_unfixed_deferred_set(Type,_) -> true).
1244
1245 ?contains_unfixed_deferred_set(global(Type),DS) :- unfixed_deferred_set(Type),DS=Type.
1246 ?contains_unfixed_deferred_set(set(Type),DS) :- contains_unfixed_deferred_set(Type,DS).
1247 contains_unfixed_deferred_set(seq(Type),DS) :- contains_unfixed_deferred_set(Type,DS).
1248 contains_unfixed_deferred_set(couple(Type1,Type2),DS) :-
1249 (contains_unfixed_deferred_set(Type1,DS) -> true ; contains_unfixed_deferred_set(Type2,DS)).
1250 contains_unfixed_deferred_set(record(Fields),DS) :-
1251 (member(field(_,Type),Fields), contains_unfixed_deferred_set(Type,DS) -> true).
1252
1253
1254 % enumerated sets can be registered here, before cleaning up a machine
1255 % this way we already know which sets are enumerated and definitely finite
1256 % and we can also register the enumerated set elements
1257 register_enumerated_sets([],_).
1258 register_enumerated_sets([TID|T],Elems) :- def_get_texpr_id(TID,ID), get_texpr_type(TID,set(Type)),
1259 El = b(identifier(Elem),Type,_),
1260 findall(Elem,member(El,Elems),EnumElems),
1261 pre_register_enumerated_set_with_elems(ID,EnumElems),
1262 register_enumerated_sets(T,Elems).
1263
1264 pre_register_enumerated_set_with_elems(GlobalSetName,ListOfConstants) :-
1265 (enumerated_set(GlobalSetName) -> true
1266 ; debug_format(19,'Pre-register ~w = ~w~n',[GlobalSetName,ListOfConstants]),
1267 assert_enumerated_set(GlobalSetName,ListOfConstants,_LowBound,_UpBound)
1268 ).
1269 % pre-registering just the enumerated set name
1270 pre_register_enumerated_set(GlobalSetName) :-
1271 (enumerated_set(GlobalSetName) -> true
1272 ; debug_format(9,'Pre-register ~w~n',[GlobalSetName]),
1273 assertz(enumerated_set(GlobalSetName))
1274 ).
1275
1276
1277 :- assert_pre(b_global_sets:assert_enumerated_set(_GS,_L,_,_),true).
1278 % TODO(DP, 7.8.2008)
1279 % (atomic(GS),type_check(L,list(xml_identifier)))).
1280 :- assert_post(b_global_sets:assert_enumerated_set(_,_,L,U),(number(L),number(U))).
1281
1282 % TODO: also process b_extract_values_clause_assignment(Cst,integer,Nr) facts !
1283 assert_enumerated_set(GlobalSetName,ListOfConstants,LowBound,UpBound) :-
1284 (enumerated_set(GlobalSetName) -> true ; assert(enumerated_set(GlobalSetName))),
1285 LowBound = 1,
1286 length(ListOfConstants,UpBound),
1287 assert_extract_setsize_from_machine_cache(GlobalSetName,LowBound,UpBound),
1288 add_named_constants_to_global_set(GlobalSetName,LowBound,ListOfConstants).
1289
1290 add_named_constants_to_global_set(GlobalSetName,LowBound,ListOfConstants) :-
1291 (b_global_constant(GlobalSetName,CurNr,CurCst)
1292 -> add_error_fail(add_named_constants_to_global_set,'Globalset already has constants: ',
1293 b_global_constant(GlobalSetName,CurNr,CurCst))
1294 ; true),
1295 ? nth0(Nr0,ListOfConstants,Cst),
1296 (lookup_global_constant(Cst,fd(_,GS2))
1297 -> (GS2=GlobalSetName
1298 -> add_internal_error('Duplicate element in global set:',(Cst,GS2)) % error is already caught by type checker
1299 ; add_internal_error('Element appears in multiple sets:',(Cst,GS2,GlobalSetName)) % ditto
1300 )
1301 ; true
1302 ),
1303 Nr is Nr0+LowBound,
1304 assertz(b_global_constant(GlobalSetName,Nr,Cst)),
1305 term_hash(fd(Nr,GlobalSetName),Hash),
1306 assertz(b_global_constant_hash(Hash,GlobalSetName,Nr,Cst)),
1307 assertz(lookup_global_constant(Cst,fd(Nr,GlobalSetName))),
1308 %format('Added ~w as nr ~w to ~w~n',[Cst,Nr,GlobalSetName]),
1309 fail.
1310 add_named_constants_to_global_set(_,_,_).
1311
1312
1313
1314 :- assert_pre(b_global_sets:b_extract_fd_type(_G,_L,_U),true).
1315 :- assert_post(b_global_sets:b_extract_fd_type(G,L,U),(atomic(G),(integer(L),integer(U)))).
1316
1317 b_extract_fd_type(GlobalSetName,LowBound,UpBound) :-
1318 ? b_global_set(GlobalSetName), % was b_get_machine_set(GlobalSetName),
1319 extract_setsize_from_machine(GlobalSetName,LowBound,UpBound).
1320
1321 is_b_precompiled_globalset(GlobalSetName) :- extract_setsize_from_machine_cache(GlobalSetName,_,_).
1322
1323 % like b_extract_fd_type above, but with GS known (avoids backtracking b_supplementary_global_set)
1324 b_get_fd_type_bounds(NonvarGlobalSetname,LowBound,UpBound) :- nonvar(NonvarGlobalSetname),
1325 extract_setsize_from_machine_cache(NonvarGlobalSetname,L,U),
1326 !,
1327 (LowBound,UpBound)=(L,U).
1328 b_get_fd_type_bounds(GS,L,U) :- b_replaced_global_set(GS,_),!,
1329 add_internal_error('Global set has been replaced: ',b_get_fd_type_bounds(GS,L,U)),fail.
1330 b_get_fd_type_bounds(GS,L,U) :-
1331 add_internal_error('Illegal call: ',b_get_fd_type_bounds(GS,L,U)),fail.
1332
1333
1334 b_global_set_cardinality('STRING',Card) :- !, Card=inf.
1335 b_global_set_cardinality('REAL',Card) :- !, Card=inf.
1336 b_global_set_cardinality('FLOAT',Card) :- !, Card=18446744073709551616. % 2^64 - TO DO: check
1337 b_global_set_cardinality('NAT',Card) :- !, get_preference(maxint,MaxInt), Card is MaxInt+1.
1338 b_global_set_cardinality('NATURAL',Card) :- !, Card=inf. %get_preference(maxint,MaxInt), Card is MaxInt+1.
1339 b_global_set_cardinality('NAT1',Card) :- !, get_preference(maxint,Card).
1340 b_global_set_cardinality('NATURAL1',Card) :- !, Card=inf. % get_preference(maxint,Card).
1341 b_global_set_cardinality('INT',Card) :- !, get_preference(maxint,MaxInt),
1342 get_preference(minint,MinInt),
1343 (MaxInt >= MinInt -> Card is MaxInt-MinInt+1
1344 ; add_error(b_global_set_cardinality,'MININT larger than MAXINT',(MinInt:MaxInt)),
1345 Card = 0
1346 ).
1347 b_global_set_cardinality('INTEGER',Card) :- !, Card=inf. % b_global_set_cardinality('INT',Card).
1348 b_global_set_cardinality(GlobalSet,Card) :- nonvar(GlobalSet),!,
1349 (b_fd_card(GlobalSet,C) -> Card=C
1350 ; b_replaced_global_set(GlobalSet,_) ->
1351 add_internal_error('Global set has been replaced: ', b_global_set_cardinality(GlobalSet,Card)),
1352 fail
1353 ; add_internal_error('Unknown global set: ', b_global_set_cardinality(GlobalSet,Card)),
1354 fail).
1355 b_global_set_cardinality(GlobalSet,Card) :- %b_global_set(GlobalSet),
1356 b_extract_fd_type(GlobalSet,Low,Up), Card is 1+ Up - Low.
1357 % enum_warning_for_global_set(GlobalSet,'assuming deferred set to be of given cardinality',Card,trigger_true(card)).
1358 %% Note: The Disprover now checks whether unfixed_deferred sets were involved; keeping track of implicit enumerations of deferred sets is just too difficult
1359
1360 b_fd_card(GlobalSet,Card) :- b_get_fd_type_bounds(GlobalSet,Low,Up),
1361 (Up=inf -> Card=inf ; Card is 1+Up-Low).
1362
1363 b_non_empty_global_set(_). % allow_empty_global_sets no longer exists; all global_sets are non-empty
1364 %b_non_empty_global_set(IntSet) :- b_integer_or_real_or_string_set(IntSet).
1365 %b_non_empty_global_set(GlobalSet) :- b_global_set(GlobalSet),
1366 % b_get_fd_type_bounds(GlobalSet,Low,Up), Up >= Low.
1367
1368 b_empty_global_set(_) :- fail. % allow_empty_global_sets no longer exists; all global_sets are non-empty
1369 %b_empty_global_set(GlobalSet) :- %b_global_set(GlobalSet),
1370 % b_get_fd_type_bounds(GlobalSet,Low,Up), Up < Low.
1371
1372
1373 b_integer_or_real_or_string_set('STRING').
1374 b_integer_or_real_or_string_set('FLOAT').
1375 b_integer_or_real_or_string_set('REAL').
1376 b_integer_or_real_or_string_set(X) :- b_integer_set(X).
1377
1378 b_integer_or_real_set('REAL').
1379 b_integer_or_real_set('FLOAT').
1380 b_integer_or_real_set(X) :- b_integer_set(X).
1381
1382 b_integer_set('NAT'). b_integer_set('NATURAL').
1383 b_integer_set('NAT1'). b_integer_set('NATURAL1').
1384 b_integer_set('INT'). b_integer_set('INTEGER').
1385
1386 % convert a type term into a global_set term
1387 try_b_type2global_set(string,R) :- !, R= global_set('STRING').
1388 try_b_type2global_set(integer,R) :- !, R= global_set('INTEGER').
1389 try_b_type2global_set(real,R) :- !, R= global_set('REAL').
1390 ?try_b_type2global_set(global(GS),R) :- b_global_set(GS),!, R=global_set(GS).
1391 try_b_type2global_set(freetype(ID),R) :- !, R=freetype(ID).
1392 try_b_type2global_set(boolean,R) :- !,
1393 %custom_explicit_sets:construct_avl_from_lists([pred_false /* bool_false */,pred_true /* bool_true */],R).
1394 R = avl_set(node(pred_false,true,1,empty,node(pred_true,true,0,empty,empty))).
1395
1396 b_type2_set(GS,Res) :- try_b_type2global_set(GS,GR),!, Res=GR.
1397 b_type2_set(Type,Res) :- Res = closure(['_zzzz_unary'],[Type],b(truth,pred,[])).
1398 %b_type2global_set(GS,_) :- add_error_and_fail(b_type2_set,'Type cannot be converted to global_set: ',GS).
1399
1400 :- use_module(fd_utils_clpfd). % in_fd
1401
1402 global_type(fd(X,GlobalSet),GlobalSet) :- %b_global_set(GlobalSet),
1403 if(b_get_fd_type_bounds(GlobalSet,Low,Up), %print(b_get_fd_type_bounds(X,GlobalSet,Low,Up)),nl, when(nonvar(X),trace),
1404 % print(in_fd(X,Low,Up)),nl,
1405 in_fd(X,Low,Up),
1406 add_internal_error('Illegal global set: ',global_type(fd(X,GlobalSet),GlobalSet))).
1407 global_type2(X,GlobalSet) :- %b_global_set(GlobalSet),
1408 if(b_get_fd_type_bounds(GlobalSet,Low,Up),
1409 in_fd(X,Low,Up),
1410 add_internal_error('Illegal global set: ',global_type2(X,GlobalSet))).
1411
1412 global_type_wf(fd(X,GlobalSet),GlobalSet,WF) :- %b_global_set(GlobalSet),
1413 b_get_fd_type_bounds(GlobalSet,Low,Up), %print(b_get_fd_type_bounds(X,GlobalSet,Low,Up)),nl,
1414 in_fd_wf(X,Low,Up,WF).
1415
1416 % get value and setup global_type FD constraint if it is a variable
1417 get_global_type_value(FD,Type,X) :-
1418 (var(FD) % print(fresh(Type,FD)),nl,
1419 -> (nonvar(Type)
1420 -> global_type2(X,Type) % instantiate FD bounds if we create a fresh FD variable X
1421 ; true
1422 ),
1423 FD = fd(X,Type)
1424 ; FD = fd(X,TypeX),
1425 (Type \== TypeX, nonvar(Type), nonvar(TypeX)
1426 -> add_internal_error('FD Type error:',get_global_type_value(FD,Type,X))
1427 ; true),
1428 TypeX=Type
1429 ).
1430
1431 % like enum_global_type but with a nonvar GlobalSet + generate enum_warning for deferred set (currently commented out)
1432 enumerate_global_type_with_enum_warning(R,GlobalSet,EnumWarning,WF) :- var(R),!, % print(enum_var(R,GlobalSet)),nl,
1433 b_get_fd_type_bounds_with_enum_warning(X,GlobalSet,Low,Up,EnumWarning,WF),
1434 % first setup CLP(FD) bounds before enumerating
1435 in_fd(X,Low,Up), % Note: Up can be the restricted range for infinite sets
1436 R=fd(X,GlobalSet),
1437 ? enum_fd(X,Low,Up).
1438 enumerate_global_type_with_enum_warning(fd(X,GlobalSet),GlobalSet,EnumWarning,WF) :-
1439 (nonvar(X) -> true
1440 ; b_get_fd_type_bounds_with_enum_warning(X,GlobalSet,Low,Up,EnumWarning,WF),
1441 ? enum_fd(X,Low,Up)
1442 ).
1443
1444 :- use_module(probsrc(clpfd_interface),[clpfd_domain/3]).
1445
1446 b_get_fd_type_bounds_with_enum_warning(X,GlobalSet,Low2,Up2,EnumWarning,WF) :-
1447 b_get_fd_type_bounds(GlobalSet,Low,Up),
1448 (Up=inf
1449 -> clpfd_domain(X,LowX,UpX),
1450 (integer(UpX), integer(LowX) -> Low2=LowX, Up2=UpX
1451 ; get_preference(maxint,MaxInt),
1452 (integer(LowX), LowX >= MaxInt ->
1453 gen_enum_warning_wf(GlobalSet,Low:Up,LowX:LowX,EnumWarning,unknown,WF),
1454 Low2=LowX, Up2=LowX % we could increase Up2, e.g., to LowX+MaxInt
1455 ; gen_enum_warning_wf(GlobalSet,Low:Up,Low:MaxInt,EnumWarning,unknown,WF),
1456 Low2=Low, Up2=MaxInt
1457 )
1458 )
1459 ; Low2=Low,Up2=Up
1460 ).
1461
1462 % enumerate global types, but limit infinite ones
1463 enum_global_type_limited(fd(X,GlobalSet),GlobalSet) :- %b_global_set(GlobalSet),
1464 (nonvar(GlobalSet) ->
1465 ? (b_get_fd_type_bounds_limited(GlobalSet,Low,Up) -> enum_global_type_aux(X,Low,Up,GlobalSet)
1466 ; add_internal_error('Illegal value: ',enum_global_type(fd(X,GlobalSet),GlobalSet)),fail)
1467 ; b_global_set(GlobalSet),
1468 b_get_fd_type_bounds(GlobalSet,Low,Up),
1469 enum_global_type_aux(X,Low,Up,GlobalSet)
1470 ).
1471
1472 enum_global_type_aux(X,Low,Up,GlobalSet) :-
1473 atomic(X),
1474 !,
1475 (number(X),X >= Low, X =< Up
1476 -> true
1477 ; add_internal_error('Illegal value: ', enum_global_type_aux(X,Low,Up,GlobalSet))).
1478 enum_global_type_aux(X,Low,Up,_GlobalSet) :-
1479 ? enum_fd(X,Low,Up).
1480
1481 % get range information for global set and generate warning if necessary
1482 %b_fd_type_with_enum_warning(GlobalSet,Low,Up) :-
1483 % b_fd_type(GlobalSet,Low,Up),
1484 % enum_warning_for_global_set(GlobalSet,'assuming deferred set to be of finite cardinality',Up,trigger_true(card)).
1485
1486 /* ------------------------------------- */
1487
1488 all_elements_of_type(Type,Set) :-
1489 all_elements_of_type_wf(Type,Set,no_wf_available).
1490
1491 :- block all_elements_of_type_wf(-,?,?).
1492 all_elements_of_type_wf(Type,Set,WF) :- % print(all_elements(Type,Set)),nl,
1493 all_elements_of_type2(Type,Set,WF).
1494
1495 :- use_module(kernel_objects,[all_strings_wf/2, gen_enum_warning_wf/6]).
1496 all_elements_of_type2('STRING',Res,WF) :- !,
1497 all_strings_wf(Res,WF).
1498 all_elements_of_type2('NAT',Res,_WF) :- !, get_preference(maxint,MaxInt),
1499 gen_int_set(0,MaxInt,Res).
1500 all_elements_of_type2('NATURAL',Res,WF) :- !, get_preference(maxint,MaxInt),
1501 gen_enum_warning_wf('NATURAL',0:sup,0:MaxInt,trigger_throw('NATURAL'),unknown,WF), %print('### Warning: expanding NATURAL'),nl,
1502 gen_int_set(0,MaxInt,Res).
1503 all_elements_of_type2('NAT1',Res,_WF) :- !, get_preference(maxint,MaxInt),
1504 gen_int_set(1,MaxInt,Res).
1505 all_elements_of_type2('NATURAL1',Res,WF) :- !,
1506 get_preference(maxint,MaxInt),
1507 gen_enum_warning_wf('NATURAL1',1:sup,1:MaxInt,trigger_throw('NATURAL1'),unknown,WF), %print('### Warning: expanding NATURAL1'),nl,
1508 gen_int_set(1,MaxInt,Res).
1509 all_elements_of_type2('INT',Res,_WF) :- !, get_preference(maxint,MaxInt),
1510 get_preference(minint,MinInt),
1511 gen_int_set(MinInt,MaxInt,Res).
1512 all_elements_of_type2('INTEGER',Res,WF) :- !, get_preference(maxint,MaxInt),
1513 get_preference(minint,MinInt),
1514 gen_enum_warning_wf('INTEGER',inf:sup,MinInt:MaxInt,trigger_throw('INTEGER'),unknown,WF), %print('### Warning: expanding INTEGER'),nl,
1515 gen_int_set(MinInt,MaxInt,Res).
1516 all_elements_of_type2('FLOAT',Res,WF) :- !, all_elements_of_type2('REAL',Res,WF).
1517 all_elements_of_type2('REAL',Res,WF) :- !,
1518 gen_enum_warning_wf('REAL',inf:sup,0.0:1.0,trigger_throw('REAL'),unknown,WF),
1519 Res = [term(floating(0.0)),term(floating(1.0))]. % not sure this will ever be used
1520 all_elements_of_type2(Type,Set,WF) :-
1521 b_get_fd_type_bounds(Type,Low,Up),
1522 (Up=inf
1523 -> get_preference(maxint,MaxInt), % infinite deferred set
1524 gen_enum_warning_wf(Type,Low:Up,Low:MaxInt,trigger_throw(Type),unknown,WF),
1525 findall(fd(El,Type),enum_fd_linear(El,Low,MaxInt),Set)
1526 ; % ensure we do not use Random enumeration
1527 findall(fd(El,Type),enum_fd_linear(El,Low,Up),Set)
1528 ).
1529
1530 % a version of all_elements_of_type which may randomise element order if preference set
1531 :- block all_elements_of_type_rand_wf(-,?,?).
1532 all_elements_of_type_rand_wf(Type,Set,WF) :- % print(all_elements(Type,Set)),nl,
1533 all_elements_of_type_rand2(Type,Set,WF).
1534
1535 ?all_elements_of_type_rand2(Type,Set,_WF) :- b_global_set(Type),!,
1536 b_get_fd_type_bounds(Type,Low,Up),
1537 % may use Random enumeration if preference RANDOMISE_ENUMERATION_ORDER set
1538 findall(fd(El,Type),enum_fd(El,Low,Up),Set).
1539 all_elements_of_type_rand2(Type,Set,WF) :- % TO DO: we could permute the solution here; but currently all_elements_of_type_rand2 is only called for enumerated/deferred sets
1540 all_elements_of_type2(Type,Set,WF).
1541
1542
1543 gen_int_set(Min,Max,Set) :-
1544 (Min>Max -> Set = []
1545 ; Set = [int(Min)|RSet],
1546 M1 is Min+1,
1547 gen_int_set(M1,Max,RSet)).
1548
1549 %% list_contains_unfixed_deferred_set_id(+TypedIds).
1550 list_contains_unfixed_deferred_set_id([b(identifier(_),Type,_)|_]) :-
1551 contains_unfixed_deferred_set(Type),
1552 !.
1553 list_contains_unfixed_deferred_set_id([_|T]) :-
1554 list_contains_unfixed_deferred_set_id(T).
1555
1556 % -----------------
1557 :- public portray_global_sets/0. % debugging utility
1558 portray_global_sets :-
1559 (enumerated_sets_precompiled -> Comp=true ; Comp=false),
1560 format('ENUMERATED SETS (precompiled=~w):~n ',[Comp]),
1561 enumerated_set(GS),
1562 format(' ~w ',[GS]),
1563 fail.
1564 portray_global_sets :-
1565 (deferred_sets_precompiled -> Comp=true ; Comp=false),
1566 format('~nDEFERRED SETS with some constants (precompiled=~w):~n ',[Comp]),
1567 b_partially_deferred_set(GS),
1568 (is_b_global_constant(GS,_Nr,Cst) -> true),
1569 format(' ~w {~w,...} ',[GS, Cst]),
1570 (fixed_deferred_set_size(GS,RCard)
1571 -> format('(fixed card ~w) ',[RCard])
1572 ; inferred_maximum_global_set_cardinality(GS,MaxCard)
1573 -> format('(max card ~w) ',[MaxCard])),
1574 fail.
1575 portray_global_sets :-
1576 (deferred_sets_precompiled -> Comp=true ; Comp=false),
1577 format('~nDEFERRED SETS (precompiled=~w):~n ',[Comp]),
1578 b_global_deferred_set(GS),
1579 format(' ~w ',[GS]),
1580 (fixed_deferred_set_size(GS,RCard)
1581 -> format('(fixed card ~w) ',[RCard])
1582 ; inferred_maximum_global_set_cardinality(GS,MaxCard)
1583 -> format('(max card ~w) ',[MaxCard])),
1584 fail.
1585 portray_global_sets :- nl.