1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5
6 :- module(b_compiler,[b_compile/6, b_optimize/6, b_optimize_closure/3]).
7
8 :- use_module(library(lists)).
9
10 :- use_module(self_check).
11 :- use_module(bsyntaxtree).
12 :- use_module(error_manager).
13 :- use_module(debug,[debug_format/3]).
14 :- use_module(btypechecker,[fasttype/2]).
15 :- use_module(bmachine,[b_get_machine_operation_for_animation/6]).
16 :- use_module(b_interpreter).
17 :- use_module(custom_explicit_sets).
18 :- use_module(kernel_waitflags,[add_error_wf/5, add_internal_error_wf/5]).
19 %:- use_module(bmachine,[b_operation_reads_output_variables/3]).
20 :- use_module(probsrc(performance_messages),[performance_monitoring_on/0,perfmessage/3]).
21
22 :- use_module(module_information,[module_info/2]).
23 :- module_info(group,interpreter).
24 :- module_info(description,'This module compiles set comprehensions into closures; making them independent of the state of the B machine.').
25
26 /* compile boolean expression into a closure where the local state and the global
27 state has been incorporated, but any parameter is left in the closure */
28
29 :- public test_bexpr/3, test_bexpr2/3.
30 test_bexpr(Expr,[bind(cc,int(1)),bind(nn,int(2))], [bind(db,[(int(1),int(2))])]) :-
31 fasttype( +conjunct( +conjunct( +member( global('Name')<<identifier(nn), +identifier('Name')),
32 +member( global('Code')<<identifier(cc), +identifier('Code'))),
33 +not_member( global('Name')<<identifier(nn),
34 +domain(set(couple(global('Name'),global('Code')))<<identifier(db)))), Expr).
35
36 test_bexpr2(Expr,[],[]) :-
37 fasttype( +implication( +equal( set(couple(integer,any))<<identifier(ss), +empty_sequence),
38 +equal( set(couple(integer,any))<<identifier(res), +empty_set)), Expr).
39
40
41
42 b_optimize_closure(closure(P,T,Body),Res,WF) :-
43 b_optimize(Body,P,[],[],CBody,WF),!,
44 Res=closure(P,T,CBody).
45 b_optimize_closure(C,C,_WF).
46
47
48 % difference with b_compile: the states LS, S will not be thrown away by the interpreter
49 % thus: we do not have to compile all accesses, in particular lazy lookups !
50 %b_optimize(TExpr,Parameters,_LS,_S,NTExpr,_WF) :- TExpr=b(_,_,Infos), member(already_optimized,Infos),
51 % !, NTExpr=TExpr.
52 b_optimize(TExpr,Parameters,LS,S,NTExpr,WF) :- %print('OPTIMIZE: '),translate:print_bexpr(TExpr),nl, trace,
53 append(LS,[bind('$optimize_do_not_force_lazy_lookups',pred_true)],NewLS),
54 b_compile(TExpr,Parameters,NewLS,S,NTExpr,WF).
55 %bsyntaxtree:add_texpr_info_if_new(NTExpr,already_optimized,ResTExpr).
56
57 b_compile(TExpr,Parameters,NewLS,S,NTExpr) :-
58 ? b_compile(TExpr,Parameters,NewLS,S,NTExpr,no_wf_available). % for unit tests
59
60 :- assert_must_succeed(( b_compiler:test_bexpr(E,L,S),
61 b_compiler:b_compile(E,[nn],L,S,_R) )).
62 :- assert_must_succeed(( b_compiler:test_bexpr2(E,L,S),
63 b_compiler:b_compile(E,[ss,res],L,S,_R) )).
64 :- assert_must_succeed(( b_compiler:b_compile(b(greater(b(value(int(2)),integer,[]),
65 b(value(int(1)),integer,[])),pred,[]),[],[],[],Res),
66 check_eq(Res,b(truth,pred,_)) )).
67 :- assert_must_succeed(( b_compiler:b_compile(b(greater(b(value(int(2)),integer,[]),
68 b(value(int(3)),integer,[])),pred,[]),[],[],[],Res),
69 check_eq(Res,b(falsity,pred,_)) )).
70 :- assert_must_succeed(( E = b(greater(b(value(int(2)),integer,[]),
71 b(value(int(_)),integer,[])),pred,[]),
72 b_compiler:b_compile(E,[],[],[],Res),
73 check_eq(Res,E) )).
74 :- assert_must_succeed(( E = b(greater(b(value(int(2)),integer,[]),
75 b(value(_),integer,[])),pred,[]),
76 b_compiler:b_compile(E,[],[],[],Res),
77 check_eq(Res,E) )).
78 :- assert_must_succeed(( E = b(greater(b(value(int(2)),integer,[]),
79 b(identifier(x),integer,[])),pred,[]),
80 b_compiler:b_compile(E,[],[bind(x,int(1))],[],Res),
81 check_eq(Res,b(truth,pred,_)) )).
82 :- assert_must_succeed(( E = b(greater(b(value(int(2)),integer,[]),
83 b(identifier(x),integer,[])),pred,[]),
84 b_compiler:b_compile(E,[],[bind(x,int(3))],[],Res),
85 check_eq(Res,b(falsity,pred,_)) )).
86
87 :- assert_must_succeed(( % !x.(x/y>0 => 2>1) is not simplified to btrue, as x/y may be ill-defined
88 X = b(identifier(x),integer,[]), Y = b(identifier(y),integer,[]),
89 Div = b(div(X,Y),integer,[contains_wd_condition]),
90 A = b(greater(Div,b(value(int(0)),integer,[])),pred,[contains_wd_condition]),
91 B = b(greater(b(value(int(2)),integer,[]),b(value(int(1)),integer,[])),pred,[]),
92 E = b(forall([X],A,B),pred,[used_ids([y])]),
93 b_compiler:b_compile(E,[],[bind(y,int(0))],[],Res),
94 Res = b(forall(_,_,_),pred,_) )).
95 :- assert_must_succeed(( % !x.(x+y>0 => 2>1) is simplified to btrue
96 X = b(identifier(x),integer,[]), Y = b(identifier(y),integer,[]),
97 A = b(greater(b(add(X,Y),integer,[]),b(value(int(0)),integer,[])),pred,[]),
98 B = b(greater(b(value(int(2)),integer,[]),b(value(int(1)),integer,[])),pred,[]),
99 E = b(forall([X],A,B),pred,[used_ids([y])]),
100 b_compiler:b_compile(E,[],[bind(y,int(0))],[],Res),
101 check_eq(Res,b(truth,pred,_)) )).
102
103 %:- assert_pre(b_compiler:b_compile_boolean_expression(E,Parameters,LS,S,_),
104 % (type_check(E,boolean_expression),type_check(Parameters,list(variable_id)),
105 % type_check(LS,store),type_check(S,store))).
106 %:- assert_post(b_compiler:b_compile_boolean_expression(_,_,_,_,E), type_check(E,boolean_expression)).
107
108 /* probably not worthwhile:
109 b_compile(TExpr,Parameters,LS,S,NTExpr) :- get_texpr_info(TExpr,Info),
110 (memberchk(compiled(Parameters),Info) -> NTExpr = TExpr ,print(already_compiled(Parameters)),nl, translate:print_bexpr(TExpr),nl
111 ; b_compile0(TExpr,Parameters,LS,S,b(E,T,I)), translate:print(compiling(Parameters)),nl, translate:print_bexpr(TExpr),nl,
112 NTExpr = b(E,T,[compiled(Parameters)|I])).
113 */
114 :- use_module(closures,[get_recursive_identifier_of_closure_body/2]).
115 b_compile(TExpr,Parameters,LS,S,NTExpr,WF) :-
116 check_is_id_list(Parameters,Parameters0),
117 (get_recursive_identifier_of_closure_body(TExpr,TRID),
118 def_get_texpr_id(TRID,RID), nonmember(bind(RID,_),LS)
119 -> Parameters1=[RID|Parameters0] % add recursive ID virtually to parameters to avoid error messages
120 ; Parameters1=Parameters0),
121 % print('compile : '),translate:print_bexpr(TExpr),nl, statistics(runtime,[Start,_]),%%
122 sort(Parameters1,Parameters2),
123 ? if(b_compile1(TExpr,Parameters2,LS,S,NTExpr0,eval,FullyKnown,WF),
124 (FullyKnown=true
125 -> copy_pos_infos(TExpr,NTExpr0,NTExpr)
126 % ensure position info is not deleted if full expression compiled away, see PROB-412 (test 1677)
127 ; NTExpr=NTExpr0),
128 (add_internal_error_wf(b_compiler,'Compilation failed: ',TExpr,TExpr,WF),
129 %b_compile1(TExpr,Parameters1,LS,S,NTExpr0,eval,_FullyKnown,WF),
130 NTExpr = TExpr)
131 ).
132 %, bsyntaxtree:check_ast(NTExpr).
133 %, check_infos(TExpr,NTExpr).
134 %, print('compiled: '), translate:print_bexpr(NTExpr), print(' '),statistics(runtime,[Stop,_]), T is Stop-Start, print(T), print(' ms '),nl, bsyntaxtree:check_ast(NTExpr). % , print(NTExpr),nl. check_ast
135
136 /*
137 check_infos(Old,New) :- bsyntaxtree:get_texpr_info(Old,IO),
138 bsyntaxtree:get_texpr_info(New,IN),
139 member(X,IO), \+ member(X,IN),
140 bsyntaxtree:important_info(X),
141 print(check_infos(Old,New)),nl,
142 print('Not copied: '), print(X),fail.
143 check_infos(_,_). */
144
145 :- use_module(bsyntaxtree,[always_well_defined/1, always_well_defined_or_wd_reorderings_allowed/1]).
146 :- use_module(translate,[translate_bexpression_with_limit/2]).
147 %:- use_module(hit_profiler,[add_profile_hit/1]).
148
149 % Eval=eval means the expression will be needed in a successful branch and we can pre-compute more aggressively
150 % Eval=false means the expression may not be needed (e.g., in a disjunction) and only perform efficient precomputations
151 b_compile1(TExpr,Parameters,LS,S,ResultTExpr,Eval,FullyKnown1,WF) :-
152 TExpr = b(Expr,Type,Infos),
153 NTExpr = b(NewUntypedExpr,Type,NewInfos),
154 %remove_bt(TExpr,Expr,NewUntypedExpr,NTExpr), % remove top-level Type Information
155 %hit_profiler:add_profile_hit(Expr),
156 %functor(Expr,E1,N1), %print(start_compile(E1/N1,Eval,FullyKnown1)),nl,
157 ? b_compile1_infos(Expr,Type,Infos,Parameters,LS,S,NewUntypedExpr,NewInfos,Eval,FullyKnown,WF),
158 %functor(NewUntypedExpr,E2,N2),
159 %format(' compiled ~w/~w -> ~w/~w : ',[E1,N1,E2,N2]),translate:print_bexpr_or_subst(NTExpr),nl,
160 %format(' fully=~w, eval=~w~n',[FullyKnown,Eval]),
161 (NTExpr = b(value(_),_,_)
162 -> FullyKnown1=FullyKnown, ResultTExpr=NTExpr
163 ; evaluate_this(FullyKnown,Eval,NewUntypedExpr,Type,NewInfos)
164 -> % print('eval : '),translate:print_bexpr(NTExpr),nl, %
165 (nonvar(NewUntypedExpr),
166 % if( would be more prudent !?, also: we used to call b_compute_expression_nowf
167 ? b_interpreter:b_compute_expression(NTExpr,LS,S,ResultValue,WF)
168 -> %print(result(ResultValue)),nl,
169 %remove_bt(TExpr,Expr,value(ResultValue),ResultTExpr)
170 get_texpr_type(TExpr,TT),ResultTExpr = b(value(ResultValue),TT,[]),
171 FullyKnown1 = true
172 %, print(compiled_value(ResultTExpr)),nl
173 ; add_internal_error_wf(b_compiler,'Undefined value marked for evaluation:',NTExpr,Infos,WF),
174 %trace, b_interpreter:b_compute_expression(NTExpr,LS,S,ResultValue,WF),
175 ResultTExpr=NTExpr, FullyKnown1=false
176 )
177 ; % ((FullyKnown=true, NTExpr\=b(value(_),_,_)) -> format('not eval: ~w (~w)~n',[NTExpr,Eval]) ; true),
178 ResultTExpr=NTExpr, FullyKnown1=false
179 ).
180
181
182 :- use_module(library(ordsets),[ord_member/2, ord_union/3]).
183 :- use_module(bsyntaxtree,[create_exists_or_let_predicate/3]).
184 :- use_module(tools_lists,[delete_first/3]).
185 add_parameters(SortedIds,NewIds,NewSortedIds) :-
186 sort(NewIds,SNew),
187 ord_union(SortedIds,SNew,NewSortedIds).
188
189 b_compile1_infos(exists(ExistsPara,Pred),_,OldInfos,Parameters,LS,S,NExpr,NewInfos,Eval,FullyKnown,WF) :- !,
190 FullyKnown=false, % predicates never automatically evaluated in b_compile1
191 get_texpr_ids(ExistsPara,AtomicIds),
192 add_parameters(Parameters,AtomicIds,NParameters),
193 ? b_compile1(Pred,NParameters,LS,S,NPred,Eval,_FullyKnown1,WF),
194 (is_falsity(NPred) -> NExpr = falsity, NewInfos = OldInfos
195 ; is_truth(NPred) -> NExpr = truth, NewInfos = OldInfos
196 %; Pred==NPred, write(unchanged(Parameters)),nl, member(used_ids(Old),OldInfos), print(used(Old)),nl,nl,fail
197 ; create_exists_or_let_predicate(ExistsPara,NPred,b(NExpr,pred,NI)),
198 %print('COMPILED EXISTS: '), translate:print_bexpr(b(NExpr,pred,NI)),nl,
199 (delete_first(OldInfos,used_ids(_),I1),
200 ? member(used_ids(NewUsedIds),NI) -> NewInfos = [used_ids(NewUsedIds)|I1]
201 ; %nl,print(missing_used_ids(OldInfos,NI)),nl, % can happen when we construt a let_predicate above
202 update_infos(NExpr,OldInfos,Parameters,NewInfos))
203 ).
204 b_compile1_infos(identifier(Id),Type,OldInfos,Parameters,LS,S,NExpr,NewInfos,_Eval,FullyKnown,WF) :- !,
205 ( ord_member(Id,Parameters) ->
206 NExpr = identifier(Id), FullyKnown=false, NewInfos = OldInfos
207 ; Id=op(_) ->
208 NExpr = identifier(Id), FullyKnown=false, NewInfos = OldInfos
209 ; b_interpreter:lookup_value_in_store_and_global_sets_wf(Id,Type,LS,S,Value,OldInfos,WF) ->
210 NExpr = value(Value), (known_value(Value) -> FullyKnown=true ; FullyKnown=false),
211 NewInfos = [was_identifier(Id)|OldInfos]
212 ; add_internal_error_wf(b_compiler,'Compilation of identifier failed: ',Id,OldInfos,WF),
213 NExpr = identifier(Id), FullyKnown=false, NewInfos = OldInfos
214 ).
215 b_compile1_infos(Expr,_,OldInfos,_Parameters,_LS,_S,NewUntypedExpr,NewInfos,_Eval,FullyKnown,_WF) :-
216 ? b_ast_cleanup:is_integer_set(Expr,_Set),!,
217 NewUntypedExpr=Expr, NewInfos=OldInfos,FullyKnown=true.
218 b_compile1_infos(operation_call_in_expr(Operation,OpCallParas),_Type,OldInfos,Parameters,LS,S,
219 Compiled,NewInfos,Eval,FullyKnown,WF) :- !,
220 def_get_texpr_id(Operation,op(OperationName)),
221 FullyKnown = false,
222 b_compile_l(OpCallParas,Parameters,LS,S,OpCallParaValues,Eval,_,WF),
223 (b_get_operation_normalized_read_write_info(OperationName,ReadVars,Modified) -> true
224 ; member(reads(ReadVars),OldInfos), member(modifies(Modified),OldInfos)
225 -> add_message(b_compiler,'Unregistered operation in expression: ',OperationName)
226 % should not happen; but proceed with the locally stored reads/writes info
227 ; add_error_wf(b_compiler,'Cannot obtain read/write info for operation:',OperationName,OldInfos,WF),
228 debug_println(19,old_infos(OldInfos)),
229 ReadVars=[], Modified=[]
230 ),
231 %exclude(operation_identifier,Read,ReadVars), % Read used to contain operations used via operation_call_in_expr; TO DO: check if this is ok in other places of source code of ProB; see test 1957
232 (Modified=[] -> true
233 ; add_error_wf(b_compiler,'Calling operation that modifies state in expression:',OperationName,OldInfos,WF)),
234 % print(compile_call_op(OperationName,ReadVars,Modified,OpCallParaValues)),nl,
235 (ReadVars=[]
236 -> Compiled = operation_call_in_expr(Operation,OpCallParaValues),
237 NewInfos = OldInfos
238 ; maplist(create_value_for_read_variable(LS,S,WF),ReadVars,TRead,TValues),
239 safe_create_texpr(let_expression_global(TRead,TValues,
240 b(operation_call_in_expr(Operation,OpCallParaValues),any,OldInfos)),any,[generated_by_b_compiler],New),
241 New = b(Compiled,_,NewInfos)
242 %NewInfos = [generated_by_b_compiler],
243 %Compiled = let_expression_global(TRead,TValues,
244 % b(operation_call_in_expr(Operation,OpCallParaValues),any,OldInfos))
245 ).
246 b_compile1_infos(kodkod(Id,Identifiers),_,OldInfos,Parameters,LS,S,NExpr,NewInfos,_Eval,FullyKnown,WF) :- !,
247 FullyKnown=false, NewInfos=OldInfos,
248 exclude(is_parameter(Parameters),Identifiers,IdsToCompile),
249 (IdsToCompile=[]
250 -> NExpr = kodkod(Id,Identifiers)
251 ; maplist(precompile_id(LS,S,WF),IdsToCompile,Values),
252 % as we cannot inspect kodkod problem: wrap it into a let with the values stored:
253 NExpr = let_predicate(IdsToCompile,Values,b(kodkod(Id,Identifiers),pred,OldInfos))
254 ).
255 b_compile1_infos(Expr,_,OldInfos,Parameters,LS,S,NewUntypedExpr,NewInfos,Eval,FullyKnown,WF) :-
256 ? b_compile2(Expr,Parameters,LS,S,NewUntypedExpr,Eval,FullyKnown,WF),
257 update_infos(NewUntypedExpr,OldInfos,Parameters,NewInfos).
258
259
260 is_parameter(Parameters,b(identifier(Id),_,_)) :- ord_member(Id,Parameters).
261
262 precompile_id(LS,S,WF,b(identifier(Id),Type,Info),b(value(Value),Type,[])) :-
263 b_interpreter:lookup_value_in_store_and_global_sets_wf(Id,Type,LS,S,Value,Info,WF).
264 % was_identifier is aded in b_compile1_infos
265
266 :- use_module(bmachine,[b_get_operation_normalized_read_write_info/3]).
267
268 %operation_identifier(op(_)).
269 create_value_for_read_variable(LS,S,WF,Variable,TVariable,TValue) :-
270 b_interpreter:lookup_value_in_store_and_global_sets_wf(Variable,_Type,LS,S,Value,unknown,WF),!,
271 % TO DO: try and find type?
272 TVariable = b(identifier(Variable),any,[]),
273 TValue = b(value(Value),any,[]).
274 create_value_for_read_variable(_LS,_S,WF,Variable,TVariable,b(value(term(undefined)),any,[])) :-
275 TVariable = b(identifier(Variable),any,[]),
276 add_internal_error_wf(b_compiler,'Cannot find variable (read) while compiling operation:',Variable,unknown,WF),
277 fail.
278
279 :- use_module(library(ordsets)).
280 update_infos(forall(EParas,LHS,RHS),Infos,Parameters,NewInfos) :-
281 % forall also has used_ids field as it may call exists in negative context
282 conjunct_predicates([LHS,RHS],Cond),
283 update_infos_aux(EParas,Cond,Infos,Parameters,NewInfos),!.
284 update_infos(exists(EParas,Cond),Infos,Parameters,NewInfos) :- % we create_exists_or_let_predicate above, but other transformations may generate an exists below:
285 update_infos_aux(EParas,Cond,Infos,Parameters,NewInfos),!.
286 update_infos(BOP,Infos,_,NewInfos) :- bsyntaxtree:syntaxelement(BOP, [A,B],[], [], [], _),
287 wd_and_efficient(BOP), % should not generate WD errors itself
288 ? (select(contains_wd_condition,Infos,NewInfos) % there is a WD condition attached
289 -> fast_check_wd(A),
290 fast_check_wd(B)
291 ),
292 %print(removing_wd_condition(BOP)),nl,
293 !.
294 update_infos(_,I,_,I).
295
296 update_infos_aux(EParas,Cond,Infos,Parameters,NewInfos) :-
297 select_used_ids(UsedIds,Infos,I1,EParas,Cond),
298 UsedIds \= [],!,
299 % remove those used identifiers which will be compiled into the predicate
300 sort(Parameters,SParas),
301 ord_intersection(UsedIds,SParas,NewUsedIds),
302 %print(update(Parameters,UsedIds,I1,new(NewUsedIds))),nl,
303 NewInfos = [used_ids(NewUsedIds)|I1].
304
305 :- use_module(bsyntaxtree,[find_identifier_uses/3]).
306 ?select_used_ids(UsedIds,Infos,I1,_,_) :- select(used_ids(UsedIds),Infos,I1),!.
307 % check_used_ids_info(Parameters,Condition,UsedIds,b_compiler)
308 select_used_ids(UsedIds,Infos,Infos,_Parameters,Condition) :-
309 %add_error(bcompiler,'Expected information of used identifiers in exists operation information : ',Parameters:Infos), %% missing info can happen due to simplifcation rules below !
310 find_identifier_uses(Condition, [], UsedIds). % ,print(used(UsedIds,in_exist(Parameters))),nl.
311 % TO DO: avoid re-computing used-ids; we should refactor b_compile2 to return new Info field
312
313
314 evaluate_this(true,Eval,NewUntypedExpr,Type,NewInfos) :- !,
315 evaluate_this_if_fully_known(Eval,NewUntypedExpr,Type,NewInfos).
316 evaluate_this(_FullyKnown,_,NewUntypedExpr,_,_) :-
317 eval_even_if_not_fully_known(NewUntypedExpr).
318
319 eval_even_if_not_fully_known(comprehension_set(A,B)) :-
320 (is_falsity(B) -> true ; b_ast_cleanup:is_integer_set(comprehension_set(A,B),_)).
321 % TODO: detect intervals?
322 eval_even_if_not_fully_known(general_product(_A,B,_C)) :- is_falsity(B).
323 eval_even_if_not_fully_known(general_sum(_A,B,_C)) :- is_falsity(B).
324
325 evaluate_this_if_fully_known(eval,X,Type,Info) :- !, worth_it_type(Type,X,Info).
326 evaluate_this_if_fully_known(_,function(A,B),Type,Info) :- !,
327 A=b(value(VA),_,_), nonvar(VA), VA=avl_set(_),
328 B=b(value(_),_,_),
329 worth_it_type(Type,function(A,B),Info). % will check well-definedness
330 evaluate_this_if_fully_known(_,X,_Type,_Info) :- wd_and_efficient(X).
331
332
333 % things which are very quick to compute
334 wd_and_efficient(sequence_extension(_)) :- !.
335 wd_and_efficient(set_extension(_)) :- !.
336 wd_and_efficient(integer_set(_)) :- !. % will be converted into value(global_set(_))
337 %% wd_and_efficient(value(_)) :- !. % is already computed
338 % the following will reduce the size of the representation; usually a good thing;
339 % we assume only avl_sets apprear here; inner set comprehensions are never computed into symbolic form by b_compile (see known_value below):
340 %wd_and_efficient(identity(_)) :- !.
341 wd_and_efficient(range(_)) :- !.
342 wd_and_efficient(domain(_)) :- !.
343 wd_and_efficient(domain_restriction(_,_)) :- !.
344 wd_and_efficient(domain_subtraction(_,_)) :- !.
345 wd_and_efficient(range_restriction(_,_)) :- !.
346 wd_and_efficient(range_subtraction(_,_)) :- !.
347 wd_and_efficient(intersection(_,_)) :- !.
348 wd_and_efficient(set_subtraction(_,_)) :- !.
349 wd_and_efficient(image(_,_)) :- !.
350 wd_and_efficient(reverse(_)) :- !. % added for rgen_rgen_Worst_Case_Stopping_distance_NCT_trm13
351 % reverse has n.log(n) complexity, but is always wd and can be beneficial
352 wd_and_efficient(union(A,B)) :- finite_set(A), finite_set(B), !. % has complexity n
353 % usually the union of two avl_sets will be smaller than keeping them separate, what about intervals?
354 wd_and_efficient(interval(_,_)) :- !. % ditto
355 wd_and_efficient(card(S)) :- !, % added for rgen_rgen_Worst_Case_Stopping_distance_NCT_trm13
356 (finite_set(S) -> true % is wd for finite set; has currently linear complexity but reduces size of closure
357 ; is_interval(S) -> true). % card is simple to compute
358 wd_and_efficient(min(S)) :- !, % logarithmic for avl_set, see test 1338
359 finite_non_empty_set(S).
360 wd_and_efficient(max(S)) :- !, % logarithmic for avl_set
361 finite_non_empty_set(S).
362 wd_and_efficient(string_set) :- !.
363 % some other efficient operators:
364 % external_function_call CHOOSE (test 1338) ?
365 % first, last, ... need to ensure we have sequence
366 wd_and_efficient(X) :- worth_it_int(X),!.
367 wd_and_efficient(X) :- worth_it_real(X),!.
368 wd_and_efficient(X) :- worth_it_other(X).
369
370 is_interval(b(value(V),set(_),_)) :- nonvar(V), V=closure(P,T,B),
371 is_fixed_interval(P,T,B,_,_).
372
373 finite_set(b(value(V),ST,_)) :- is_set_type(ST,_), nonvar(V), finite_set_aux(V).
374 finite_set_aux([]).
375 finite_set_aux(avl_set(_)).
376 finite_non_empty_set(b(value(V),ST,_)) :- is_set_type(ST,_), nonvar(V), V=avl_set(_).
377
378 fast_check_wd(b(E,_,Infos)) :-
379 (nonmember(contains_wd_condition,Infos) -> true
380 ; nonvar(E), E=value(_)).
381
382 check_wd(NTExpr) :- bsyntaxtree:always_well_defined(NTExpr). % ,print(wd(NTExpr)),nl.
383 %(bsyntaxtree:always_well_defined(NTExpr) -> true ; print(not_guaranteed_wd(NTExpr)),nl).
384
385 % (worth_it_type(Type,X,Info) -> true ; X=value(_) -> true ; print(not_evaluating(X)),nl,fail).
386 worth_it_type(integer,X,Info) :- worth_it_int_wd(X),!, check_wd(b(X,integer,Info)).
387 worth_it_type(real,X,Info) :- worth_it_real_wd(X),!, check_wd(b(X,real,Info)).
388 worth_it_type(T,function(A,B),Info) :- !,
389 (check_wd(b(function(A,B),T,Info)) -> true
390 ; fail). %print('not_precompiling_function '),translate:print_bexpr(A), print(' @ '), translate:print_bexpr(B),nl,fail).
391 worth_it_type(integer,X,_) :- worth_it_int(X),!.
392 worth_it_type(real,X,_) :- worth_it_real(X),!.
393 worth_it_type(T,X,Info) :- worth_it_wd(X),!, check_wd(b(X,T,Info)).
394 worth_it_type(set(_),X,_) :- worth_it_set(X),!.
395 worth_it_type(seq(_),X,_) :- worth_it_set(X),!.
396 worth_it_type(_,X,_) :- worth_it_other(X).
397
398 % TO DO: we should use the predicate has_wd_condition from b_ast_cleanup
399
400 % integer operations that could generate WD-errors
401 worth_it_int_wd(div(_,_)).
402 worth_it_int_wd(max(_)).
403 worth_it_int_wd(min(_)).
404 worth_it_int_wd(mod(_,_)).
405 worth_it_int_wd(power_of(_,_)).
406 worth_it_int_wd(card(_)). % has WD condition !!
407 worth_it_int_wd(size(_)).
408
409 % real operations that could generate WD-errors
410 worth_it_real_wd(div_real(_,_)).
411 worth_it_real_wd(max_real(_)).
412 worth_it_real_wd(min_real(_)).
413 worth_it_real_wd(power_of_real(_,_)).
414
415 % other operations that could generate WD-errors
416 worth_it_wd(first(_)).
417 worth_it_wd(last(_)).
418 worth_it_wd(tail(_)).
419 worth_it_wd(front(_)).
420 worth_it_wd(restrict_front(_,_)).
421 worth_it_wd(restrict_tail(_,_)).
422 worth_it_wd(rel_iterate(_,_)). %% could be expensive
423 worth_it_wd(general_intersection(_)).
424 worth_it_wd(general_concat(_)).
425 worth_it_wd(insert_front(_,_)).
426 worth_it_wd(insert_tail(_,_)).
427 worth_it_wd(mu(_)).
428 worth_it_wd(iteration(_,_)). % iterate(R,N) is not well-defined for N<0
429 worth_it_wd(rev(_)). % reverse of sequence: argument must be a sequence
430 worth_it_wd(concat(_,_)). % ditto: both arguments must be sequences
431
432 % to do: check other operators that could be not well-defined !
433
434 % integer operations that are always wd
435 worth_it_int(unary_minus(_)).
436 worth_it_int(add(_,_)).
437 worth_it_int(minus(_,_)).
438 worth_it_int(multiplication(_,_)).
439 worth_it_int(max_int).
440 worth_it_int(min_int).
441 worth_it_int(convert_int_floor(_)).
442 worth_it_int(convert_int_ceiling(_)).
443
444 % real operations that are always wd
445 worth_it_real(unary_minus_real(_)). % this results in no change of precision?!
446 worth_it_real(add_real(_,_)) :- precompile_real_operators.
447 worth_it_real(minus_real(_,_)) :- precompile_real_operators.
448 worth_it_real(multiplication_real(_,_)) :- precompile_real_operators.
449 worth_it_real(convert_real(_)) :- precompile_real_operators.
450
451 % as we pre-compile using ProB's interpreter/kernel, this may not be ok if we use another semantics
452 % e.g., Z3 represents numbers as fractions and polynomial roots;
453 % performing the operation in floats may result in imprecision, see test 2319
454 precompile_real_operators :- preferences:preference(solver_for_reals,Z), Z \= z3_solver.
455
456 %worth_it_set(empty_set). % treated below
457 %worth_it_set(empty_sequence). % treated below
458 %worth_it_set(closure(_)). % this is closure1; it is currently always kept symbolic and can be counterproductive to compile; e.g., card(closure1(%x.(x : 1 .. 200|x + 1)))
459 %% ?? need to be more careful here; can be expensive --> need to keep track which parts need definitely to be evaluated
460 worth_it_set(integer_set(_)). % will be converted into value(global_set(_))
461 %worth_it_set(comprehension_set(A,B)) :- % due to predicate B this will never be fully known
462 % (is_falsity(B) -> true ; b_ast_cleanup:is_integer_set(comprehension_set(A,B),_)).
463 worth_it_set(interval(_,_)).
464 worth_it_set(reflexive_closure(A)) :- \+ symbolic_value(A).
465 worth_it_set(reverse(_)). % function inverse
466 worth_it_set(domain(_)). worth_it_set(range(_)).
467 worth_it_set(union(_,_)). worth_it_set(intersection(_,_)). worth_it_set(set_subtraction(_,_)).
468 worth_it_set(image(_,B)) :- \+ symbolic_value(B).
469 worth_it_set(composition(_,_)).
470 worth_it_set(domain_restriction(_,_)). worth_it_set(domain_subtraction(_,_)).
471 worth_it_set(range_restriction(_,_)). worth_it_set(range_subtraction(_,_)).
472 worth_it_set(direct_product(A,B)) :- \+ symbolic_value(A), \+ symbolic_value(B).
473 worth_it_set(parallel_product(A,B)) :- \+ symbolic_value(A), \+ symbolic_value(B).
474 worth_it_set(set_extension([H|_])) :- \+ symbolic_value(H). % otherwise we may get an enumeration warning
475 worth_it_set(sequence_extension([H|_])) :- \+ symbolic_value(H). % ditto, TODO: check tail unless expensive
476 worth_it_set(seq(_)). % will be kept symbolic anyway
477 worth_it_set(seq1(_)). % will be kept symbolic anyway; relevant for test 1731
478 % f=%x.(x:iseq(struct(a:seq1(NATURAL),b:BOOL))|x) & f([rec(a:[222],b:TRUE)])=[rec(a:[222],b:xx)] & xx=TRUE
479 % however: value can be put into a set-extension!
480 worth_it_set(iseq(_)). % will be kept symbolic anyway
481 worth_it_set(iseq1(_)). % will be kept symbolic anyway
482 worth_it_set(perm(_)). % will be kept symbolic anyway
483 worth_it_set(pow_subset(_)). % will be kept symbolic anyway
484 worth_it_set(pow1_subset(_)). % will be kept symbolic anyway
485 worth_it_set(fin_subset(_)). % will be kept symbolic anyway
486 worth_it_set(fin1_subset(_)). % will be kept symbolic anyway
487 worth_it_set(general_union(X)) :- \+ symbolic_value(X). % otherwise we can get enumeration warnings
488 worth_it_set(identity(_)).
489 worth_it_set(first_of_pair(_)). % can also produce set
490 worth_it_set(second_of_pair(_)). % can also produce set
491 worth_it_set(cartesian_product(_,_)). % will usually be kept symbolic
492 worth_it_set(string_set). % ensure we have values inside compiled closures, e.g., for custom_explicit_set card computations
493 worth_it_set(bool_set).
494
495 symbolic_value(b(value(Val),_,_)) :- nonvar(Val), symbolic_val_aux(Val).
496 symbolic_val_aux(closure(P,T,B)) :- \+ is_fixed_interval(P,T,B,_,_).
497 symbolic_val_aux(global_set(_)).
498
499 :- use_module(external_functions,[not_declarative/1,external_fun_has_wd_condition/1,
500 expects_unevaluated_args/1]).
501 worth_it_other(boolean_true).
502 worth_it_other(boolean_false).
503 worth_it_other(real(_)).
504 worth_it_other(string(_)).
505 worth_it_other(first_of_pair(_)).
506 worth_it_other(second_of_pair(_)).
507 worth_it_other(couple(_,_)).
508 worth_it_other(record_field(_,_)).
509 worth_it_other(external_function_call(FunName,_)) :-
510 \+ not_declarative(FunName),
511 \+ external_fun_has_wd_condition(FunName). %print(compile(FunName)),nl.
512 % CHOOSE for finite_non_empty_set ?
513 worth_it_other(rec(_)).
514 worth_it_other(struct(_)).
515 %worth_it_other(value(_)). % does not have to be evaluted; already a value
516
517 /*
518 % To do: distinguish which parts definitely need to be evaluated
519 %dont_eval_subexpressions(member). % special membership code can be used
520 %dont_eval_subexpressions(not_member). % special membership code can be used
521 dont_eval_subexpressions(disjunct(_,_)). % it may not be necessary to eval RHS
522 dont_eval_subexpressions(implication(_,_)). % it may not be necessary to eval RHS
523 */
524
525 :- use_module(bsyntaxtree, [get_negated_operator_expr/2]).
526 :- use_module(kernel_objects,[equal_object/3]).
527 :- use_module(kernel_mappings,[binary_boolean_operator/3]).
528 :- use_module(kernel_tools,[filter_cannot_match/4, get_template_for_filter_cannot_match/2]).
529 b_compile2(Exp,_Parameters,_LS,_S,NExpr,_Eval,FullyKnown,WF) :- var(Exp), !,
530 add_internal_error_wf(b_compiler,'Variable Expression: ',Exp,unknown,WF),
531 NExpr=Exp, FullyKnown=false.
532 b_compile2(truth,_,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !, NExpr=truth, FullyKnown=false. % predicates never fully known
533 b_compile2(falsity,_,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !, NExpr=falsity, FullyKnown=false. % predicates never fully known
534 b_compile2(empty_set,_,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !, NExpr=value([]), FullyKnown=true.
535 b_compile2(empty_sequence,_,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !, NExpr=value([]), FullyKnown=true.
536 b_compile2(boolean_false,_,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !, NExpr=value(pred_false), FullyKnown=true.
537 b_compile2(boolean_true,_,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !, NExpr=value(pred_true), FullyKnown=true.
538 b_compile2(value(Val),_Parameters,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !,
539 NExpr=value(Val),
540 (known_value(Val) -> % ground(Val) -> known_value ?
541 FullyKnown=true ; FullyKnown=false).
542 b_compile2(integer(Val),_Parameters,_LS,_S,NExpr,_Eval,FullyKnown,_WF) :- !,
543 NExpr=value(int(Val)), (number(Val) -> FullyKnown=true ; FullyKnown=false).
544 b_compile2(lazy_lookup_pred(Id),Parameters,LS,S,NExpr,_Eval,FullyKnown,WF) :- !,
545 ( ord_member(Id,Parameters) -> %print(lazy_lookup_pred_id_as_parameter(Id,Parameters)),nl,
546 NExpr = lazy_lookup_pred(Id), FullyKnown=false
547 ; compute_lazy_lookup(Id,lazy_lookup_pred(Id),LS,S,NExpr,FullyKnown,WF)
548 ).
549 b_compile2(lazy_lookup_expr(Id),Parameters,LS,S,NExpr,_Eval,FullyKnown,WF) :- !,
550 ( ord_member(Id,Parameters) -> %print(lazy_lookup_expr_id_as_parameter(Id,Parameters)),nl,
551 NExpr = lazy_lookup_expr(Id), FullyKnown=false
552 ; compute_lazy_lookup(Id,lazy_lookup_expr(Id),LS,S,NExpr,FullyKnown,WF)
553 ).
554
555 % treat a few common cases, more efficiently than syntaxtransformation
556 b_compile2(equal(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
557 FullyKnown=false, % predicates never evaluated in b_compile1
558 ? b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnownA,WF),
559 ? b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnownB,WF),
560 ( FullyKnownA=true, FullyKnownB=true,
561 NExprA = b(value(VA),_,_), NExprB = b(value(VB),_,_)
562 -> (equal_object(VA,VB,b_compile2_1) -> NExpr = truth ; NExpr = falsity)
563 ; generate_equality(NExprA,NExprB,NExpr)
564 ).
565 b_compile2(not_equal(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
566 FullyKnown=false, % predicates never evaluated in b_compile1
567 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnownA,WF),
568 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnownB,WF),
569 ( FullyKnownA=true, FullyKnownB=true,
570 NExprA = b(value(VA),_,_), NExprB = b(value(VB),_,_)
571 -> %print(computing_neq(VA,VB)),nl,
572 (kernel_objects:equal_object(VA,VB,b_compile2_2) -> NExpr = falsity ; NExpr = truth)
573 %, print(result(NExpr)),nl
574 ; NExpr = not_equal(NExprA,NExprB)
575 ).
576 b_compile2(member(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
577 FullyKnown=false, % predicates never evaluated in b_compile1
578 ? b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnownB,WF),
579 (NExprB = b(value(X),BT,BI)
580 -> (X==[], always_well_defined(A) -> NExpr = falsity
581 ? ; b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnownA,WF),
582 % check if we can decide membership (e.g., 1:{1})
583 ? (quick_test_membership1(NExprA,X,PRes)
584 -> convert_pred_res(PRes,NExpr)
585 % TO DO: maybe optimize x: {y|P(y)} --> P(x) ; by commenting in code below
586 % However, ensure test 273 succeeds and closure equality correctly detected (e.g., for BV16 = {bt|bt : BIT_VECTOR & bv_size(bt) = 16})
587 % ; (get_texpr_id(NExprA,IDA),
588 % get_comprehension_set(NExprB,IDB,Pred), get_texpr_info(NExprB,Info),
589 % print(rename(IDB,IDA,Info)),nl,
590 % bsyntaxtree:rename_bt(Pred,[rename(IDB,IDA)],PredA)) -> get_texpr_expr(PredA,NExpr)
591 ; custom_explicit_sets:singleton_set(X,El) % replace x:{El} -> x=El
592 -> get_texpr_type(NExprA,TA),
593 generate_equality_with_value(NExprA,FullyKnownA,El,FullyKnownB,TA,NExpr)
594 ; get_template_for_filter_cannot_match(NExprA,VA)
595 -> filter_cannot_match(X,VA,NewX,Filtered),
596 % (Filtered=false -> true ; print(filtered(NewX,VA,X)),nl),
597 (Filtered=false -> NExpr = member(NExprA,NExprB)
598 ; (NewX==[], always_well_defined(A)) -> NExpr = falsity
599 ; custom_explicit_sets:singleton_set(NewX,El)
600 -> get_texpr_type(NExprA,TA),
601 %nl,print(create_equal(NExprA,FullyKnownA,El,FullyKnownB,NExprB)),nl,nl,
602 generate_equality_with_value(NExprA,FullyKnownA,El,FullyKnownB,TA,NExpr)
603 ; NExpr = member(NExprA, b(value(NewX),BT,BI))
604 )
605 % end fo filtering
606 ; NExpr = member(NExprA,NExprB)
607 )
608 % , print('compile: '),print(NExpr),nl
609 )
610 ; NExpr = member(NExprA,NExprB),
611 b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF)
612 ).
613 % TO DO: also optimize things like: (ev1 |-> 0) |-> eg : #221:{((1|->0)|->3),((2|->0)|->0),...,((233|->0)|->218),((234|->0)|->228)}
614
615 b_compile2(not_member(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
616 FullyKnown=false, % predicates never evaluated in b_compile1
617 b_compile1(B,Parameters,LS,S,NExprB,Eval,_,WF),
618 (NExprB = b(value(X),_,_)
619 -> (X==[], always_well_defined(A) -> NExpr = truth
620 ; b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF),
621 (quick_test_membership1(NExprA,X,PRes)
622 -> convert_neg_pred_res(PRes,NExpr)
623 ; NExpr = not_member(NExprA,NExprB))
624 )
625 ; NExpr = not_member(NExprA,NExprB),
626 b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF)
627 ).
628 b_compile2(function(Fun,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
629 (is_lazy_extension_function_for_fun_app(Fun)
630 -> Eval1=false % extension function applications treated lazily
631 % TO DO: first evaluate B, if known then only evaluate relevant part of extension function
632 ; Eval1=Eval),
633 b_compile1(Fun,Parameters,LS,S,NExprA,Eval1,FullyKnown1,WF),
634 combine_fully_known(FullyKnown1,FullyKnown2,FullyKnown12),
635 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnown2,WF),
636 %tools_printing:print_term_summary(compiled_function(FullyKnown1,FullyKnown2,NExprA,NExprB)),nl,
637 (FullyKnown2=true,
638 (NExprA=b(value(_),_,_) -> true % no WD issue can be removed by apply, value already computed
639 ; preferences:preference(find_abort_values,false) % in a sequence extension we could remove non-WD elements
640 ),
641 % check if we have enough information to apply a partially specified function as a list
642 % e.g. if the function is [(int(1),A),(int(2),B)] and the argument is int(2): we can apply the function without knowing A or B; can have a dramatic importance when expanding unversal quantifiers !
643 ? can_apply_partially_specified_function(NExprA,NExprB,ResultExpr,WF)
644 -> NExpr = ResultExpr,
645 (FullyKnown12=true -> FullyKnown=true
646 ; ResultExpr=value(ResultValue),known_value(ResultValue) -> FullyKnown=true
647 ; FullyKnown = false)
648 ; %tools_printing:print_term_summary(cannot_apply_function(FullyKnown2,NExprA,NExprB)),nl,
649 %translate:print_bexpr(NExprA),nl, translate:print_bexpr(NExprB),nl,
650 NExpr = function(NExprA,NExprB), FullyKnown = FullyKnown12).
651
652 b_compile2(conjunct(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
653 FullyKnown=false, % predicates never automatically evaluated in b_compile1
654 ? b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF),
655 (is_falsity(NExprA) -> NExpr = falsity
656 ;
657 % TO DO: propagate static information from A to B, e.g. if A :: x=10 -> add x=10 to LS/Parameters
658 % also: try and detect unsatisfiable predicates beforehand
659 ? b_compile1(B,Parameters,LS,S,NExprB,Eval,_,WF),
660 (is_falsity(NExprB),
661 always_well_defined_or_wd_reorderings_allowed(NExprA) % otherwise we may remove a WD error, e.g., in x/y>0 & c>5
662 -> NExpr = falsity
663 ; is_truth(NExprB) -> get_texpr_expr(NExprA,NExpr)
664 ; is_truth(NExprA) -> get_texpr_expr(NExprB,NExpr)
665 ; NExpr = conjunct(NExprA,NExprB))
666 ).
667 b_compile2(disjunct(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
668 FullyKnown=false, % predicates never automatically evaluated in b_compile1
669 ? b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF),
670 (is_truth(NExprA) -> NExpr = truth
671 ? ; b_compile1(B,Parameters,LS,S,NExprB,false,_,WF), % does not have to be executed in a successful branch: set Eval to false to avoid computing expensive expressions which may not be needed
672 (is_truth(NExprB),
673 always_well_defined_or_wd_reorderings_allowed(NExprA) % otherwise we may remove a WD error, e.g., in x/y>0 or c<5
674 -> NExpr = truth
675 ; is_falsity(NExprA) -> get_texpr_expr(NExprB,NExpr)
676 ; is_falsity(NExprB) -> get_texpr_expr(NExprA,NExpr)
677 ; NExpr = disjunct(NExprA,NExprB))
678 ).
679 b_compile2(implication(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
680 FullyKnown=false, % predicates never automatically evaluated in b_compile1
681 b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF),
682 (is_falsity(NExprA) -> NExpr = truth
683 ; is_truth(NExprA) -> b_compile1(B,Parameters,LS,S,NExprB,Eval,_,WF), get_texpr_expr(NExprB,NExpr)
684 ; NExpr = implication(NExprA,NExprB),
685 b_compile1(B,Parameters,LS,S,NExprB,false,_,WF) % B does not have to be executed in a successful branch: set Eval to false to avoid computing expensive expressions which may not be needed
686 % TO DO: add preference to force pre-computation everywhere and pass Eval instead of false to b_compile1; ditto for disjunction
687 ).
688 b_compile2(negation(A),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
689 FullyKnown=false, % predicates never automatically evaluated in b_compile1
690 b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF),
691 ( get_negated_operator_expr(NExprA,NegatedA) -> NExpr = NegatedA
692 ; NExpr = negation(NExprA)
693 ).
694 b_compile2(if_then_else(A,B,C),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
695 b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF),
696 (is_falsity(NExprA) -> b_compile1(C,Parameters,LS,S,NExprC,Eval,FullyKnown,WF), get_texpr_expr(NExprC,NExpr)
697 ; is_truth(NExprA) -> b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnown,WF), get_texpr_expr(NExprB,NExpr)
698 ; NExpr = if_then_else(NExprA,NExprB,NExprC), FullyKnown=false,
699 b_compile1(B,Parameters,LS,S,NExprB,false,_,WF), % set Eval to false as we do not know if B will be needed
700 b_compile1(C,Parameters,LS,S,NExprC,false,_,WF) % ditto for C
701 ).
702 /* b_compile2(comprehension_set(CParas,Body),Parameters,LS,S,NExpr,_Eval,FullyKnown,WF) :-
703 sort(Parameters,SParas),
704 b_ast_cleanup:not_occurs_in_predicate(SParas,Body), %can only be applied if Body does not reference Parameters
705 !,
706 b_generate_inner_closure_if_necessary(Parameters,CParas,Body,LS,S,Result), % will itself call b_compile
707 NExpr = value(Result),
708 (ground(Result) -> FullyKnown=true ; FullyKnown=false). */
709 b_compile2(forall(ForallPara,A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
710 FullyKnown=false, % predicates never automatically evaluated in b_compile1
711 get_texpr_ids(ForallPara,AtomicIds),
712 add_parameters(Parameters,AtomicIds,NParameters),
713 b_compile1(A,NParameters,LS,S,NA,Eval,_FullyKnownA,WF),
714 (is_falsity(NA) -> NExpr = truth
715 ; b_compile1(B,NParameters,LS,S,NB,Eval,_FullyKnownB,WF),
716 (is_truth(NB),
717 always_well_defined_or_wd_reorderings_allowed(NA) % otherwise we may remove a WD error, e.g., in !x.(x:1..2 & x/y>0 => c<5)
718 -> NExpr = truth
719 ; NExpr = forall(ForallPara,NA,NB)
720 % TO DO ??: if we have an equality -> replace Body by value and remove quantifier
721 %,print('COMPIlED: '),translate:print_bexpr(b(NExpr,pred,[])),nl
722 )
723 ).
724 % some special cases to avoid calling syntaxtransformation
725 b_compile2(record_field(A,FieldName),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
726 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnownA,WF),
727 % First: we can try compute even if value not fully known !, we just need record field list
728 (get_record_field(NExprA,FieldName,NExpr,FullyKnown) -> true
729 ; NExpr = record_field(NExprA,FieldName), FullyKnown=FullyKnownA).
730 b_compile2(couple(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
731 %NExpr = couple(NExprA,NExprB),
732 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnown1,WF),
733 combine_fully_known(FullyKnown1,FullyKnown2,FullyKnown),
734 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnown2,WF),
735 (FullyKnown \== true, % evaluation will already combine the result
736 NExprA=b(value(VA),_,_),NExprB=b(value(VB),_,_)
737 -> NExpr = value((VA,VB))
738 ; NExpr = couple(NExprA,NExprB)).
739 b_compile2(image(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
740 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnown1,WF),
741 combine_fully_known(FullyKnown1,FullyKnown2,FullyKnown),
742 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnown2,WF),
743 (FullyKnown \= true, NExprA=b(value(VA),BT,BI),
744 NExprB=b(value(VB),_,_), nonvar(VB),
745 custom_explicit_sets:singleton_set(VB,VBX)
746 -> filter_cannot_match(VA,(VBX,_),NewVA,_Filtered), %nl,print(filtered_image(VBX,VA,NewVA)),nl,
747 NExpr = image(b(value(NewVA),BT,BI),NExprB)
748 % TO DO: add case where VB==[] or VA==[] are the empty set
749 ; NExpr = image(NExprA,NExprB)
750 ). %, print('compile image: '),translate:print_bexpr(NExpr),nl.
751 % TO DO: do something like can_apply_partially_specified_function; or filter_can_match
752 b_compile2(composition(A,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
753 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnown1,WF),
754 combine_fully_known(FullyKnown1,FullyKnown2,FullyKnown),
755 NExpr = composition(NExprA,NExprB),
756 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnown2,WF),
757 (FullyKnown=false, Eval=eval, performance_monitoring_on,
758 ( FullyKnown1=true, NExprB=b(value(_),_,Info), large_known_value(NExprA,2)
759 -> true %translate:nested_print_bexpr(NExprB),nl
760 ; FullyKnown2=true, NExprA=b(value(_),_,Info), large_known_value(NExprB,2)
761 -> true %translate:nested_print_bexpr(NExprA),nl
762 )
763 -> perfmessage(b_compiler,'Cannot compile relational composition (try lift it out of quantification)',Info)
764 ; true).
765 b_compile2(assertion_expression(A,Msg,B),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
766 b_compile1(A,Parameters,LS,S,NExprA,Eval,_,WF),
767 (is_truth(NExprA) -> % the ASSERT EXPR is redundant
768 %print(removed_assert),nl, translate:print_bexpr(B),nl,
769 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnown,WF),
770 get_texpr_expr(NExprB,NExpr)
771 ; b_compile1(B,Parameters,LS,S,NExprB,Eval,_,WF),
772 FullyKnown=false, % we cannot get rid of WD condition
773 NExpr = assertion_expression(NExprA,Msg,NExprB)
774 ).
775 b_compile2(domain(A),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
776 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnown1,WF),
777 (FullyKnown1=false,get_texpr_expr(NExprA,NA),evaluate_domain(NA,Domain) % try and compute domain even if not fully known
778 -> FullyKnown = true, NExpr = value(Domain)
779 ; FullyKnown = FullyKnown1, NExpr = domain(NExprA)).
780 b_compile2(range(A),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
781 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnown1,WF),
782 (FullyKnown1=false,evaluate_range(NExprA,Range) % try and compute range even if not fully known
783 -> FullyKnown = true, NExpr = value(Range)
784 ; FullyKnown = FullyKnown1, NExpr = range(NExprA)).
785 b_compile2(assign(LHS_List,RHS_List),Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- !,
786 NExpr = assign(New_LHS_List,NewRHS_List), FullyKnown = false,
787 maplist(b_compile_lhs(Parameters,LS,S,Eval,WF),LHS_List,New_LHS_List),
788 b_compile_l(RHS_List,Parameters,LS,S,NewRHS_List,Eval,_FullyKnown2,WF).
789 b_compile2(assign_single_id(ID,B),Parameters,LS,S,assign_single_id(ID,NExprB),Eval,FullyKnown,WF) :- !,
790 FullyKnown = false,
791 b_compile1(B,Parameters,LS,S,NExprB,Eval,_,WF).
792 b_compile2(operation_call(Operation,OpCallResults,OpCallParas),Parameters,LS,S,InlinedOpCall,Eval,FullyKnown,WF) :-
793 % TO DO: evaluate if we should also use the let_expression_global approach used for operation_call_in_expr
794 !,
795 def_get_texpr_id(Operation,op(OperationName)),
796 FullyKnown = false,
797 b_compile_l(OpCallParas,Parameters,LS,S,OpCallParaValues,Eval,_,WF),
798 TopLevel=false,
799 b_get_machine_operation_for_animation(OperationName,OpResults,OpFormalParameters,Body,_OType,TopLevel),
800 bsyntaxtree:replace_ids_by_exprs(Body,OpResults,OpCallResults,Body2),
801 get_texpr_ids(OpFormalParameters,OpIds),
802 add_parameters(Parameters,OpIds,InnerParas),
803 b_compile1(Body2,InnerParas,[],S,NBody,Eval,FullyKnown,WF), % do not pass local state: this may override constants,... from the called machine
804 % Note: global state S should be valid for all machines in currently loaded specification
805 get_texpr_ids(OpCallResults,OpRIds),
806 add_parameters(Parameters,OpRIds,LocalKnownParas),
807 simplify_assignment(OpFormalParameters,OpCallParaValues,LHSFormalParas,RHSCallVals), %%
808 split_formal_parameters(LHSFormalParas,RHSCallVals,LocalKnownParas,
809 FreshOpParas,FreshCallVals,
810 ClashOpParas, ClashCallVals), % only set up VAR for fresh Paras
811 % print(split(LHSFormalParas,LocalKnownParas,fresh(FreshOpParas),clash(ClashOpParas))),nl,
812 (FreshOpParas=[] -> get_texpr_expr(NBody,Let1)
813 ; create_equality_for_let(FreshOpParas,FreshCallVals,Equality1),
814 Let1 = let(FreshOpParas,Equality1,NBody)),
815 (ClashOpParas = []
816 -> InlinedOpCall = Let1
817 ; %nl,print(clash(ClashOpParas)),nl,
818 maplist(create_fresh_id,ClashOpParas,FreshCopy),
819 create_equality_for_let(ClashOpParas,FreshCopy,Equality2), % copy Values from Fresh Ids
820 create_equality_for_let(FreshCopy,ClashCallVals,Equality3), % assign Parameter Vals to Fresh Ids
821 get_texpr_pos(Body,BodyPos), BodyPosInfo = [nodeid(BodyPos)],
822 Let2 = let(ClashOpParas,Equality2,b(Let1,subst,[BodyPosInfo])),
823 InlinedOpCall = let(FreshCopy,Equality3,b(Let2,subst,[BodyPosInfo]))
824 ).
825 %, print('Compiled operation call: '), translate:print_subst(b(InlinedOpCall,subst,BodyPosInfo)),nl,nl.
826 % Maybe this version is faster when no OpCallResults:
827 %b_compile2(operation_call(Operation,OpCallResults,OpCallParas),Parameters,LS,S,InlinedOpCall,Eval,FullyKnown,WF) :-
828 % OpCallResults=[],
829 % !,
830 % def_get_texpr_id(Operation,op(OperationName)),
831 % FullyKnown = false,
832 %% b_compile_l(Results,Parameters,LS,S,NResults,Eval,_,WF),
833 % b_compile_l(OpCallParas,Parameters,LS,S,OpCallParaValues,Eval,_,WF),
834 % TopLevel=false,
835 % b_get_machine_operation_for_animation(OperationName,OpResults,OpParameters,Body,_OType,TopLevel),
836 % % Note: input parameters cannot be assigned to: so replace ids is ok
837 % % However, we cannot replace output parameters: these can be assigned to and we can have aliasing
838 % % Note: no aliasing is allowed in OpCallResults (cf Atelier-B handbook x,x <-- op not allowed)
839 % bsyntaxtree:replace_ids_by_exprs(Body,OpParameters,OpCallParaValues,Body2),
840 % get_texpr_ids(OpResults,OpIds),
841 % append(OpIds,Parameters,InnerParas),
842 % b_compile1(Body2,InnerParas,LS,S,NBody,Eval,FullyKnown,WF),
843 % FinalBody = NBody.
844 b_compile2(Expr,Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :-
845 functor(Expr,BOP,2),
846 binary_boolean_operator(BOP,_,_),!, % from kernel_mappings, slightly more efficient than syntaxtransformation
847 arg(1,Expr,A),
848 FullyKnown=false, % predicates never evaluated in b_compile1
849 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnownA,WF),
850 arg(2,Expr,B),
851 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnownB,WF),
852 (eval_binary_bool(FullyKnownA,NExprA,FullyKnownB,NExprB,BOP,Result)
853 -> NExpr = Result
854 ; functor(NExpr,BOP,2), arg(1,NExpr,NExprA), arg(2,NExpr,NExprB)
855 ).
856 b_compile2(external_function_call(ExtFun,Args),_Parameters,LS,_S,NExpr,_Eval,FullyKnown,_WF) :-
857 expects_unevaluated_args(ExtFun),
858 memberchk(bind('$optimize_do_not_force_lazy_lookups',_),LS), % this is an optimize call
859 !,
860 debug_format(9,'Not compiling external function call to ~w~n',[ExtFun]),
861 NExpr=external_function_call(ExtFun,Args),
862 FullyKnown=false.
863 b_compile2(Expr,Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :-
864 functor(Expr,BOP,2),
865 kernel_mappings:binary_function(BOP,_,_),!, % slightly more efficient than syntaxtransformation
866 arg(1,Expr,A),
867 ? b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnownA,WF),
868 combine_fully_known(FullyKnownA,FullyKnownB,FullyKnown),
869 arg(2,Expr,B),
870 b_compile1(B,Parameters,LS,S,NExprB,Eval,FullyKnownB,WF),
871 functor(NExpr,BOP,2), arg(1,NExpr,NExprA), arg(2,NExpr,NExprB).
872 b_compile2(Expr,Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :-
873 functor(Expr,UOP,1),
874 kernel_mappings:unary_function(UOP,_,_),!, % slightly more efficient than syntaxtransformation
875 arg(1,Expr,A),
876 b_compile1(A,Parameters,LS,S,NExprA,Eval,FullyKnown,WF),
877 functor(NExpr,UOP,1), arg(1,NExpr,NExprA).
878 b_compile2(Expr,Parameters,LS,S,NExpr,Eval,FullyKnown,WF) :- % GENERAL CASE
879 %hit_profiler:add_profile_hit(Expr),
880 ? syntaxtransformation(Expr,Subs,Names,NSubs,NExpr),
881 get_texpr_ids(Names,Ids),
882 add_parameters(Parameters,Ids,NParameters),
883 ? b_compile_l(Subs,NParameters,LS,S,NSubs,Eval,FullyKnown,WF).
884
885 b_compile_l([],_,_,_,[],_Eval,true,_WF).
886 b_compile_l([Expr|ExprRest],P,LS,S,[NExpr|NExprRest],Eval,FullyKnown,WF) :-
887 ? b_compile1(Expr,P,LS,S,NExpr,Eval,FullyKnown1,WF),
888 combine_fully_known(FullyKnown1,FullyKnown2,FullyKnown),
889 b_compile_l(ExprRest,P,LS,S,NExprRest,Eval,FullyKnown2,WF).
890
891 % detecth when a parameter clashes with existing known ids
892 id_clash(LocalKnownParas,TID) :- def_get_texpr_id(TID,ID), member(ID,LocalKnownParas).
893
894 /* comment in if we want to compile inner comprehension sets:
895 :- use_module(bsyntaxtree,[split_names_and_types/3]).
896 :- use_module(closures,[construct_closure_if_necessary/4]).
897 b_generate_inner_closure_if_necessary(OuterParameters,ClosureParas,Condition,LocalState,State,Result) :-
898 split_names_and_types(ClosureParas,Names,Types),
899 add_parameters(OuterParameters,Names,FullNames),
900 b_compile(Condition,FullNames,LocalState,State,ClosurePred),
901 print('INNER COMPILE: '), translate:print_bexpr(ClosurePred),nl,
902 construct_closure_if_necessary(Names,Types,ClosurePred,Result).
903 */
904
905
906 % the LHS contains l-values which should not be looked up in the environment
907 % however, we need to deal with things like f(i) := RHS and compile i
908 b_compile_lhs(Parameters,LS,S,Eval,WF,TExpr,NewTExpr) :-
909 TExpr = b(Expr,Type,Info), NewTExpr = b(NewExpr,Type,Info),
910 b_compile_lhs_aux(Expr,Parameters,LS,S,NewExpr,Eval,WF).
911
912 b_compile_lhs_aux(function(A,B),Parameters,LS,S,function(NewA,NewB),Eval,WF) :- !,
913 b_compile_lhs(Parameters,LS,S,Eval,WF,A,NewA), % we can have nexted function calls f(e)(g) :=
914 b_compile1(B,Parameters,LS,S,NewB,Eval,_,WF).
915 b_compile_lhs_aux(E,_,_,_,E,_,_WF). % other LHS should be identifier -> just copy
916
917 get_record_field(b(value(Val),_,_),FieldName,value(Field),FullyKnown) :- !,
918 nonvar(Val), Val=rec(Fields),
919 safe_get_field(Fields,FieldName,Field),
920 known_value(Field,FullyKnown).
921 get_record_field(b(function(FUN,ARG),_Type,_Info),FieldName,function(ReducedFUN,ARG),false) :-
922 % {1|->rec(a:1,b:2),...}(x)'b --> {1|->2,...}(x)
923 %nl,print(get_field(FUN,ARG,FieldName)),nl,
924 % TO DO: also allow nested functions calls {1|->rec(a:1,b:2),...}(x)(y)'b or other reduction operators
925 get_field_in_range(FUN,FieldName,ReducedFUN).
926 safe_get_field(V,FN,_) :- (var(V) ; var(FN)),!,fail.
927 safe_get_field([field(N,V)|T],FieldName,Result) :- nonvar(N),
928 (N=FieldName -> Result=V ; safe_get_field(T,FieldName,Result)).
929
930 :- use_module(probsrc(custom_explicit_sets),[expand_custom_set_to_list/4, convert_to_avl/2]).
931 :- use_module(probsrc(avl_tools),[avl_height_less_than/2]).
932 get_field_in_range(b(value(OldVal),OldType,Info),FieldName,
933 b(value(NewVal),set(couple(Dom,NewRange)),Info)) :-
934 is_set_type(OldType,couple(Dom,OldRange)),
935 nonvar(OldVal), OldVal=avl_set(AVL),
936 avl_height_less_than(AVL,10),
937 OldRange = record(Fields),
938 member(field(FieldName,NewRange),Fields),!,
939 expand_custom_set_to_list(avl_set(AVL),List,_,get_field_in_range),
940 maplist(safe_get_range_field(FieldName),List,NewList),
941 convert_to_avl(NewList,NewVal).
942
943 % compute the field access for the range elements:
944 safe_get_range_field(FieldName,(Dom,rec(Fields)),(Dom,Field)) :- safe_get_field(Fields,FieldName,Field).
945
946
947 eval_binary_bool(true,b(value(ValA),_,_),true,b(value(ValB),_,_),BOP,Result) :-
948 ground(ValA),
949 ground(ValB),
950 eval_binary_aux(BOP,ValA,ValB,Result).
951
952 eval_binary_aux(less,int(A),int(B),Result) :-
953 (A < B -> Result = truth ; Result = falsity).
954 eval_binary_aux(greater,int(A),int(B),Result) :-
955 (A > B -> Result = truth ; Result = falsity).
956 eval_binary_aux(less_equal,int(A),int(B),Result) :-
957 (A =< B -> Result = truth ; Result = falsity).
958 eval_binary_aux(greater_equal,int(A),int(B),Result) :-
959 (A >= B -> Result = truth ; Result = falsity).
960 eval_binary_aux(subset,avl_set(A1),avl_set(A2),Result) :-
961 (custom_explicit_sets:check_avl_subset(A1,A2) -> Result = truth ; Result = falsity).
962 eval_binary_aux(subset,[],_,Result) :- Result=truth.
963 %eval_binary_aux(less_real,real(A),real(B),Result) :- % TO DO
964 % (A < B -> Result = truth ; Result = falsity).
965 % TO DO: other operators are not_subset, strict_subset, ... intervals for subset,...
966
967
968
969 :- use_module(store,[lookup_value_for_existing_id_wf/5]).
970 compute_lazy_lookup(Id,Expr,LS,S,NExpr,FullyKnown,WF) :-
971 lookup_value_for_existing_id_wf(Id,LS,S,(Evaluated,Value),WF),
972 % the lazy expression has already been registered, but maybe not yet evaluated
973 !,
974 known_value(Value,FullyKnown), % compute if value fully known
975 (Evaluated==pred_true -> NExpr = value(Value)
976 ; FullyKnown==true -> NExpr = value(Value)
977 ; memberchk(bind('$optimize_do_not_force_lazy_lookups',_),LS)
978 -> NExpr = Expr % we do not force lookup: there could be WD issues !
979 % TO DO: examine Infos for wd_condition; we could also return NExpr = lazy_value(Id,Evaluated,Value)
980 ; if(Evaluated = pred_true,
981 % will force evaluation ! Note: this means shared expression inside a compiled expression must be well-defined
982 NExpr = value(Value),
983 (add_internal_error_wf(b_compiler,'Compilation failed: ', Id, unknown,WF),
984 fail))
985 ).
986 compute_lazy_lookup(Id,_E,_LS,_S,_LazyValue,_,WF) :-
987 add_internal_error_wf(b_compiler,'Compilation failed, illegal lazy_lookup_value: ',Id,unknown,WF),
988 fail.
989
990 combine_fully_known(true,A,A).
991 combine_fully_known(false,_,false).
992
993 :- use_module(tools_lists,[length_greater/2]).
994 % is an extension function with at least two elements, but not too long
995 % (for long set extensions it is much better to compile them to avl once; see private_examples/ClearSy/2019_Sep/rule_dummy)
996 % extension functions are treated lazily in b_interpreter for function application under the condition:
997 % memberchk(contains_wd_condition,FInfo) ; preferences:preference(use_clpfd_solver,false) ; ground_value(ArgValue)
998 is_lazy_extension_function_for_fun_app(b(A,_,FInfo)) :-
999 preferences:preference(data_validation_mode,false),
1000 (memberchk(contains_wd_condition,FInfo) -> Lim=98 ; Lim = 23),
1001 is_extension_function_aux(A,Lim).
1002 is_extension_function_aux(set_extension([_A,_|T]),Lim) :- \+ length_greater(T,Lim).
1003 is_extension_function_aux(sequence_extension([_,_|T]),Lim) :- \+ length_greater(T,Lim).
1004
1005 :- use_module(bsyntaxtree,[is_set_type/2]).
1006 % check if we can apply an argument to a partially specified function (as a list and now also as AVL)
1007 %can_apply_partially_specified_function(Fun,X,_,_) :- print(fun(Fun)),nl,print(val(X)),nl,fail.
1008 can_apply_partially_specified_function(b(Expr,TYPE,_), b(value(X),TA,_),ResultExpr,WF) :-
1009 ? can_apply_aux(Expr,TYPE,X,TA,ResultExpr,WF).
1010
1011 can_apply_aux(value(VAL),TYPE,X,TA,value(ResultValue),WF) :-
1012 is_set_type(TYPE,couple(TA,_TB)),
1013 ? lookup_result(VAL,X,ResultValue,WF).
1014 can_apply_aux(sequence_extension(List),_,X,integer,ResultExpr,_WF) :-
1015 % important, e.g., for solving test 1551: {b|[a,b,c](2)=333} =res & a : res & b:res
1016 nonvar(X), X=int(Index), number(Index),
1017 % this will prevent computing rest of sequence extension: can hide WD issues !
1018 % print(apply_seq_extension(Index,List)),nl,
1019 nth1(Index,List,b(ResultExpr,_,_)).
1020
1021 :- use_module(kernel_equality,[equality_objects_wf/4, equality_can_be_decided_by_unification/1]).
1022 :- use_module(kernel_tools,[ground_value/1]).
1023 %lookup_result(VAR,ArgValue,Result,WF) :- var(VAR),!,kernel_mappings:kernel_call_apply_to(VAR,ArgValue,Result,unknown,unknown,WF).
1024 % the clause above is unsound; as apply_to CAN RAISE WD ERRORS !! what if we have IF 1:dom(f) THEN f(1) ELSE f(0) END; we do not want to compute f(1) ! it can also instantiate unbound variables !
1025 % the idea was to avoid that we wait on the full function, before compiled closure can be evaluated; test 1552
1026 % important for e.g. a = {(1, {([]|->2)} ), (2, const(1, [a(1)]))}
1027 % or: a = {1 |-> {[] |-> 2}, 2 |-> (dom({pi,ff,p|((pi : seq(INTEGER) & ff : INTEGER) & p : seq(INTEGER)) & (p |-> ff : [a(1)](1) & pi = 1 -> p)}) \/ {[] |-> 1})}
1028 % test 1552 is currently skipped
1029 % TO DO: think whether there are other deterministic computations that can be done in b_compile: prj1,prj2, record-field access ? this would ensure that closures,... can be computed earlier
1030 lookup_result(VAR,_,_,_WF) :- var(VAR),!,fail.
1031 lookup_result(avl_set(A),X,Result,_WF) :- ground_value(X),
1032 % the avl_set may be a relation which is not a function: we need to check that there is exactly one result
1033 findall(R,custom_explicit_sets:avl_member_pair_arg1_ground(X,R,A),Results),
1034 (Results = [Result]
1035 -> true % precompiled function application
1036 ; debug_format(19,'Function application in b_compiler for avl_set is not well-defined for: ~w~n',[X]),
1037 % We could transform the function application into a construct that raises a WD error
1038 fail).
1039 lookup_result(closure(_P,_T,_B),_X,_Result,_WF) :- !,
1040 fail. % TODO: should we replace parameters by values in body? if domain is full type?
1041 lookup_result(List,X,Result,WF) :- List = [_|_],equality_can_be_decided_by_unification(X),!,
1042 % this is relevant for long lists,
1043 % see public_examples/B/ExternalFunctions/Satsolver/QueensBoardVersionTF_Satsolver.mch
1044 fast_lookup_result(List,X,Result,WF).
1045 lookup_result(List,X,Result,WF) :-
1046 regular_lookup_result_in_list(List,X,Result,WF).
1047
1048 :- use_module(probsrc(preferences),[call_with_preference/3]).
1049 :- assert_must_fail(call_with_preference(
1050 b_compiler:lookup_result([(int(1),int(2)),(int(1),int(3))],int(1),_,_),find_abort_values,true)). % relation, not a function
1051 :- assert_must_succeed((call_with_preference(
1052 b_compiler:lookup_result([(int(1),int(2)),(int(1),int(3))],int(1),R,_),find_abort_values,false), R==int(2))).
1053 :- assert_must_succeed((call_with_preference(
1054 b_compiler:lookup_result([(int(1),int(2)),(int(2),int(3))],int(1),R,_),find_abort_values,true), R==int(2))).
1055 :- assert_must_fail((custom_explicit_sets:construct_interval_closure(1,2,C),
1056 custom_explicit_sets:convert_to_avl([int(1),int(2)],A),
1057 call_with_preference(
1058 b_compiler:lookup_result([(A,int(5)),(C,int(6))],A,_,_),find_abort_values,true))). % 1..2 = {1,2}: relation
1059 :- assert_must_succeed((custom_explicit_sets:construct_interval_closure(1,3,C),
1060 custom_explicit_sets:convert_to_avl([int(1),int(2)],A),
1061 call_with_preference(
1062 b_compiler:lookup_result([(A,int(5)),(C,int(6))],A,R,_),find_abort_values,true), R==int(5))).
1063 regular_lookup_result_in_list([],X,_Result,_WF) :-
1064 debug_format(19,'Function application in b_compiler for list is not well-defined for: ~w~n',[X]), % ditto
1065 fail.
1066 regular_lookup_result_in_list([(HFrom,HTo)|T],X,Result,WF) :-
1067 equality_objects_wf(HFrom,X,PredRes,WF),
1068 %kernel_equality:equality_objects1(HFrom,X,PredRes,WF), % this could be called if X is guaranteed nonvar
1069 nonvar(PredRes), % only proceed if we have enough information to determine the result of the comparison
1070 (PredRes = pred_true
1071 -> check_no_other_match(T,X,WF), % list may be a relation, e.g., {1|->2,1|->3}: application would be a WD error
1072 Result = HTo
1073 ; regular_lookup_result_in_list(T,X,Result,WF)).
1074
1075 % a faster version which does not use equality_objects_wf
1076 fast_lookup_result([(HFrom,HTo)|T],X,Result,WF) :-
1077 equality_can_be_decided_by_unification(HFrom), !,
1078 (HFrom=X -> check_no_other_match(T,X,WF), Result = HTo
1079 ; fast_lookup_result(T,X,Result,WF)
1080 ).
1081 fast_lookup_result(List,X,Result,WF) :-
1082 regular_lookup_result_in_list(List,X,Result,WF).
1083
1084 % if TRY_FIND_ABORT is true: check that X definitely does not occur in the domain of the remaining list;
1085 % otherwise fail (do not compile), so that the interpreter can detect the WD error
1086 check_no_other_match(T,X,WF) :-
1087 (preferences:preference(find_abort_values,true)
1088 -> no_other_match_in_list(T,X,WF)
1089 ; true). % we assume there is no other value later
1090 no_other_match_in_list(V,_,_) :- var(V),!,fail.
1091 no_other_match_in_list([],_,_).
1092 no_other_match_in_list([(HFrom,_)|T],X,WF) :-
1093 (equality_can_be_decided_by_unification(HFrom),
1094 equality_can_be_decided_by_unification(X)
1095 -> HFrom \= X
1096 ; equality_objects_wf(HFrom,X,PredRes,WF),
1097 PredRes == pred_false
1098 ),
1099 no_other_match_in_list(T,X,WF).
1100
1101
1102 % get_comprehension_set(b(SET,_,_),ID,PRED) :- get_comprehension_set_aux(SET,ID,PRED).
1103 % get_comprehension_set_aux(comprehension_set([TID],PRED),ID,PRED) :-
1104 % get_texpr_id(TID,ID).
1105 % get_comprehension_set_aux(value(V),ID,PRED) :- nonvar(V), V = closure([ID],_,PRED).
1106
1107
1108
1109
1110 quick_test_membership1(b(value(VA),_,_),VB,Result) :-
1111 ? quick_test_membership_aux(VB,VA,Result).
1112 quick_test_membership_aux(VAR,_,_) :- var(VAR),!,fail.
1113 quick_test_membership_aux([],_,pred_false).
1114 quick_test_membership_aux(avl_set(AVL),X,Result) :-
1115 custom_explicit_sets:quick_test_avl_membership(AVL,X,Result). % we could also check that in case X is not ground but partially instantiated, whether there is a possible match in AVL (if not Result = pred_false)
1116 quick_test_membership_aux(global_set(GS),X,Result) :- nonvar(X), X=int(IX), nonvar(IX),
1117 custom_explicit_sets:membership_global_set(GS,X,R,_WF),
1118 nonvar(R), Result=R.
1119 quick_test_membership_aux(closure(P,T,B),X,Result) :- nonvar(X), X=int(IX), nonvar(IX),
1120 is_fixed_interval(P,T,B,LOW,UP),
1121 kernel_equality:in_nat_range_test(X,int(LOW),int(UP),R),
1122 nonvar(R), Result=R.
1123 quick_test_membership_aux(closure(P,T,B),X,Result) :- X==[], % check {} : POW(_) / FIN(_) and {} : POW1(_) / FIN1(_)
1124 custom_explicit_sets:is_powerset_closure(closure(P,T,B),Kind,_),
1125 (contains_empty_set(Kind) -> Result = pred_true ; Result=pred_false).
1126
1127 is_fixed_interval(P,T,B,LOW,UP) :-
1128 custom_explicit_sets:is_interval_closure(P,T,B,LOW,UP), integer(LOW),integer(UP).
1129
1130 contains_empty_set(pow).
1131 contains_empty_set(fin).
1132
1133 convert_pred_res(pred_false,falsity).
1134 convert_pred_res(pred_true,truth).
1135 convert_neg_pred_res(pred_true,falsity).
1136 convert_neg_pred_res(pred_false,truth).
1137
1138 generate_equality(b(A,_,_),b(B,_,_),Res) :-
1139 ( generate_equality_aux(A,B,Res) ;
1140 generate_equality_aux(B,A,Res) ),
1141 !.
1142 generate_equality(A,B,equal(A,B)).
1143
1144 generate_equality_aux(convert_bool(AA),value(PT),Res) :-
1145 PT==pred_true,
1146 get_texpr_expr(AA,TA),
1147 !,
1148 Res = TA.
1149 generate_equality_aux(convert_bool(AA),value(PF),Res) :-
1150 PF==pred_false,!,
1151 Res = negation(AA).
1152
1153 % generate an equal(_,_) node where the second one is a Value
1154 generate_equality_with_value(b(value(ValA),_,_),true,ValB,true,_TA,NExpr) :-
1155 % both are FullyKnown
1156 simple_value(ValA), % we should avoid closures
1157 !,
1158 kernel_equality:equality_objects(ValA,ValB,PRes),
1159 convert_pred_res(PRes,NExpr).
1160 generate_equality_with_value(NExprA,_,Value,_,TA,equal(NExprA,b(value(Value),TA,[]))).
1161
1162 % similar to custom_explicit_sets:simple_value
1163 % values where we can decide equality easily
1164 simple_value(fd(_,_)).
1165 simple_value(pred_true /* bool_true */).
1166 simple_value(pred_false /* bool_false */).
1167 simple_value(int(_)).
1168 simple_value((A,B)) :- simple_value(A), simple_value(B).
1169 simple_value(rec(Fields)) :- maplist(simple_field,Fields).
1170 simple_value(string(_)).
1171
1172 simple_field(field(_,Val)) :- simple_value(Val).
1173
1174 known_value(X,FullyKnown) :- (known_value(X) -> FullyKnown=true ; FullyKnown=false).
1175 known_value(X) :- nonvar(X), known_value2(X).
1176 known_value2(global_set(GS)) :- nonvar(GS).
1177 known_value2(freetype(GS)) :- nonvar(GS).
1178 known_value2(closure(P,T,B)) :- known_closure(P,T,B).
1179 %Note: for other closures: they still may have to be computed; some of the computations in wd_and_efficient could be expensive for closures
1180 known_value2(avl_set(_)). % already fully normalised
1181 known_value2((X,Y)) :- known_value(X),known_value(Y).
1182 known_value2(fd(A,B)) :- number(A),atomic(B).
1183 known_value2(int(N)) :- number(N).
1184 known_value2(term(F)) :- nonvar(F),F=floating(N),number(N).
1185 known_value2([]).
1186 known_value2(pred_true).
1187 known_value2(pred_false).
1188 known_value2(string(S)) :- atomic(S).
1189 known_value2([H|T]) :- known_value(H), known_value(T).
1190 %known_value2(record(Fields)) :- known_fields(Fields).
1191 known_value2(rec(Fields)) :- known_fields(Fields).
1192
1193 :- use_module(avl_tools,[avl_height_less_than/2]).
1194 % large known avl_set value; for issueing perfmessage warnings
1195 large_known_value(b(value(V),_,_),Lim) :- nonvar(V), large_known_aux(V,Lim).
1196 large_known_aux(avl_set(A),Lim) :-
1197 \+ avl_height_less_than(A,Lim).
1198
1199 % something we could do:
1200 %optimize_known_value([H|T],Res) :- (convert_to_avl([H|T],CS) -> Res=CS ; print(failed_to_convert_known_list),nl,fail).
1201 % try_convert_to_avl
1202
1203 known_closure(P,T,B) :- custom_explicit_sets:is_interval_closure(P,T,B,Low,Up), !,
1204 number(Low), number(Up),
1205 Up < Low+1000.
1206 known_closure(P,T,B) :-
1207 is_cartesian_product_closure(closure(P,T,B),A1,A2),
1208 !,% we could call is_cartesian_product_closure_aux(P,T,B,A1,A2)
1209 known_value(A1), known_value(A2).
1210
1211 known_fields(X) :- var(X),!,fail.
1212 known_fields([]).
1213 known_fields([field(N,V)|T]) :- ground(N),known_value(V),known_fields(T).
1214
1215 %b_evaluate1(TExpr,Parameters,LS,S,ResultTExpr,FullyKnown) :-
1216
1217 check_is_id_list([],[]).
1218 check_is_id_list([H|T],Res) :-
1219 (H=b(identifier(_),_,_)
1220 -> add_internal_error('Typed id list as argument: ',check_is_id_list([H|T],Res)), % use get_texpr_ids or maplist(def_get_texpr_id,P,PIDs)
1221 maplist(def_get_texpr_id,[H|T],Res)
1222 ; Res=[H|T]).
1223
1224 :- use_module(kernel_frozen_info,[kfi_domain/2]).
1225
1226 :- use_module(custom_explicit_sets,[construct_interval_closure/3]).
1227 % try and evaluate domain of a list (avl_set already dealt with separately)
1228 %evaluate_domain(X,_) :- print(dom(X)),nl,fail.
1229 evaluate_domain(sequence_extension(L),Domain) :-
1230 % this will prevent computing the elements of the sequence extension: we may hide WD issues, e.g., dom([1/y])
1231 all_wd_or_wd_reorderings_allowed(L,0,Len),
1232 construct_interval_closure(1,Len,Domain).
1233 % TO DO: set_extension when possible ?
1234 evaluate_domain(value(L),Domain) :-
1235 get_domain(L,Domain).
1236
1237 % check that all elements are well-defined (or WD reordering allowed) and compute the length of the list
1238 all_wd_or_wd_reorderings_allowed([],Len,Len).
1239 all_wd_or_wd_reorderings_allowed([H|T],Acc,Len) :-
1240 always_well_defined_or_wd_reorderings_allowed(H),
1241 Acc1 is Acc+1,
1242 all_wd_or_wd_reorderings_allowed(T,Acc1,Len).
1243
1244 :- assert_must_succeed((custom_explicit_sets:construct_interval_closure(1,2,C), % {1..2|->1, {1,2}|->2}
1245 custom_explicit_sets:convert_to_avl([int(1),int(2)],A),
1246 b_compiler:get_domain([(C,int(1)),(A,int(2))],R),
1247 kernel_objects:equal_object(R,[A]))).
1248 :- assert_must_fail((custom_explicit_sets:construct_interval_closure(1,2,C), % {SC|->1, SC|->2} with SC symbolic
1249 closures:mark_closure_as_symbolic(C,SC),
1250 b_compiler:get_domain([(SC,int(1)),(SC,int(2))],_))). % domain cannot be converted to AVL
1251 get_domain(V,Dom) :- var(V),!,kfi_domain(V,Dom). % try infer domain from attached co-routines
1252 get_domain([],[]).
1253 get_domain([V|VT],Result) :- nonvar(V), V=(D,_),
1254 known_value(D),get_list_domain(VT,DT),
1255 %length(DT,Len),print(got_list_domain(D,Len)),nl,
1256 convert_to_duplicate_free_set(D,DT,domain,Result).
1257 % we could also do this:
1258 %get_domain(closure(Par,Typ,Body),Result) :-
1259 % is_lambda_value_domain_closure(Par,Typ,Body, DomainValue,Expr), check_wd(Expr),
1260 % Result=DomainValue.
1261 get_list_domain(V,_) :- var(V),!,fail.
1262 get_list_domain([],[]).
1263 get_list_domain([V|VT],[D|DT]) :- nonvar(V), V=(D,_),
1264 known_value(D),get_list_domain(VT,DT).
1265
1266
1267 :- use_module(kernel_frozen_info,[kfi_range/2]).
1268
1269 % try and evaluate range of a list (avl_set already dealt with separately)
1270 evaluate_range(b(value(L),_T,_),Range) :-
1271 get_range(L,Range).
1272 :- assert_must_succeed((custom_explicit_sets:construct_interval_closure(1,2,C), % {1|->1..2, 2|->{1,2}}
1273 custom_explicit_sets:convert_to_avl([int(1),int(2)],A),
1274 b_compiler:get_range([(int(1),C),(int(2),A)],R),
1275 kernel_objects:equal_object(R,[A]))).
1276 :- assert_must_succeed((b_compiler:get_range([(int(1),int(2)),(int(2),int(2))],R), kernel_objects:equal_object(R,[int(2)]))).
1277 get_range(V,Dom) :- var(V),!,kfi_range(V,Dom). % try infer range from attached co-routines
1278 get_range([],[]).
1279 get_range([V|VT],Result) :- nonvar(V), V=(_,D),
1280 known_value(D),
1281 get_list_range(VT,DT),
1282 convert_to_duplicate_free_set(D,DT,range,Result).
1283
1284 % convert a list of known values [D|DT] (domain or range of a relation) into a set value without duplicates
1285 % sort/2 would not remove duplicate values in different representations, e.g., 1..2 and {1,2}
1286 convert_to_duplicate_free_set(D,DT,Kind,Result) :-
1287 custom_explicit_sets:try_convert_to_avl([D|DT],Res),
1288 (Res = avl_set(_) -> Result=Res
1289 ; DT = [] -> Result = [D]
1290 ; perfmessage(b_compiler,'Could not convert domain/range to AVL:',Kind/D),
1291 fail). % we could have duplicates, e.g., for symbolic closures; do not compile
1292
1293 get_list_range(V,_) :- var(V),!,fail.
1294 get_list_range([],[]).
1295 get_list_range([V|VT],[D|DT]) :-
1296 nonvar(V), V=(_,D),
1297 known_value(D),
1298 get_list_range(VT,DT).
1299
1300 create_equality_for_let(LHS,RHS,Conj) :-
1301 maplist(create_eq,LHS,RHS,CL),
1302 conjunct_predicates(CL,Conj).
1303 create_eq(Id,Expr,TPred) :- safe_create_texpr(equal(Id,Expr),pred,TPred).
1304
1305 % split formal operation call parameters into those which clash and those that do not:
1306 split_formal_parameters([],[],_,[],[],[],[]).
1307 split_formal_parameters([Formal1|FormalT],[Val1|VT],LocalKnownParas,Fresh,FV,Clash,CV) :-
1308 (id_clash(LocalKnownParas,Formal1)
1309 -> Fresh = FreshT, FV=FVT, Clash = [Formal1|ClashT], CV = [Val1|CVT]
1310 ; Fresh = [Formal1|FreshT], FV = [Val1|FVT], Clash = ClashT, CV = CVT
1311 ), split_formal_parameters(FormalT,VT,LocalKnownParas,FreshT,FVT,ClashT,CVT).
1312
1313 :- use_module(gensym,[gensym/2]).
1314 create_fresh_id(b(identifier(_),T,I),b(identifier(FRESHID),T,I)) :-
1315 gensym('__COMPILED_ID__',FRESHID).
1316
1317 :- use_module(bsyntaxtree, [get_texpr_pos/2,same_id/3]).
1318 % compute which assignments are really necessary, remove skip assignments x := x
1319 simplify_assignment([],[],[],[]).
1320 simplify_assignment([ID1|T1],[ID2|T2],Res1,Res2) :-
1321 (same_id(ID1,ID2,_) -> Res1=TR1, Res2=TR2 ; Res1=[ID1|TR1], Res2=[ID2|TR2]),
1322 simplify_assignment(T1,T2,TR1,TR2).
1323
1324
1325 /*
1326 % check if an AST term is a total lambda without WD condition:
1327 % NExprA=value(closure([x,...,'_lambda_result_'],b(equal())), NExprB=couple(,,,,) -> replace x by parameters
1328 % possibly better to do this via contains_wd_condition or similar Info field?!
1329
1330
1331 is_total_lambda(b(value(V),_,_),OtherIDs,LambdaExpr) :- nonvar(V),
1332 V=closure(Args,_Types,Body),
1333 is_total_lambda_closure(Args,Body, OtherIDs, LambdaExpr).
1334
1335 :- use_module(probsrc(bsyntaxtree),[conjunction_to_list/2,occurs_in_expr/2]).
1336 is_total_lambda_closure(Args,b(equal(TLambda,LambdaExpr),pred,_),OtherIDs,LambdaExpr) :-
1337 get_texpr_id(TLambda,LambdaID),
1338 append(OtherIDs,[LambdaID],Args),
1339 \+ occurs_in_expr(LambdaID,LambdaExpr).
1340
1341 % try and get arguments from expression
1342 get_actual_arguments([_],Expr,Args) :- !,
1343 % print('arg1: '),tools_printing:print_term_summary(Expr),nl,
1344 check_simple(Expr),
1345 Args= [Expr].
1346 get_actual_arguments([_|T],b(Couple,_,_),[Arg1|TArgs]) :-
1347 get_couple(Couple,Arg1,Arg2), print('arg: '),tools_printing:print_term_summary(Arg1),nl,
1348 check_simple(Arg1),
1349 get_actual_arguments(T,Arg2,TArgs).
1350
1351 check_simple(b(V,_,_)) :- simple2(V).
1352 simple2(value(_)).
1353 simple2(identifier(_)).
1354 simple2(integer(_)).
1355
1356 get_couple(couple(A,B),A,B).
1357 %get_couple(value(V),A,B) :- nonvar(V), V=(V1,V2), ... % TODO
1358
1359
1360 Code for bcompile2(function(...))
1361
1362
1363 % ; is_total_lambda(NExprA,Ids,Expr) ,
1364 % get_actual_arguments(Ids,NExprB,Args) %, print(ok),nl, translate:l_print_bexpr_or_subst(Args),nl
1365 % ->
1366 % bsyntaxtree:replace_ids_by_exprs(Expr,Ids,Args,Result),
1367 % % only ok if we do not replicate expressions !! we could repeatedly re-apply rule / compilation on result
1368 % print(' replaced: '),translate:print_bexpr(Result),nl,
1369 % Result = b(NExpr,_,_), FullyKnown = FullyKnown12
1370
1371 */