1 % (c) 2012-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(external_functions,[call_external_function/7, call_external_predicate/8,
6 call_external_substitution/6,
7 reset_external_functions/0,
8 print_external_function_instantiation_profile/0,
9 external_pred_always_true/1,
10 reset_side_effect_occurred/0,
11 side_effect_occurred/1,
12 performs_io/1, not_declarative/1,
13 is_external_function_name/1,
14 get_external_function_type/3, % version with types with Prolog variables
15 external_fun_type/3,
16 external_subst_enabling_condition/3,
17 external_fun_has_wd_condition/1,
18 external_fun_can_be_inverted/1,
19 external_function_requires_state/1,
20 expects_unevaluated_args/1,
21 do_not_evaluate_args/1,
22 reset_argv/0, set_argv_from_list/1, set_argv_from_atom/1,
23 set_current_state_for_external_fun/1, clear_state_for_external_fun/0,
24
25 observe_parameters/2, observe_state/1, observe_value/2,
26
27 consult_new_external_functions/1
28 ]).
29
30 % Note: there is also the predicate external_procedure_used/1 in bmachine_construction
31
32 :- use_module(error_manager).
33 :- use_module(self_check).
34 :- use_module(library(avl)).
35 :- use_module(library(lists)).
36 :- use_module(translate).
37
38 % TO DO: add external Prolog files
39 % Should we do auto-conversion of B to Prolog types ,... ?
40
41 :- use_module(kernel_waitflags).
42 :- use_module(debug).
43 :- use_module(bsyntaxtree).
44 :- use_module(custom_explicit_sets).
45
46 :- use_module(module_information,[module_info/2]).
47 :- module_info(group,external_functions).
48 :- module_info(description,'This module provides a way to call external functions and predicates.').
49
50 :- set_prolog_flag(double_quotes, codes).
51
52 :- dynamic side_effect_occurred/1.
53 % TRUE if a side effect has occured
54 % possible values (user_output, file)
55 reset_side_effect_occurred :- (retract(side_effect_occurred(_)) -> retractall(side_effect_occurred(_)) ; true).
56 assert_side_effect_occurred(Location) :-
57 (side_effect_occurred(Location) -> true ; assertz(side_effect_occurred(Location))).
58
59 :- discontiguous expects_waitflag/1.
60 :- discontiguous expects_spaninfo/1.
61 :- discontiguous expects_type/1. % only used for external functions, not predicates or subst
62 :- discontiguous performs_io/1.
63 :- discontiguous is_not_declarative/1. % does not perform io but is still not declarative, e.g., has hidden args
64 :- discontiguous does_not_modify_state/1.
65 :- discontiguous expects_unevaluated_args/1.
66 :- discontiguous do_not_evaluate_args/1. % currently only used for external predicates, not for functions
67 :- discontiguous expects_state/1. % currently only used for external predicates
68 :- discontiguous external_pred_always_true/1. % external predicates which are always true
69 :- discontiguous external_subst_enabling_condition/3. % external predicates which are always true
70 :- discontiguous external_fun_has_wd_condition/1.
71 :- discontiguous external_fun_can_be_inverted/1. % helps the ProB constraint solver
72 :- discontiguous external_function_requires_state/1. % true if the function/predicate works on the current state in the state space
73 :- discontiguous external_fun_type/3. % external_fun_type(FUN,ListOfTypeParameters,ListOfArgTypes); also applicable to external predicates
74
75 % declare those predicates multifile which an external function library
76 % (loaded by -load_external_library) may have to define
77 % in principle these are all the predicates above
78 :- multifile external_fun_type/3, performs_io/1, expects_spaninfo/1, expects_waitflag/1,
79 external_fun_has_wd_condition/1.
80
81 :- meta_predicate safe_call(0,-,-).
82 :- meta_predicate safe_call(0,-).
83
84 :- meta_predicate observe_ground(-,-,-,-,-,0).
85
86 not_declarative(FunName) :- if(performs_io(FunName),true,is_not_declarative(FunName)).
87
88 is_external_function_name(Name) :- if(external_fun_type(Name,_,_),true,
89 if(expects_waitflag(Name),true,
90 if(expects_spaninfo(Name),true,
91 if(external_subst_enabling_condition(Name,_,_),true,
92 if(not_declarative(Name),true,
93 if(expects_unevaluated_args(Name),true,fail)
94 ))))).
95
96
97 :- use_module(state_space,[current_state_id/1, get_current_context_state/1]).
98 :- dynamic current_state_id_for_external_fun/1.
99 % some external functions access the current state; here we can set a particular state, without changing the animator/state_space
100 % useful, e.g., when exporting a VisB HTML trace when the JSON glue file uses ENABLED
101 % TODO: some commands also access the history;
102
103 % we use this rather than set_context_state because this would lead to errors being stored in the state_space
104 set_current_state_for_external_fun(ID) :-
105 asserta(current_state_id_for_external_fun(ID)).
106
107 clear_state_for_external_fun :-
108 (retract(current_state_id_for_external_fun(_)) -> true ; format('No state for external functions stored!~n',[])).
109
110 get_current_state_id(ID) :-
111 (current_state_id_for_external_fun(CID) -> ID=CID
112 ; state_space:get_current_context_state(CID) -> ID=CID
113 ; current_state_id(ID)).
114
115 % get current history without root (and without current state id)
116 get_current_history(History,Span) :-
117 history(RH),!,
118 (state_space:get_current_context_state(CID),
119 (current_state_id(CID)
120 -> RH=[Last|_], \+ state_space:transition(Last,CID,_) % something wrong, this cannot be last state of history
121 ; true % the history was not made for context state CID
122 ),
123 append(_,[CID|RH2],RH) % stop at CID which is being set; not a perfect solution; CID could occur multiple times!
124 -> true
125 ; RH2=RH),
126 (RH2=[] -> History=[]
127 ; reverse(RH2,[root|HH]) -> History = HH
128 ; add_message(external_functions,'HISTORY does not start with root:',RH2,Span), % from ProB2: fix
129 reverse(RH2,History)
130 ).
131 get_current_history(History,Span) :- add_message(external_functions,'No HISTORY available','',Span), History=[].
132
133 :- use_module(runtime_profiler,[profile_single_call/4]).
134
135 :- assert_must_succeed(( external_functions:call_external_function('COS',[b(integer(0),integer,[])],
136 [int(0)],int(100),integer,unknown,_WF) )).
137 :- assert_must_succeed(( external_functions:call_external_function('SIN',[b(integer(0),integer,[])],
138 [int(0)],int(0),integer,unknown,_WF) )).
139 % first a few hard-wired external functions for efficiency:
140 call_external_function('COS',_,[X],Value,_,_,_WF) :- !, 'COS'(X,Value). % already use safe_is
141 call_external_function('SIN',_,[X],Value,_,_,_WF) :- !, 'SIN'(X,Value).
142 call_external_function('TAN',_,[X],Value,_,_,_WF) :- !, 'TAN'(X,Value).
143 %call_external_function('STRING_APPEND',_,[A,B],Value,_,_,WF) :- !, 'STRING_APPEND'(A,B,Value,WF). % do we need safe_call?
144 %call_external_function('STRING_LENGTH',_,[A],Value,_,_,_WF) :- !, 'STRING_LENGTH'(A,Value).
145 % now the generic case:
146 call_external_function(F,Args,EvaluatedArgs,Value,Type,SpanInfo,WF) :-
147 (expects_waitflag(F)
148 -> E1=[WF],
149 (expects_spaninfo(F) -> E2=[SpanInfo|E1] ; E2=E1)
150 ; E1=[],
151 (expects_spaninfo(F) -> add_call_stack_to_span(SpanInfo,WF,S2), E2=[S2|E1] ; E2=E1)
152 ),
153 (expects_unevaluated_args(F) -> E3=[Args|E2] ; E3=E2),
154 (expects_type(F) -> E4=[Type|E3] ; E4=E3),
155 append(EvaluatedArgs,[Value|E4],AV),
156 % Check if there is better way to do this
157 Call =.. [F|AV],
158 % print('EXTERNAL FUNCTION CALL: '), print(F), print(' '), print(Call),nl,
159 % we could pass get_current_state_id(.) instead of unknown
160 profile_single_call(F,external_functions,unknown,safe_call(Call,SpanInfo,WF))
161 %, print(result(Value)),nl.
162 .
163
164 call_external_predicate(F,Args,EvaluatedArgs,LocalState,State,PREDRES,SpanInfo,WF) :-
165 (expects_waitflag(F)
166 -> E1=[WF],
167 (expects_spaninfo(F) -> E2=[SpanInfo|E1] ; E2=E1)
168 ; E1=[],
169 (expects_spaninfo(F) -> add_call_stack_to_span(SpanInfo,WF,S2), E2=[S2|E1] ; E2=E1)
170 ),
171 (expects_unevaluated_args(F) -> E3=[Args|E2] ; E3=E2),
172 (expects_state(F) -> E4=[LocalState,State|E3] ; E4=E3),
173 append(EvaluatedArgs,[PREDRES|E4],AV),
174 Call =.. [F|AV],
175 % print('EXTERNAL PREDICATE CALL: '), print(Call),nl, %%
176 profile_single_call(F,external_functions,unknown,safe_call(Call,SpanInfo,WF)).
177
178 call_external_substitution(FunName,Args,InState,OutState,Info,WF) :-
179 % TO DO: signal if substitution can be backtracked
180 get_wait_flag_for_subst(FunName,WF,Flag),
181 (does_not_modify_state(FunName) -> OutState=[] ; OutState = OutState2),
182 call_external_substitution2(Flag,FunName,Args,InState,OutState2,Info,WF).
183
184 get_wait_flag_for_subst(FunName,WF,Flag) :- perform_directly(FunName),!,
185 get_wait_flag1(WF,Flag). % ensure that precondition, ... have been evaluated
186 get_wait_flag_for_subst(FunName,WF,Flag) :- performs_io(FunName),!,
187 get_enumeration_finished_wait_flag(WF,Flag). % ensure that precondition, ... have been evaluated
188 % get_enumeration_starting_wait_flag(external(FunName),WF,Flag).
189 get_wait_flag_for_subst(FunName,WF,Flag) :- get_binary_choice_wait_flag(external(FunName),WF,Flag).
190
191 :- block call_external_substitution2(-,?,?,?,?,?,?).
192 call_external_substitution2(_,F,Args,InState,OutState,SpanInfo,WF) :-
193 (expects_waitflag(F) -> E1=[WF] ; E1=[]),
194 (expects_spaninfo(F) -> E2=[SpanInfo|E1] ; E2=E1),
195 append(Args,[InState,OutState|E2],AV),
196 Call =.. [F|AV],
197 % print('EXTERNAL SUBSTITUTION CALL: '), print(Call),nl, %%
198 profile_single_call(F,external_functions,unknown,safe_call(Call,SpanInfo,WF)).
199
200 safe_call(X,SpanInfo) :- safe_call(X,SpanInfo,no_wf_available).
201 safe_call(X,SpanInfo,WF) :-
202 catch(call(X), Exception, add_exception_error(Exception,X,SpanInfo,WF)).
203
204 safe_is(Context,X,Y,Span) :- safe_is(Context,X,Y,Span,no_wf_available).
205 safe_is(Context,X,Y,Span,WF) :- % print(safe_is(Context,X,Y)),nl,
206 catch(X is Y, Exception, add_exception_error(Exception,Context,Span,WF)). %, print(res(X)),nl.
207
208 add_exception_error(Exception,Context,Span,WF) :-
209 get_function_call_info(Context,SimplifiedContext),
210 add_exception_error2(Exception,SimplifiedContext,Span,WF),
211 (debug:debug_mode(on) -> tools_printing:print_term_summary(Context),nl ; true).
212
213 get_function_call_info(external_functions:X,Func) :- nonvar(X),!,functor(X,Func,_Arity).
214 get_function_call_info(M:X,M:Func) :- nonvar(X),!,functor(X,Func,_Arity).
215 get_function_call_info(X,X).
216
217 :- use_module(kernel_waitflags,[add_error_wf/5, add_warning_wf/5,add_wd_error_span/4]).
218 add_exception_error2(error(existence_error(procedure,external_functions:FUN),_),_X,SpanInfo,WF) :-
219 FUN = PRED/_Arity,
220 external_fun_type(PRED,_,ArgTypes), length(ArgTypes,Len), NA is Len-1, !,
221 ajoin(['EXTERNAL function exists but expects ',NA,' arguments:'],Msg),
222 add_error_wf(external_functions,Msg,FUN,SpanInfo,WF),
223 fail.
224 add_exception_error2(error(existence_error(procedure,external_functions:FUN),_),ExtFun,SpanInfo,WF) :-
225 FUN = ExtFun/_Arity, % the existence error is for the main external function being called
226 !,
227 add_error_wf(external_functions,
228 'EXTERNAL function does not exist (check that you have an up-to-date version of ProB):',FUN,SpanInfo,WF),
229 fail.
230 add_exception_error2(error(existence_error(procedure,MODULE:FUN),_),_X,SpanInfo,WF) :- !,
231 add_error_wf(external_functions,'Predicate called by EXTERNAL function does not exist (please report a bug):',MODULE:FUN,SpanInfo,WF),
232 fail.
233 add_exception_error2(error(undefined,ERR),X,SpanInfo,WF) :-
234 is_error(ERR,ExprTerm),!,
235 ajoin(['Arithmetic operation ',X,' not defined:'],Msg),
236 add_error_wf(external_functions,Msg,ExprTerm,SpanInfo,WF),
237 fail.
238 add_exception_error2(error(evaluation_error(undefined),ERR),X,SpanInfo,WF) :-
239 is_error(ERR,ExprTerm),!,
240 ajoin(['Arithmetic operation ',X,' not defined for given argument(s):'],Msg),
241 add_wd_error_span(Msg,ExprTerm,SpanInfo,WF).
242 add_exception_error2(error(evaluation_error(zero_divisor),ERR),X,SpanInfo,WF) :-
243 is_error(ERR,_),!,
244 % TO DO: use add_wd_error_set_result:
245 add_wd_error_span('Division by 0 in arithmetic operation: ',X,SpanInfo,WF).
246 add_exception_error2(error(existence_error(source_sink,File),Err2),X,SpanInfo,WF) :- !,
247 (arg(1,Err2,Call), get_file_open_mode(Call,append)
248 -> ajoin(['File does not exist and cannot be created (calling external function ',X,'):'],Msg)
249 ; arg(1,Err2,Call), get_file_open_mode(Call,write)
250 -> ajoin(['File cannot be created (calling external function ',X,'):'],Msg)
251 ; ajoin(['File does not exist (calling external function ',X,'):'],Msg)
252 ),
253 add_error_wf(external_functions,Msg,File,SpanInfo,WF),
254 fail.
255 add_exception_error2(error(consistency_error(Msg,_,format_arguments),_),_X,SpanInfo,WF) :- !,
256 add_error_wf(external_functions,'Illegal format string (see SICStus Prolog reference manual for syntax):',Msg,SpanInfo,WF),
257 fail.
258 add_exception_error2(enumeration_warning(A,B,C,D,E),X,SpanInfo,WF) :-
259 Exception = enumeration_warning(A,B,C,D,E),!,
260 debug_println(20,Exception),
261 get_predicate_name(X,Pred),
262 add_warning_wf(external_functions,'Enumeration warning occured while calling external function: ',Pred,SpanInfo,WF),
263 % or should we just print a message on the console ?
264 % or use
265 throw(Exception).
266 add_exception_error2(user_interrupt_signal,X,SpanInfo,WF) :- !,
267 get_predicate_name(X,Pred),
268 add_warning_wf(external_functions,'User Interrupt during external function evaluation: ',Pred,SpanInfo,WF),
269 throw(user_interrupt_signal).
270 add_exception_error2(Exception,X,SpanInfo,WF) :-
271 debug_println(20,Exception),
272 ajoin(['Exception occurred while calling external function ',X,':'],Msg),
273 add_error_wf(external_functions,Msg,Exception,SpanInfo,WF),
274 fail.
275
276 % get file open mode from a SICStus library call (e.g., that caused an existence_error exception)
277 get_file_open_mode(open(_File,Mode,_,_),Mode).
278 get_file_open_mode(open(_File,Mode,_),Mode).
279
280 get_predicate_name(Var,P) :- var(Var),!,P='_VAR_'.
281 get_predicate_name(external_functions:C,P) :- !, get_predicate_name(C,P).
282 get_predicate_name(Module:C,Module:P) :- !, get_predicate_name(C,P).
283 get_predicate_name(Call,F/P) :- functor(Call,F,P).
284
285 is_error(evaluation_error('is'(_,ExprTerm),2,_,_),ExprTerm).
286 is_error(domain_error('is'(_,ExprTerm),2,_,_),ExprTerm).
287
288 get_external_function_type(FunName,ArgTypes,ReturnType) :-
289 external_fun_type(FunName,TypeParas,AllTypes),
290 (member(TP,TypeParas),nonvar(TP)
291 -> add_internal_error('External function type parameter not a variable:,',
292 external_fun_type(FunName,TypeParas,AllTypes))
293 ; true
294 ),
295 append(ArgTypes,[ReturnType],AllTypes).
296
297 % STANDARD EXTERNAL FUNCTIONS
298
299
300 % -------------------------------
301
302
303 :- use_module(extrasrc(external_functions_reals)). % removed explicit imports for Spider
304 %:- use_module(extrasrc(external_functions_soft_floats)). % removed October 15th 2026
305 % is now in git@gitlab.cs.uni-duesseldorf.de:stups/prob/prob_prolog_extensions.git
306
307 :- use_module(probsrc(tools),[get_set_optional_prolog_flag/3]).
308 % load additional external functions that can be called
309 consult_new_external_functions(File) :-
310 add_message(external_functions,'Loading new external functions from: ',File),
311 get_set_optional_prolog_flag(redefine_warnings, Old, off),
312 get_set_optional_prolog_flag(single_var_warnings, Old2, off),
313 (catch(compile(File),
314 error(existence_error(_,_),_),
315 add_error_fail(external_functions,'Prolog module file with additional external functions does not exist:',File))
316 -> OK=true ; OK=false),
317 get_set_optional_prolog_flag(redefine_warnings, _, Old),
318 get_set_optional_prolog_flag(single_var_warnings, _, Old2),
319 OK=true.
320
321 expects_waitflag('STRING_TO_REAL').
322 external_fun_type('STRING_TO_REAL',[],[string,real]).
323
324 expects_waitflag('RADD').
325 external_fun_type('RADD',[],[real,real,real]).
326 expects_waitflag('RSUB').
327 external_fun_type('RSUB',[],[real,real,real]).
328 expects_waitflag('RMUL').
329 external_fun_type('RMUL',[],[real,real,real]).
330 expects_waitflag('RDIV').
331 expects_spaninfo('RDIV').
332 external_fun_type('RDIV',[],[real,real,real]).
333 external_fun_has_wd_condition('RDIV').
334 expects_waitflag('RINV').
335 expects_spaninfo('RINV').
336 external_fun_type('RINV',[],[real,real]).
337 external_fun_has_wd_condition('RINV').
338
339 external_fun_type('RPI',[],[real]).
340 external_fun_type('RZERO',[],[real]).
341 external_fun_type('RONE',[],[real]).
342 external_fun_type('REULER',[],[real]).
343 external_fun_type('REPSILON',[],[real]).
344 external_fun_type('RMAXFLOAT',[],[real]).
345
346 external_fun_type('RSIN',[],[real,real]).
347 expects_waitflag('RSIN').
348 external_fun_type('RCOS',[],[real,real]).
349 expects_waitflag('RCOS').
350 external_fun_type('RTAN',[],[real,real]).
351 expects_waitflag('RTAN').
352 external_fun_type('RCOT',[],[real,real]).
353 expects_waitflag('RCOT').
354 external_fun_type('RSINH',[],[real,real]).
355 expects_waitflag('RSINH').
356 external_fun_type('RCOSH',[],[real,real]).
357 expects_waitflag('RCOSH').
358 external_fun_type('RTANH',[],[real,real]).
359 expects_waitflag('RTANH').
360 external_fun_type('RCOTH',[],[real,real]).
361 expects_waitflag('RCOTH').
362 external_fun_type('RASIN',[],[real,real]).
363 expects_waitflag('RASIN').
364 external_fun_type('RACOS',[],[real,real]).
365 expects_waitflag('RACOS').
366 external_fun_type('RATAN',[],[real,real]).
367 expects_waitflag('RATAN').
368 external_fun_type('RACOT',[],[real,real]).
369 expects_waitflag('RACOT').
370 external_fun_type('RASINH',[],[real,real]).
371 expects_waitflag('RASINH').
372 external_fun_type('RACOSH',[],[real,real]).
373 expects_waitflag('RACOSH').
374 external_fun_type('RATANH',[],[real,real]).
375 expects_waitflag('RATANH').
376 external_fun_type('RACOTH',[],[real,real]).
377 expects_waitflag('RACOTH').
378 external_fun_type('RATAN2',[],[real,real,real]).
379 expects_waitflag('RATAN2').
380 expects_spaninfo('RATAN2').
381 external_fun_type('RHYPOT',[],[real,real,real]).
382 expects_waitflag('RHYPOT').
383 expects_spaninfo('RHYPOT').
384 external_fun_type('RADIANS',[],[real,real]).
385 expects_waitflag('RADIANS').
386 expects_spaninfo('RADIANS').
387 external_fun_type('DEGREE',[],[real,real]).
388 expects_waitflag('DEGREE').
389 expects_spaninfo('DEGREE').
390
391
392 external_fun_type('RUMINUS',[],[real,real]).
393 expects_waitflag('RUMINUS').
394 external_fun_type('REXP',[],[real,real]).
395 expects_waitflag('REXP').
396 external_fun_type('RLOGe',[],[real,real]).
397 expects_waitflag('RLOGe').
398 expects_spaninfo('RLOGe').
399 external_fun_has_wd_condition('RLOGe').
400 external_fun_type('RSQRT',[],[real,real]).
401 expects_waitflag('RSQRT').
402 expects_spaninfo('RSQRT').
403 external_fun_has_wd_condition('RSQRT'). % for negative numbers obviously
404 external_fun_type('RABS',[],[real,real]).
405 expects_waitflag('RABS').
406 external_fun_type('ROUND',[],[real,integer]).
407 expects_waitflag('ROUND').
408 external_fun_type('RSIGN',[],[real,real]).
409 expects_waitflag('RSIGN').
410 external_fun_type('RINTEGER',[],[real,real]).
411 expects_waitflag('RINTEGER').
412 external_fun_type('RFRACTION',[],[real,real]).
413 expects_waitflag('RFRACTION').
414
415 expects_waitflag('RMAX').
416 expects_spaninfo('RMAX').
417 external_fun_type('RMAX',[],[real,real,real]).
418 expects_waitflag('RMIN').
419 expects_spaninfo('RMIN').
420 external_fun_type('RMIN',[],[real,real,real]).
421 expects_spaninfo('RPOW').
422 expects_waitflag('RPOW').
423 external_fun_type('RPOW',[],[real,real,real]).
424 external_fun_has_wd_condition('RPOW'). % for negative numbers, e.g., RPOW(-1.0,1.1) or RPOW(-1.0,0.5)
425 expects_spaninfo('RDECIMAL').
426 expects_waitflag('RDECIMAL').
427 external_fun_type('RDECIMAL',[],[integer,integer,real]).
428 expects_waitflag('RLOG').
429 expects_spaninfo('RLOG').
430 external_fun_type('RLOG',[],[real,real,real]).
431 external_fun_has_wd_condition('RLOG').
432
433 expects_waitflag('RLT').
434 external_fun_type('RLT',[],[real,real,boolean]).
435 expects_waitflag('REQ').
436 external_fun_type('REQ',[],[real,real,boolean]).
437 expects_waitflag('RNEQ').
438 external_fun_type('RNEQ',[],[real,real,boolean]).
439 expects_waitflag('RLEQ').
440 external_fun_type('RLEQ',[],[real,real,boolean]).
441 expects_waitflag('RGT').
442 external_fun_type('RGT',[],[real,real,boolean]).
443 expects_waitflag('RGEQ').
444 external_fun_type('RGEQ',[],[real,real,boolean]).
445 expects_waitflag('RMAXIMUM').
446 expects_spaninfo('RMAXIMUM').
447 external_fun_type('RMAXIMUM',[],[set(real),real]).
448 external_fun_has_wd_condition('RMAXIMUM'). % empty set or unbounded set
449 expects_waitflag('RMINIMUM').
450 expects_spaninfo('RMINIMUM').
451 external_fun_type('RMINIMUM',[],[set(real),real]).
452 external_fun_has_wd_condition('RMINIMUM'). % empty set or unbounded set
453
454 external_fun_type('RNEXT',[],[real,real]).
455 external_fun_type('RPREV',[],[real,real]).
456
457
458
459 % -------------------------------
460
461 :- use_module(extrasrc(external_functions_svg)). %, [svg_points/4, svg_train/8, svg_car/8, svg_axis/7, svg_set_polygon/7]).
462
463 expects_waitflag('svg_points').
464 expects_spaninfo('svg_points').
465 external_fun_type('svg_points',[T1,T2],[seq(couple(T1,T2)),string]). % T1, T2 should be numbers
466
467 expects_waitflag('svg_train').
468 expects_spaninfo('svg_train').
469 external_fun_type('svg_train',[T1,T2],[T1,T1,T2,T2,T2,string]). % T1, T2 should be numbers
470 expects_waitflag('svg_car').
471 expects_spaninfo('svg_car').
472 external_fun_type('svg_car',[T1,T2],[T1,T1,T2,T2,T2,string]). % T1, T2 should be numbers
473
474 expects_waitflag('svg_axis').
475 expects_spaninfo('svg_axis').
476 external_fun_type('svg_axis',[T1,T2],[set(T1),T2,T2,T2,string]). % T1, T2 should be numbers
477
478 expects_waitflag('svg_set_polygon').
479 expects_spaninfo('svg_set_polygon').
480 external_fun_type('svg_set_polygon',[T2],[set(integer),T2,T2,T2,string]). % T2 should be number type
481
482 expects_waitflag('svg_set_polygon_auto').
483 expects_spaninfo('svg_set_polygon_auto').
484 external_fun_type('svg_set_polygon_auto',[T2],[set(integer),T2,T2,string]). % T2 should be number type
485
486 expects_waitflag('svg_dasharray_for_intervals').
487 expects_spaninfo('svg_dasharray_for_intervals').
488 external_fun_type('svg_dasharray_for_intervals',[T1,T2],[set(couple(T1,T2)),string]). % T1, T2 should be numbers
489
490 expects_waitflag('svg_set_dasharray').
491 expects_spaninfo('svg_set_dasharray').
492 external_fun_type('svg_set_dasharray',[],[set(integer),string]).
493
494 % -------------------------------
495
496 % MATHEMATICAL FUNCTIONS
497
498 external_fun_type('COS',[],[integer,integer]).
499 :- public 'COS'/2.
500 :- block 'COS'(-,?). % redundant; we could add CLPFD constraints for R
501 'COS'(int(X),int(R)) :- cos2(100,X,R,unknown).
502 external_fun_type('COSx',[],[integer,integer,integer]).
503 expects_spaninfo('COSx').
504 :- public 'COSx'/4.
505 :- block 'COSx'(-,?,?,?),'COSx'(?,-,?,?).
506 'COSx'(int(PrecisionMultiplier),int(X),int(R),Span) :- cos2(PrecisionMultiplier,X,R,Span).
507 :- block cos2(-,?,?,?),cos2(?,-,?,?).
508 cos2(Multiplier,X,R,Span) :- safe_is('COSx',R,round(Multiplier*cos(X/Multiplier)),Span).
509
510 external_fun_type('SIN',[],[integer,integer]).
511 :- public 'SIN'/2.
512 :- block 'SIN'(-,?). % redundant; we could add CLPFD constraints for R
513 'SIN'(int(X),int(R)) :- sin2(100,X,R,unknown).
514 external_fun_type('SINx',[],[integer,integer,integer]).
515 expects_spaninfo('SINx').
516 :- public 'SINx'/4.
517 :- block 'SINx'(-,?,?,?),'SINx'(?,-,?,?).
518 'SINx'(int(PrecisionMultiplier),int(X),int(R),Span) :- %print('SINx'(PrecisionMultiplier,X,R)),nl,
519 sin2(PrecisionMultiplier,X,R,Span).
520 :- block sin2(-,?,?,?),sin2(?,-,?,?).
521 sin2(Multiplier,X,R,Span) :- safe_is('SINx',R,round(Multiplier*sin(X/Multiplier)),Span).
522
523 external_fun_type('TAN',[],[integer,integer]).
524 :- public 'TAN'/2.
525 :- block 'TAN'(-,?). % redundant; we could add CLPFD constraints for R
526 'TAN'(int(X),int(R)) :- tan2(100,X,R,unknown).
527 external_fun_type('TANx',[],[integer,integer,integer]).
528 expects_spaninfo('TANx').
529 :- public 'TANx'/4.
530 :- block 'TANx'(-,?,?,?),'TANx'(?,-,?,?).
531 'TANx'(int(PrecisionMultiplier),int(X),int(R),Span) :- tan2(PrecisionMultiplier,X,R,Span).
532 :- block tan2(?,-,?,?),tan2(-,?,?,?).
533 tan2(Multiplier,X,R,Span) :- safe_is('TANx',R,round(Multiplier*tan(X/Multiplier)),Span).
534
535
536 external_fun_type('PROLOG_FUN',[],[string,integer,integer,integer]).
537 external_fun_has_wd_condition('PROLOG_FUN').
538 expects_spaninfo('PROLOG_FUN').
539 :- public 'PROLOG_FUN'/5.
540 'PROLOG_FUN'(string(Function),int(PrecisionMultiplier),int(Argument),int(Result),Span) :-
541 prolog_fun2(Function,PrecisionMultiplier,Argument,Result,Span).
542 % Function can be:
543 % sin, cos, tan, cot, sinh, cosh, tanh, asin, acos, atan, acot, asinh, acosh, atanh, acoth, sqrt, log, exp
544 :- block prolog_fun2(?,-,?,?,?),prolog_fun2(-,?,?,?,?), prolog_fun2(?,?,-,?,?).
545 prolog_fun2(Function,Multiplier,X,R,Span) :-
546 E =.. [Function,X/Multiplier],
547 safe_is(Function,R,round(Multiplier*E),Span).
548
549 external_fun_has_wd_condition('LOGx'). % PrecisionMultiplier>0, Base>0, X>0
550 expects_spaninfo('LOGx').
551 external_fun_type('LOGx',[],[integer,integer,integer,integer]).
552 :- public 'LOGx'/5.
553 :- block 'LOGx'(-,?,?,?,?),'LOGx'(?,-,?,?,?), 'LOGx'(?,?,-,?,?).
554 'LOGx'(int(PrecisionMultiplier),int(Base),int(X),int(R),Span) :-
555 log2(PrecisionMultiplier,Base,X,R,Span).
556 :- block log2(?,-,?,?,?),log2(-,?,?,?,?),log2(?,?,-,?,?).
557 log2(Multiplier,Base,X,R,Span) :-
558 logx_internal(Multiplier,Base,X,R,Span).
559
560 :- use_module(tools_portability, [check_arithmetic_function/1]).
561 :- if(check_arithmetic_function(log(2, 4))).
562 % Native log(Base, Power) function is available - use it.
563 logx_internal(Multiplier,Base,X,R,Span) :-
564 safe_is('LOGx',R,round(Multiplier*log(Base/Multiplier,X/Multiplier)),Span).
565 :- else.
566 % No native log(Base, Power) support, so construct it using natural logarithms.
567 logx_internal(Multiplier,Base,X,R,Span) :-
568 safe_is('LOGx',R,round(Multiplier*(log(X/Multiplier)/log(Base/Multiplier))),Span).
569 :- endif.
570
571 :- use_module(clpfd_interface,[clpfd_gcd/3, clpfd_lcm/3, clpfd_abs/2, clpfd_sign/2]).
572 external_fun_type('GCD',[],[integer,integer,integer]).
573 :- public 'GCD'/3.
574 :- block 'GCD'(-,-,-).
575 'GCD'(int(X),int(Y),int(R)) :-
576 clpfd_gcd(X,Y,R).
577
578 % least / smallest common multiple
579 external_fun_type('LCM',[],[integer,integer,integer]).
580 :- public 'LCM'/3.
581 :- block 'LCM'(-,-,-).
582 'LCM'(int(X),int(Y),int(R)) :- clpfd_lcm(X,Y,R).
583
584 external_fun_type('ABS',[],[integer,integer]).
585 external_fun_can_be_inverted('ABS'). % there are two possible input values for an output value
586 :- public 'ABS'/2.
587 :- block 'ABS'(-,-). % do we need this ??
588 'ABS'(int(X),int(R)) :-
589 clpfd_abs(X,R).
590
591 external_fun_type('SIGN',[],[integer,integer]).
592 :- public 'SIGN'/2.
593 :- block 'SIGN'(-,-).
594 'SIGN'(int(X),int(R)) :-
595 clpfd_sign(X,R).
596
597
598 % TLA style floored division
599 external_fun_has_wd_condition('FDIV').
600 expects_spaninfo('FDIV').
601 expects_waitflag('FDIV').
602 external_fun_type('FDIV',[],[integer,integer,integer]).
603 :- public 'FDIV'/5.
604 :- block 'FDIV'(-,-,-,?,?).
605 'FDIV'(X,Y,Z,Span,WF) :-
606 kernel_objects:floored_division(X,Y,Z,Span,WF).
607
608 % ceiling division
609 external_fun_has_wd_condition('CDIV').
610 expects_spaninfo('CDIV').
611 expects_waitflag('CDIV').
612 external_fun_type('CDIV',[],[integer,integer,integer]).
613 :- public 'CDIV'/5.
614 :- block 'CDIV'(-,?,?,?,?),'CDIV'(?,-,?,?,?).
615 'CDIV'(int(X),int(Y),Res,Span,WF) :-
616 ceiling_division(X,Y,Res,Span,WF).
617
618 :- block ceiling_division(-,?,?,?,?),ceiling_division(?,-,?,?,?).
619 ceiling_division(X,Y,_Res,Span,WF) :- Y=0,!,
620 add_wd_error_span('Ceiling division by zero:',X,Span,WF).
621 ceiling_division(X,Y,Res,_Span,_WF) :-
622 X mod Y =:= 0,!,
623 XY is X//Y, Res = int(XY).
624 ceiling_division(X,Y,Res,Span,WF) :-
625 kernel_objects:floored_division(int(X),int(Y),int(Z),Span,WF),
626 Z1 is 1 + Z,
627 Res = int(Z1).
628
629 external_fun_has_wd_condition('SQRT').
630 expects_spaninfo('SQRT').
631 expects_waitflag('SQRT').
632 external_fun_type('SQRT',[],[integer,integer]).
633 %external_fun_can_be_inverted('SQRT'). % TODO : comment in after fixing TODOs below
634 :- public 'SQRT'/4.
635 :- block 'SQRT'(-,?,?,?).
636 'SQRT'(int(X),R,Span,WF) :-
637 positive_integer_sqrt(X,R,Span,WF). % TO DO: maybe do CLPFD propagation?
638 % TODO: backwards propagation from R to X; if X=2 -> X=+/-4,5,6,7,8
639
640 :- block positive_integer_sqrt(-,?,?,?).
641 positive_integer_sqrt(X,_,Span,WF) :- X<0,!,
642 add_wd_error_span('Trying to compute square root of negative number:',X,Span,WF).
643 positive_integer_sqrt(X,Res,Span,_WF) :-
644 Candidate is floor(sqrt(X)), % compute using floating number function
645 (Candidate*Candidate =< X
646 -> C1 is Candidate+1,
647 (C1*C1 > X
648 -> Res = int(Candidate)
649 ; (C1+1)*(C1+1) > X
650 -> Res = int(C1)
651 ; % SQR is (C1+1)^2, Delta is X-SQR, write(sqr_candidate(C1,SQR,X,Delta)),nl,
652 % >>> SQRT(9999911144210000019*9999911144210000019+2)
653 add_error(external_functions,'Rounding error (2) while computing SQRT of: ',X,Span),
654 Res = int(C1)
655 )
656 ; add_error(external_functions,'Rounding error (1) while computing SQRT of: ',X,Span),
657 % SQRT(999991114421000001*999991114421000001+2)
658 Res = int(Candidate)
659 ).
660
661 external_fun_type('MSB',[],[integer,integer]).
662 expects_spaninfo('MSB').
663 :- public 'MSB'/3.
664 :- block 'MSB'(-,?,?).
665 'MSB'(int(X),int(R),Span) :- msb2(X,R,Span). % most significant bit
666 :- block msb2(-,?,?).
667 msb2(X,R,Span) :- safe_is('MSB',R,msb(X),Span). % TO DO: could be made reversible by propagating constraint if R known
668
669
670 external_fun_type('FACTORIAL',[],[integer,integer]).
671 expects_spaninfo('FACTORIAL').
672 expects_waitflag('FACTORIAL').
673 :- public 'FACTORIAL'/4.
674 :- block 'FACTORIAL'(-,?,?,?).
675 'FACTORIAL'(int(X),int(R),Span,WF) :- fact(X,R,Span,WF). % most significant bit
676 :- block fact(-,?,?,?).
677 fact(X,_,Span,WF) :- X<0,!, add_wd_error_span('FACTORIAL applied to negative number: ',X,Span,WF).
678 fact(X,_,Span,WF) :- X>10000,!, add_wd_error_span('FACTORIAL overflow, argument too large: ',X,Span,WF).
679 fact(X,Res,_,_) :- fact_acc(X,1,Res).
680
681 fact_acc(0,Acc,Res) :- !,Res=Acc.
682 fact_acc(N,Acc,Res) :- NAcc is Acc*N,
683 N1 is N-1, fact_acc(N1,NAcc,Res).
684
685 % TODO: fact_k, choose_nk
686
687 % BITWISE OPERATORS
688 external_fun_type('BNOT',[],[integer,integer]).
689 external_fun_can_be_inverted('BNOT').
690 expects_spaninfo('BNOT').
691 :- public 'BNOT'/3.
692 :- if((current_prolog_flag(dialect, sicstus),
693 current_prolog_flag(version_data, sicstus(4,VN,_,_,_)), VN>=9)).
694 :- block 'BNOT'(-,-,?).
695 'BNOT'(int(X),int(R),Span) :-
696 (preferences:preference(use_clpfd_solver,true)
697 -> clpfd_eq_expr(R,'\\'(X))
698 ; bitwise_not(X,R,Span)
699 ).
700 :- else.
701 'BNOT'(int(X),int(R),Span) :- bitwise_not(X,R,Span).
702 :- endif.
703 :- block bitwise_not(-,-,?).
704 bitwise_not(X,R,Span) :- number(X),!,safe_is('BNOT',R,\(X),Span).
705 bitwise_not(X,R,Span) :- safe_is('BNOT',X,\(R),Span).
706
707 :- use_module(clpfd_interface,[clpfd_eq_expr/2]).
708
709 external_fun_type('BAND',[],[integer,integer,integer]).
710 :- public 'BAND'/3.
711 :- if((current_prolog_flag(dialect, sicstus),
712 current_prolog_flag(version_data, sicstus(4,VN,_,_,_)), VN>=9)).
713 :- block 'BAND'(-,-,-).
714 'BAND'(int(X),int(Y),int(R)) :-
715 (preferences:preference(use_clpfd_solver,true)
716 -> clpfd_eq_expr(R,'/\\'(X,Y))
717 ; bitwise_and(X,Y,R)).
718 :- else.
719 :- block 'BAND'(-,?,?),'BAND'(?,-,?).
720 'BAND'(int(X),int(Y),int(R)) :- bitwise_and(X,Y,R).
721 :- endif.
722 :- block bitwise_and(?,-,?),bitwise_and(-,?,?).
723 bitwise_and(X,Y,R) :- R is X /\ Y. % we could do some early consistency checking, e.g., when X and R known
724
725 external_fun_type('BOR',[],[integer,integer,integer]).
726 :- public 'BOR'/3.
727 :- if((current_prolog_flag(dialect, sicstus),
728 current_prolog_flag(version_data, sicstus(4,VN,_,_,_)), VN>=9)).
729 :- block 'BOR'(-,-,-).
730 'BOR'(int(X),int(Y),int(R)) :-
731 (preferences:preference(use_clpfd_solver,true)
732 -> clpfd_eq_expr(R,'\\/'(X,Y))
733 ; bitwise_or(X,Y,R)).
734 :- else.
735 :- block 'BOR'(-,?,?),'BOR'(?,-,?).
736 'BOR'(int(X),int(Y),int(R)) :- bitwise_or(X,Y,R).
737 :- block bitwise_or(?,-,?),bitwise_or(-,?,?).
738 :- endif.
739 bitwise_or(X,Y,R) :- R is X \/ Y. % we could do some early consistency checking, e.g., when X and R known
740
741 external_fun_type('BXOR',[],[integer,integer,integer]).
742 external_fun_can_be_inverted('BXOR').
743 :- public 'BXOR'/3.
744 :- if((current_prolog_flag(dialect, sicstus),
745 current_prolog_flag(version_data, sicstus(4,VN,_,_,_)), VN>=9)).
746 :- block 'BXOR'(-,-,-).
747 'BXOR'(int(X),int(Y),int(R)) :-
748 (preferences:preference(use_clpfd_solver,true)
749 -> clpfd_eq_expr(R,xor(X,Y))
750 ; bitwise_xor(X,Y,R)).
751 :- else.
752 :- block 'BXOR'(-,-,?),'BXOR'(?,-,-),'BXOR'(-,?,-).
753 'BXOR'(int(X),int(Y),int(R)) :- bitwise_xor(X,Y,R).
754 :- endif.
755 :- block bitwise_xor(-,-,?),bitwise_xor(?,-,-),bitwise_xor(-,?,-).
756 % DO WE NEED TO KNOW THE sizes of X,Y,R ?
757 bitwise_xor(X,Y,R) :- var(X),!, X is xor(R,Y).
758 bitwise_xor(X,Y,R) :- var(Y),!, Y is xor(X,R).
759 bitwise_xor(X,Y,R) :- R is xor(X,Y).
760
761 % TO DO: do some clpfd propagations ? X:0..N & Y:0..M -> BAND(X,Y) : 0..min(N,M)
762
763 % EXTERNAL_FUNCTION_BITS == INTEGER --> seq(INTEGER)
764 % BITS(x) == [0]
765 external_fun_type('BLSHIFT',[],[integer,integer,integer]).
766 :- public 'BLSHIFT'/3.
767 :- block 'BLSHIFT'(-,?,?),'BLSHIFT'(?,-,?).
768 'BLSHIFT'(int(X),int(Y),int(R)) :- bitwise_left_shift(X,Y,R).
769 :- block bitwise_left_shift(?,-,?),bitwise_left_shift(-,?,?).
770 bitwise_left_shift(X,Y,R) :- R is X << Y.
771 external_fun_type('BRSHIFT',[],[integer,integer,integer]).
772 :- public 'BRSHIFT'/3.
773 :- block 'BRSHIFT'(-,?,?),'BRSHIFT'(?,-,?).
774 'BRSHIFT'(int(X),int(Y),int(R)) :- bitwise_right_shift(X,Y,R).
775 :- block bitwise_right_shift(?,-,?),bitwise_right_shift(-,?,?).
776 bitwise_right_shift(X,Y,R) :- R is X >> Y.
777
778 :- assert_must_succeed(( external_functions:call_external_function('BITS',[12],[int(12)],R,integer,unknown,_WF),
779 equal_object(R,[(int(1),int(1)),(int(2),int(1)),(int(3),int(0)),(int(4),int(0))]) )).
780
781 external_fun_type('BITS',[],[integer,seq(integer)]).
782 :- public 'BITS'/2.
783 :- block 'BITS'(-,?).
784 'BITS'(int(X),Res) :- convert_to_bits(X,Res).
785
786 :- block convert_to_bits(-,?).
787 convert_to_bits(0,Res) :- !, convert_list_to_seq([int(0)],Res).
788 convert_to_bits(N,Res) :- convert_to_bits(N,[],List),
789 convert_list_to_seq(List,Res).
790 convert_to_bits(0,Acc,Res) :- !, Res=Acc.
791 convert_to_bits(X,Acc,Res) :- XM2 is X mod 2, XD2 is X // 2,
792 convert_to_bits(XD2,[int(XM2)|Acc],Res).
793 % TO DO: maybe do some constraint propagation from Result to number, or use CLP(FD) size info to infer size of sequence?
794
795 % -------------------------------
796
797 % THE CHOOSE operator (for TLA, recursive functions over sets,...)
798 % or choice operator from Abrial Book, page 60ff
799
800 :- use_module(kernel_reals,[is_interval_closure_or_realset/3, is_real/2]).
801 :- use_module(kernel_waitflags,[add_wd_error_span/4]).
802 :- use_module(b_global_sets,[b_integer_or_real_or_string_set/1]).
803 external_fun_type('CHOOSE',[X],[set(X),X]).
804 external_fun_has_wd_condition('CHOOSE').
805 expects_waitflag('CHOOSE').
806 expects_spaninfo('CHOOSE').
807 :- public 'CHOOSE'/4.
808 :- block 'CHOOSE'(-,?,?,?).
809 'CHOOSE'([],_,Span,WF) :- !,
810 add_wd_error_span('CHOOSE applied to empty set: ',[],Span,WF).
811 'CHOOSE'(CS,Res,_,_) :- is_interval_closure_or_integerset(CS,Low,Up), % TODO: also support reals
812 !,
813 choose_interval(Low,Up,H),Res=int(H).
814 'CHOOSE'([H|T],C,_Span,WF) :- T==[], !, kernel_objects:equal_object_optimized_wf(C,H,'CHOOSE',WF).
815 'CHOOSE'([H|T],C,Span,WF) :- !,
816 ground_value_check([H|T],Gr),
817 when(nonvar(Gr),
818 (convert_to_avl([H|T],AVL) -> 'CHOOSE'(AVL,C,Span,WF)
819 ; add_wd_error_span('Cannot determine minimum element for CHOOSE: ',[H|T],Span,WF),
820 kernel_objects:equal_object_wf(C,H,WF))
821 ).
822 'CHOOSE'(avl_set(A),H,_,WF) :- !, avl_min(A,Min), kernel_objects:equal_object_wf(H,Min,WF).
823 'CHOOSE'(global_set(GS),H,_,_) :- \+ b_integer_or_real_or_string_set(GS), !,
824 H = fd(1,GS). % assume GS not empty, integer sets covered above
825 'CHOOSE'(global_set('STRING'),H,_,_) :- !, H = string(''). % return empty string
826 'CHOOSE'(freetype(ID),H,Span,WF) :- !,
827 (kernel_freetypes:enumerate_freetype_wf(basic,FV,freetype(ID),WF)
828 -> kernel_objects:equal_object_wf(FV,H,WF)
829 ; add_internal_error('Could not generate freetype element: ','CHOOSE'(freetype(ID),H,Span,WF))).
830 'CHOOSE'(CS,H,Span,WF) :- custom_explicit_sets:is_cartesian_product_closure(CS,Set1,Set2),!,
831 'CHOOSE'(Set1,H1,Span,WF),
832 'CHOOSE'(Set2,H2,Span,WF),
833 kernel_objects:equal_object_wf(H,(H1,H2),WF).
834 'CHOOSE'(CS,Res,_,_) :- is_interval_closure_or_realset(CS,Low,Up), % TODO: also support reals
835 !,
836 choose_interval(Low,Up,H),
837 (H=0 -> is_real(Res,0.0) ; is_real(Res,H)).
838 'CHOOSE'(CS,H,Span,WF) :- is_custom_explicit_set(CS),
839 custom_explicit_sets:expand_custom_set_wf(CS,ER,'CHOOSE',WF),
840 'CHOOSE'(ER,H,Span,WF).
841
842 % choose a value from an interval; can be open interval and can be a real interval
843 :- block choose_interval(-,?,?).
844 choose_interval(Low,_Up,H) :- number(Low),!,H=Low.
845 choose_interval(_Low,Up,H) :- choose_interval2(Up,H). % lower-bound is minus infinity
846 :- block choose_interval2(-,?).
847 choose_interval2(Up,H) :- number(Up),!,H=Up. % for those intervals we choose Up
848 choose_interval2(_,0). % we have INTEGER or something equivalent with minus_inf,inf; simply choose 0
849
850 :- use_module(kernel_objects,[singleton_set_element/4, singleton_set_element_wd/4]).
851 external_fun_type('MU',[X],[set(X),X]).
852 external_fun_has_wd_condition('MU').
853 expects_waitflag('MU').
854 expects_spaninfo('MU').
855 :- public 'MU'/4.
856 'MU'(Set,Res,Span,WF) :-
857 singleton_set_element(Set,Res,Span,WF).
858
859 external_fun_type('MU_WD',[X],[set(X),X]).
860 external_fun_has_wd_condition('MU_WD').
861 expects_waitflag('MU_WD').
862 expects_spaninfo('MU_WD').
863 % a version of MU which propagates more strongly from result to input
864 % but may thus fail to generate WD errors; can be used for stronger constraint propagation if MU is known to be WD
865 :- public 'MU_WD'/4.
866 'MU_WD'(Set,Res,Span,WF) :-
867 singleton_set_element_wd(Set,Res,Span,WF).
868
869
870 % choose n elements from a set
871 % will currently fail without good error message when we cannot find enough solutions
872 external_fun_type('CHOOSE_n',[X],[integer,set(X),set(X)]).
873 external_fun_has_wd_condition('CHOOSE_n').
874 expects_waitflag('CHOOSE_n').
875 expects_spaninfo('CHOOSE_n').
876 expects_type('CHOOSE_n').
877 :- public 'CHOOSE_n'/6.
878 :- block 'CHOOSE_n'(-,?,?,?,?,?).
879 'CHOOSE_n'(int(Nr),Set,Result,set(Type),Span,WF) :-
880 ground_value_check(Set,GrSet),
881 choose_n_aux(Nr,GrSet,Set,Result,Type,Span,WF).
882
883 :- block 'choose_n_aux'(-,?,?,?,?,?,?),'choose_n_aux'(?,-,?,?,?,?,?).
884 choose_n_aux(Nr,_,Set,Result,Type,Span,WF) :-
885 generate_elements(Nr,Set,[],List,Type,Span,WF),
886 equal_object_wf(List,Result,WF).
887
888 % TODO: disable enumeration warnings when generating new elements
889 generate_elements(0,_,_,Res,_,_,_) :- !, Res=[].
890 generate_elements(Nr,Set,Acc,[H|T],Type,Span,WF) :-
891 init_wait_flags_with_call_stack(WF2,[operation_call('CHOOSE_n',[int(Nr)],Span)]),
892 check_element_of_wf(H,Set,WF2),
893 not_element_of_wf(H,Acc,WF2),
894 b_enumerate:b_enumerate_typed_values([H],[Type],WF2),
895 ground_wait_flags(WF2),
896 add_element_wf(H,Acc,Acc2,no_wf_available),
897 !,
898 N1 is Nr-1,
899 generate_elements(N1,Set,Acc2,T,Type,Span,WF).
900
901
902 % -----------------
903
904 % sort a set and generate a sequence
905 % external_fun_has_wd_condition('SORT'). SORT generates virtual time-out for infinite sets; but has no WD-condition
906 % important to remove wd_condition fact to allow b_compiler to pre-compute calls to SORT
907 expects_waitflag('SORT').
908 expects_spaninfo('SORT').
909 external_fun_type('SORT',[X],[set(X),seq(X)]).
910 :- public 'SORT'/4.
911 :- block 'SORT'(-,?,?,?).
912 'SORT'([],Res,_Span,_WF) :- !, Res=[].
913 'SORT'(CS,Res,_,WF) :- custom_explicit_sets:is_custom_explicit_set(CS),!,
914 expand_custom_set_to_list_wf(CS,ER,Done,'SORT',WF),
915 sort_aux(Done,ER,Res,WF).
916 'SORT'([H|T],Res,_,WF) :-
917 when(ground([H|T]),
918 (maplist(convert_to_avl_if_possible,[H|T],List),
919 sort(List,SList),sort_aux(done,SList,Res,WF))).
920
921 convert_to_avl_if_possible(H,Res) :- convert_to_avl(H,CH),!,Res=CH.
922 convert_to_avl_if_possible(H,H) :-
923 add_warning(external_functions,'Cannot guarantee order when sorting:',H).
924
925 :- block sort_aux(-,?,?,?).
926 sort_aux(_,ER,Res,_WF) :- convert_list_to_seq(ER,Res).
927
928 % construct a B sequence from a Prolog list
929 convert_list_to_seq(ER,Res) :- convert_list_to_seq(ER,1,Seq), equal_object_optimized(Seq,Res).
930
931 convert_list_to_seq([],_,[]).
932 convert_list_to_seq([H|T],N,[(int(N),H)|CT]) :- N1 is N+1, convert_list_to_seq(T,N1,CT).
933
934 % :- use_module(library(samsort),[samsort/3]).
935 % TO DO: version of SORT with samsort/3 and user provided sorting predicate
936
937 % Z Compaction / squash operator to fill up gaps in sequence
938 external_fun_has_wd_condition('SQUASH'). % needs to be a function
939 expects_waitflag('SQUASH').
940 external_fun_type('SQUASH',[X],[set(couple(integer,X)),seq(X)]). % input not necessarily proper sequence
941
942 :- use_module(kernel_z,[compaction/3]).
943 :- public 'SQUASH'/3.
944 'SQUASH'(Sequence,Value,WF) :- compaction(Sequence,Value,WF).
945
946 external_fun_has_wd_condition('REPLACE'). % needs to be a function
947 expects_waitflag('REPLACE').
948 expects_spaninfo('REPLACE').
949 external_fun_type('REPLACE',[X],[seq(X),seq(X),seq(X),set(seq(X))]).
950 % Replace a pattern by another pattern within a sequence
951 % Currently it also performs a squashing of its arguments and does not check if its argument is a function or sequence.
952 % REPLACE([a],[b],[a,c,a]) = { [b,c,a], [a,c,b] };
953 % REPLACE([a],[],[a,c,a]) = { [c,a], [a,c] };
954 % REPLACE([a,a],[],[a,c,a]) = { }
955 :- public 'REPLACE'/6.
956 :- block 'REPLACE'(-,?,?,?,?,?), 'REPLACE'(?,-,?,?,?,?), 'REPLACE'(?,?,-,?,?,?).
957 'REPLACE'(Pat,Replacement,InSequence,Res,Span,_WF) :-
958 ground_value_check((Pat,Replacement,InSequence),Gr),
959 replace_pat_aux(Gr,Pat,Replacement,InSequence,Res,Span).
960 :- block replace_pat_aux(-,?,?,?,?,?).
961 replace_pat_aux(_,Pat,Replacement,InSequence,Res,Span) :-
962 convert_to_sorted_seq_list(Pat,PL,Span),
963 convert_to_sorted_seq_list(Replacement,RL,Span),
964 convert_to_sorted_seq_list(InSequence,SL,Span),
965 findall(ResList,replace_pattern(PL,RL,SL,ResList),ResLists),
966 equal_object_optimized(ResLists,Res,'REPLACE').
967
968 % convert argument to avl list and then on to a list of elements without indices
969 convert_to_sorted_seq_list([],List,_Span) :- !, List=[].
970 convert_to_sorted_seq_list(Sequence,List,_Span) :-
971 convert_to_avl(Sequence,avl_set(AVL)),
972 custom_explicit_sets:get_avl_sequence(AVL,List),!.
973 convert_to_sorted_seq_list(Sequence,_,Span) :-
974 add_error(external_functions,'Cannot convert argument to finite sequences: ',Sequence,Span).
975
976 replace_pattern(Pat,Rep,Seq,ResBSequence) :- % Prefix.Pat.Post ---> Prefix.Rep.Post
977 append(Pat,Post,PatPost),
978 append(Rep,Post,RepPost),
979 append(Prefix,PatPost,Seq),
980 append(Prefix,RepPost,ResList),
981 convert_list_to_seq(ResList,ResBSequence).
982
983
984 % Prolog term order on encoding
985 external_fun_type('LESS',[X],[X,X,boolean]).
986 :- public 'LESS'/3.
987 :- block 'LESS'(-,?,?), 'LESS'(?,-,?).
988 'LESS'(string(A),string(B),Res) :- !, less2(A,B,Res).
989 'LESS'(int(A),int(B),Res) :- !, less_clpfd(A,B,Res). % use CLPFD less ?
990 'LESS'(fd(A,G),fd(B,G),Res) :- !, less_clpfd(A,B,Res).
991 'LESS'(term(floating(A)),B,Res) :- !,
992 kernel_reals:real_comp_wf('<',term(floating(A)),B,Res,no_wf_available).
993 'LESS'(pred_false,B,Res) :- !, B=Res. % if B=pred_true then < , otherwise not
994 'LESS'(pred_true,_,Res) :- !, Res=pred_false.
995 % TO DO: expand finite closures, couples, avl_sets, ...
996 'LESS'(X,Y,Res) :- when((ground(X),ground(Y)), less2(X,Y,Res)).
997 % TO DO: use kernel_ordering,[ordered_value/2]).
998
999 :- use_module(clpfd_interface,[clpfd_leq_expr/2,clpfd_lt_expr/2]).
1000 :- block less_clpfd(-,?,-), less_clpfd(?,-,-).
1001 less_clpfd(A,B,Res) :- Res==pred_true, !, clpfd_lt_expr(A,B).
1002 less_clpfd(A,B,Res) :- Res==pred_false, !, clpfd_leq_expr(B,A).
1003 less_clpfd(A,B,Res) :- (A < B -> Res=pred_true ; Res=pred_false).
1004
1005
1006 :- block less2(-,?,?), less2(?,-,?).
1007 less2(A,B,Res) :- (A @< B -> Res=pred_true ; Res=pred_false).
1008
1009 :- use_module(kernel_ordering,[leq_ordered_value/3]).
1010
1011 :- public 'LEQ_SYM_BREAK'/4.
1012 expects_waitflag('LEQ_SYM_BREAK').
1013 external_fun_type('LEQ_SYM_BREAK',[X],[X,X,boolean]).
1014 'LEQ_SYM_BREAK'(A,B,Res,WF) :- 'LEQ_SYM'(A,B,Res,WF).
1015
1016 expects_waitflag('LEQ_SYM').
1017 external_fun_type('LEQ_SYM',[X],[X,X,boolean]).
1018 % true if arg1 <= arg2 according to Prolog term order; may return true for some symbolic representations
1019 % Note: it is sometimes ignored, e.g., by Kodkod or Z3 translation
1020 % Also: LEQ_SYM_BREAK / LEQ_SYM do not fully support all types yet, see sym_break_supported_type
1021 :- block 'LEQ_SYM'(-,?,?,?).
1022 'LEQ_SYM'(int(A),int(B),Res,_WF) :- !,
1023 b_interpreter_check:check_arithmetic_operator('<=',A,B,Res).
1024 'LEQ_SYM'(fd(A,G),fd(B,G),Res,_WF) :- !,
1025 b_interpreter_check:check_arithmetic_operator('<=',A,B,Res).
1026 'LEQ_SYM'(term(T),B,Res,WF) :- nonvar(T), T=floating(A), !,
1027 kernel_reals:real_comp_wf('=<',term(floating(A)),B,Res,WF).
1028 'LEQ_SYM'(pred_false,_,Res,_WF) :- !, Res=pred_true. % pred_false @< pred_true
1029 'LEQ_SYM'(pred_true,B,Res,_WF) :- !, Res=B. % if B=pred_true -> ok; otherwise Res=pred_false
1030 'LEQ_SYM'([],_,Res,_W) :- !, Res=pred_true. % the empty set is the smallest set
1031 'LEQ_SYM'(closure(_,_,_),_,Res,_) :- !, Res=pred_true. % otherwise we would have to expand it
1032 'LEQ_SYM'(global_set(_),_,Res,_) :- !, Res=pred_true. % ditto
1033 'LEQ_SYM'(X,Y,Res,WF) :- 'LEQ_SYM2'(X,Y,Res,WF).
1034
1035 :- block 'LEQ_SYM2'(?,-,?,?).
1036 %'LEQ_SYM'(X,Y,Res) :- print('LEQ_SYM'(X,Y,Res)),nl,fail.
1037 'LEQ_SYM2'(string(A),string(B),Res,_WF) :- !, less_eq2(A,B,Res).
1038 'LEQ_SYM2'(_,closure(_,_,_),Res,_WF) :- !, Res=pred_true. % we would have to expand it
1039 'LEQ_SYM2'(Set1,[],Res,WF) :- !, kernel_equality:empty_set_test_wf(Set1,Res,WF).
1040 'LEQ_SYM2'((A,B),(X,Y),Res,_WF) :- Res==pred_true,!, leq_ordered_value((A,B),(X,Y),_Equal).
1041 'LEQ_SYM2'(rec(FA),rec(FB),Res,_WF) :- Res==pred_true,!, leq_ordered_value(rec(FA),rec(FB),_Equal).
1042 % TODO: support sets, e.g., by comparing cardinality or minimal elements
1043 'LEQ_SYM2'(_A,_B,Res,_WF) :- Res=pred_true.
1044 %'LEQ_SYM2'(X,Y,Res,_WF) :- when((ground(X),ground(Y)), less_eq2(X,Y,Res)). % unsafe to use; we should normalize AVLs ...
1045 % TO DO: use kernel_ordering:leq_ordered_value/2 more or use lex_chain([[X,X],[Y,Z]],[op(#=<)]) for pairs/records of FD values
1046 % Note: it is reified in b_interpreter_check
1047
1048 :- block less_eq2(-,?,?), less_eq2(?,-,?).
1049 less_eq2(A,B,Res) :- (A @=< B -> Res=pred_true ; Res=pred_false).
1050
1051 % -------------------------------
1052
1053 % was a first prototype for implementing recursive functions
1054 % was still a bit clumsy to define recursive functions (using STRING parameter for names)
1055 % a restriction is that we can only have one version per machine, i.e.
1056 % one can only define recursive function in the CONSTANTS section and only
1057 % in a deterministic fashion not depending on enumerated constants,...
1058 % we now use generate_recursive_closure in b_interpreter for recursive_let/2 constructs
1059 %:- dynamic recursive_function/2.
1060 %expects_waitflag('REC'). % DEPRECATED
1061 %expects_spaninfo('RECx'). % DEPRECATED
1062 %expects_spaninfo('REC_LET'). % DEPRECATED
1063
1064
1065 reset_external_functions :-
1066 retractall(last_walltime(_)),
1067 reset_ident,
1068 reset_kodkod,
1069 reset_observe,
1070 close_all_files.
1071
1072 :- use_module(eventhandling,[register_event_listener/3]).
1073 :- register_event_listener(clear_specification,reset_external_functions,
1074 'Reset B External Functions.').
1075
1076 print_external_function_instantiation_profile :-
1077 %TODO: we could register number of external function calls, ..
1078 portray_instantiations.
1079
1080
1081 % -------------------------------
1082
1083 expects_waitflag('FORCE').
1084 external_fun_type('FORCE',[T],[T,T]).
1085 :- public 'FORCE'/3.
1086 % example usage halve = FORCE( %x.(x:0..1000 & x mod 2 = 0 | x/2))
1087 :- block 'FORCE'(-,?,?).
1088 %'FORCE'(A,B,_) :- print(force(A)),nl,fail.
1089 'FORCE'(avl_set(A),Result,_) :- !, equal_object(avl_set(A),Result).
1090 'FORCE'([],Result,_) :- !, equal_object([],Result).
1091 'FORCE'(closure(P,T,B),Result,WF) :- !,
1092 (debug:debug_mode(on) -> print('FORCING : '),translate:print_bvalue(closure(P,T,B)),nl ; true),
1093 custom_explicit_sets:expand_closure_to_avl_or_list(P,T,B,ExpandedValue,no_check,WF),
1094 (debug:debug_mode(on) -> print('RESULT : '),translate:print_bvalue(ExpandedValue),nl,
1095 print(' ASSIGNING TO : '), translate:print_bvalue(Result),nl
1096 ; true),
1097 equal_object(ExpandedValue,Result).
1098 'FORCE'((A,B),(FA,FB),WF) :- !,'FORCE'(A,FA,WF), 'FORCE'(B,FB,WF).
1099 % TO DO: treat lists and records ...
1100 'FORCE'(A,B,_) :- equal_object_optimized(A,B,'FORCE').
1101
1102 % -----------------------------------------
1103
1104 :- use_module(tools, [read_term_from_file/2]).
1105 :- use_module(typing_tools, [check_type_of_value/2]).
1106
1107 expects_spaninfo('READ_PROB_DATA_FILE').
1108 expects_type('READ_PROB_DATA_FILE').
1109 external_fun_type('READ_PROB_DATA_FILE',[T],[set(T),string,T]).
1110 :- public 'READ_PROB_DATA_FILE'/5.
1111 :- block 'READ_PROB_DATA_FILE'(-,?,?,?,?), 'READ_PROB_DATA_FILE'(?,-,?,?,?).
1112 'READ_PROB_DATA_FILE'(_,string(File),Expr,Type,Span) :- % first arg provides type info
1113 read_prob_data_file(File,Expr,Type,Span).
1114
1115 :- use_module(tools,[start_ms_timer/1, stop_ms_timer_with_debug_msg/2]).
1116
1117 :- block read_prob_data_file(-,?,?,?).
1118 read_prob_data_file(File,ResExpr,Type,Span) :-
1119 b_absolute_file_name(File,AFile,Span),
1120 start_ms_timer(T),
1121 safe_call(read_term_from_file(AFile,Expr),Span), % can also be in fastrw format
1122 stop_ms_timer_with_debug_msg(T,'read PROB_DATA file'),
1123 (check_type_of_value(Type,Expr) -> ResExpr=Expr
1124 ; pretty_type(Type,TS),
1125 ajoin(['Type of B value does not match expected type ',TS,' in data file:'],Msg),
1126 add_error('READ_PROB_DATA_FILE',Msg,File,Span),
1127 fail).
1128
1129
1130
1131 % -----------------------------------------
1132
1133 :- public 'ENUM'/2.
1134 % example usage: ENUM((x,y)) : AVLSet
1135 % external function used for deriving info field annotations in ast_cleanup
1136 'ENUM'(Obj,Obj).
1137
1138 % -----------------------------------------
1139
1140 expects_unevaluated_args('DO_NOT_ENUMERATE').
1141 :- public 'DO_NOT_ENUMERATE'/3.
1142 :- block 'DO_NOT_ENUMERATE'(-,?,?).
1143 'DO_NOT_ENUMERATE'((A,B),PredRes,UEA) :- !, 'DO_NOT_ENUMERATE'(A,PredRes,UEA),'DO_NOT_ENUMERATE'(B,PredRes,UEA).
1144 'DO_NOT_ENUMERATE'(fd(V,_),PredRes,UEA) :- !, 'DO_NOT_ENUMERATE'(V,PredRes,UEA).
1145 'DO_NOT_ENUMERATE'(int(V),PredRes,UEA) :- !, 'DO_NOT_ENUMERATE'(V,PredRes,UEA).
1146 'DO_NOT_ENUMERATE'(string(V),PredRes,UEA) :- !, 'DO_NOT_ENUMERATE'(V,PredRes,UEA).
1147 'DO_NOT_ENUMERATE'(_Obj,PredRes,_UEA) :-
1148 %print('INSTANTIATED: '),nl, _UEA=[UnEvalArg],translate:print_bexpr(UnEvalArg),nl, print(_Obj),nl,
1149 PredRes=pred_true.
1150 % add_message('DO_NOT_ENUMERATE','Enumerating: ',UnEvalArgs).
1151
1152 % a utility to avoid propagation of values, can be used as "enumeration barrier"
1153 expects_waitflag('COPY').
1154 :- public 'COPY'/3.
1155 :- block 'COPY'(-,?,?).
1156 'COPY'(Val,Result,WF) :- ground_value_check(Val,GrVal),
1157 when(nonvar(GrVal),equal_object_optimized_wf(Val,Result,'COPY',WF)).
1158
1159
1160 % -------------------------------
1161
1162 :- assert_must_succeed(( external_functions:call_external_function('STRING_APPEND',[a,b],[string(a),string(b)],string(ab),string,unknown,_WF) )).
1163 % STRING MANIPULATION FUNCTIONS
1164
1165 :- use_module(kernel_strings,[b_string_append_wf/4, b_concat_sequence_of_strings_wf/4, b_string_reverse_wf/3,
1166 b_string_chars/2, b_string_codes/2, b_string_length/2,
1167 b_string_to_uppercase/2, b_string_to_lowercase/2]).
1168
1169 % function to append two strings, reversible
1170 external_fun_can_be_inverted('STRING_APPEND').
1171 expects_waitflag('STRING_APPEND').
1172 external_fun_type('STRING_APPEND',[],[string,string,string]).
1173 :- public 'STRING_APPEND'/4.
1174 'STRING_APPEND'(A,B,C,WF) :- b_string_append_wf(A,B,C,WF).
1175
1176 % function to append two strings, reversible
1177 external_fun_can_be_inverted('STRING_REV').
1178 expects_waitflag('STRING_REV').
1179 external_fun_type('STRING_REV',[],[string,string]).
1180 :- public 'STRING_REV'/3.
1181 'STRING_REV'(A,B,WF) :- b_string_reverse_wf(A,B,WF).
1182
1183 expects_waitflag('STRING_CONC').
1184 expects_spaninfo('STRING_CONC').
1185 external_fun_type('STRING_CONC',[],[seq(string),string]).
1186 :- public 'STRING_CONC'/4.
1187 :- block 'STRING_CONC'(-,?,?,?).
1188 % the conc(.) operator is mapped to this for strings (instead to concat_sequence)
1189 'STRING_CONC'(List,Res,Span,WF) :-
1190 b_concat_sequence_of_strings_wf(List,Res,Span,WF).
1191
1192 external_fun_can_be_inverted('STRING_CHARS').
1193 external_fun_type('STRING_CHARS',[],[string,seq(string)]).
1194 :- public 'STRING_CHARS'/2.
1195 'STRING_CHARS'(Str,SeqOfChars) :- b_string_chars(Str,SeqOfChars).
1196 /* Note: STRING_CONC can be used as inverse to combine the chars */
1197
1198 external_fun_can_be_inverted('CODES_TO_STRING').
1199 external_fun_type('CODES_TO_STRING',[],[seq(integer),string]).
1200 :- public 'CODES_TO_STRING'/2.
1201 'CODES_TO_STRING'(A,SeqRes) :- 'STRING_CODES'(SeqRes,A).
1202
1203 external_fun_can_be_inverted('STRING_CODES').
1204 external_fun_type('STRING_CODES',[],[string,seq(integer)]).
1205 :- public 'STRING_CODES'/2.
1206 'STRING_CODES'(A,SeqRes) :- b_string_codes(A,SeqRes).
1207
1208
1209 external_fun_type('STRING_TO_UPPER',[],[string,string]).
1210 :- public 'STRING_TO_UPPER'/2.
1211 'STRING_TO_UPPER'(S,S2) :- b_string_to_uppercase(S,S2).
1212 external_fun_type('STRING_TO_LOWER',[],[string,string]).
1213 :- public 'STRING_TO_LOWER'/2.
1214 'STRING_TO_LOWER'(S,S2) :- b_string_to_lowercase(S,S2).
1215
1216 :- use_module(kernel_strings,[b_string_equal_case_insensitive/3]).
1217 external_fun_type('STRING_EQUAL_CASE_INSENSITIVE',[],[string,string,boolean]).
1218 :- public 'GET_STRING_EQUAL_CASE_INSENSITIVE'/3.
1219 'STRING_EQUAL_CASE_INSENSITIVE'(S1,S2,Res) :- b_string_equal_case_insensitive(S1,S2,Res).
1220
1221 :- assert_must_succeed(( external_functions:call_external_function('STRING_LENGTH',[a],[string(a)],int(1),integer,unknown,_WF) )).
1222 % function to get length of a string
1223 external_fun_type('STRING_LENGTH',[],[string,integer]).
1224 :- public 'STRING_LENGTH'/2.
1225 'STRING_LENGTH'(S,L) :- b_string_length(S,L).
1226
1227 :- use_module(kernel_strings,[b_string_split_wf/4, b_string_join_wf/5]).
1228
1229 % function to split a string into a list of strings which were delimited by a separator
1230 % WARNING: if the seperator is of length more than one, then first match-strategy will be used
1231 external_fun_can_be_inverted('STRING_SPLIT').
1232 expects_waitflag('STRING_SPLIT').
1233 external_fun_type('STRING_SPLIT',[],[string,string,seq(string)]). % actually seq1(string)
1234 :- public 'STRING_SPLIT'/4.
1235 'STRING_SPLIT'(Str,Sep,Strings,WF) :- b_string_split_wf(Str,Sep,Strings,WF).
1236
1237 :- public 'STRING_JOIN'/5.
1238 expects_waitflag('STRING_JOIN').
1239 expects_spaninfo('STRING_JOIN').
1240 external_fun_type('STRING_JOIN',[],[seq(string),string,string]).
1241 'STRING_JOIN'(SplitAtoms,Sep,Res,Span,WF) :- b_string_join_wf(SplitAtoms,Sep,Res,Span,WF).
1242
1243
1244 expects_waitflag('STRING_CONTAINS_STRING').
1245 external_fun_type('STRING_CONTAINS_STRING',[],[string,string,boolean]).
1246 % TRUE when arg2 occurs as contiguous substring in arg1
1247 :- public 'STRING_CONTAINS_STRING'/4.
1248 :- block 'STRING_CONTAINS_STRING'(-,?,?,?), 'STRING_CONTAINS_STRING'(?,-,?,?).
1249 'STRING_CONTAINS_STRING'(string(A),string(B),PredRes,_WF) :-
1250 string_contains_string_aux(A,B,PredRes).
1251 :- use_module(library(lists),[sublist/5]).
1252 % TO DO: we could enumerate B if A known and waitflag instantiated
1253 :- block string_contains_string_aux(-,?,?),string_contains_string_aux(?,-,?).
1254 string_contains_string_aux(A,B,PredRes) :-
1255 atom_codes(A,ACodes),
1256 atom_codes(B,BCodes),
1257 ? (sublist(ACodes,BCodes,_,_,_) -> PredRes=pred_true ; PredRes=pred_false).
1258
1259 :- use_module(kernel_strings,[b_substring_wf/6]).
1260 :- public 'SUB_STRING'/6.
1261 expects_spaninfo('SUB_STRING').
1262 expects_waitflag('SUB_STRING').
1263 external_fun_type('SUB_STRING',[],[string,integer,integer,string]).
1264 'SUB_STRING'(S,From,Len,Res,Span,WF) :- b_substring_wf(S,From,Len,Res,Span,WF).
1265
1266
1267 :- use_module(kernel_strings,[b_string_replace/4]).
1268 :- public 'STRING_REPLACE'/4.
1269 external_fun_type('STRING_REPLACE',[],[string,string,string,string]).
1270 'STRING_REPLACE'(S,Pat,New,Res) :- b_string_replace(S,Pat,New,Res).
1271
1272
1273 :- use_module(probsrc(kernel_freetypes), [get_freetype_id/2, get_freeval_type/3, registered_freetype_case_value/3]).
1274 :- use_module(probsrc(translate), [pretty_type/2]).
1275 :- use_module(probsrc(btypechecker), [unify_types_werrors/4]).
1276
1277 external_fun_type('STRING_IS_FREETYPE',[],[string,boolean]).
1278 :- public 'STRING_IS_FREETYPE'/2.
1279 :- block 'STRING_IS_FREETYPE'(-,?).
1280 'STRING_IS_FREETYPE'(string(ID),Res) :-
1281 get_freeval_type(_,ID,_) -> Res=pred_true ; Res=pred_false.
1282
1283 external_fun_has_wd_condition('STRING_TO_FREETYPE').
1284 external_fun_type('STRING_TO_FREETYPE',[F],[string,F]). % F is freetype case
1285 expects_type('STRING_TO_FREETYPE').
1286 expects_spaninfo('STRING_TO_FREETYPE').
1287 :- public 'STRING_TO_FREETYPE'/4.
1288 :- block 'STRING_TO_FREETYPE'(-,?,?,?).
1289 'STRING_TO_FREETYPE'(string(ID),Value,Type,Span) :-
1290 string_to_freetype2(ID,Value,Type,Span).
1291
1292 :- block string_to_freetype2(-,?,?,?).
1293 string_to_freetype2(ID,Value,Type,Span) :-
1294 get_freetype_id(Type,FreetypeId), !, % checks implicitly that Type is freetype
1295 check_is_freetype_case(FreetypeId,ID,ArgType,Span),
1296 (Type = set(couple(_,freetype(_)))
1297 -> ExpectedType = set(couple(ArgType,freetype(FreetypeId)))
1298 ; ExpectedType = freetype(FreetypeId)
1299 ),
1300 unify_types_werrors(ExpectedType,Type,Span,'STRING_TO_FREETYPE'),
1301 (registered_freetype_case_value(ID,Type,Value) -> true
1302 ; add_error('STRING_TO_FREETYPE','error while accessing case value:',ID,Span)
1303 ).
1304 string_to_freetype2(ID,_,Type,Span) :-
1305 (nonvar(ID) -> pretty_type(Type,TS),
1306 add_error('STRING_TO_FREETYPE','STRING_TO_FREETYPE: Type mismatch: expected FREETYPE or FREETYPE case function (T <-> FREETYPE), but was',TS,Span)
1307 ; add_error('STRING_TO_FREETYPE','STRING_TO_FREETYPE cannot be inverted',ID,Span)),
1308 fail.
1309
1310 :- block check_is_freetype_case(?,-,?,?).
1311 check_is_freetype_case(FreetypeId,ID,ArgType,_) :- get_freeval_type(FreetypeId,ID,ArgType), !.
1312 check_is_freetype_case(_,ID,_,Span) :-
1313 add_error('STRING_TO_FREETYPE','STRING_TO_FREETYPE: no FREETYPE case found for string',ID,Span),
1314 fail.
1315
1316
1317 external_fun_has_wd_condition('TYPED_STRING_TO_ENUM').
1318 expects_waitflag('TYPED_STRING_TO_ENUM').
1319 expects_spaninfo('TYPED_STRING_TO_ENUM').
1320 external_fun_type('TYPED_STRING_TO_ENUM',[T],[set(T),string,T]).
1321 :- public 'TYPED_STRING_TO_ENUM'/5.
1322 :- block 'TYPED_STRING_TO_ENUM'(?,-,-,?,?),'TYPED_STRING_TO_ENUM'(-,?,?,?,?).
1323 'TYPED_STRING_TO_ENUM'(Type,string(S),Res,Span,WF) :-
1324 string_to_enum2(S,fd(Nr,GS),_,Span),
1325 check_type(Type,S,Nr,GS,Res,Span,WF).
1326
1327 :- block check_type(-,?,?, ?,?,?,?), check_type(?,-,?, ?,?,?,?), check_type(?,?,-, ?,?,?,?).
1328 check_type(GSTypeExpr,S,Nr,GS,Res,Span,WF) :-
1329 get_global_set_value_type(GSTypeExpr,'TYPED_STRING_TO_ENUM',ExpectedGS),
1330 ExpectedGS=GS,
1331 !,
1332 membership_test_wf(GSTypeExpr,fd(Nr,GS),MemTest,WF),
1333 check_value(MemTest,Nr,GS,Res,S,GSTypeExpr,Span,WF).
1334 check_type(GSTypeExpr,S,_,GS,_,Span,WF) :-
1335 get_global_set_value_type(GSTypeExpr,'TYPED_STRING_TO_ENUM',ExpectedGS),
1336 ajoin(['String value ',S,' is of type ',GS,' and not of expected type:'],Msg),
1337 add_wd_error_span(Msg,ExpectedGS,Span,WF).
1338
1339 :- block check_value(-,?,?,?,?,?,?,?).
1340 check_value(pred_true,Nr,GS,Res,_,_,_,_) :- !, Res=fd(Nr,GS).
1341 check_value(pred_false,_,_GS,_,S,GSTypeExpr,Span,WF) :-
1342 ajoin(['String value ',S,' is of correct type but not in set:'],Msg),
1343 translate:translate_bvalue(GSTypeExpr,SetStr),
1344 add_wd_error_span(Msg,SetStr,Span,WF).
1345
1346 % get type of a set of enumerated/deferred set elements
1347 get_global_set_value_type(global_set(GS),_,Res) :- !, Res=GS.
1348 get_global_set_value_type([fd(_,GS)|_],_,Res) :- !, Res=GS.
1349 get_global_set_value_type(avl_set(node(fd(_,GS),_True,_,_,_)),_,Res) :- !, Res=GS.
1350 get_global_set_value_type(Val,Source,_) :- translate:translate_bvalue(Val,VS),
1351 add_error(Source,'First argument of illegal type, it must be a set of deferred or enumerated set elements:',VS),fail.
1352
1353 :- use_module(probsrc(translate), [pretty_type/2]).
1354
1355 external_fun_can_be_inverted('STRING_TO_ENUM').
1356 external_fun_has_wd_condition('STRING_TO_ENUM').
1357 external_fun_type('STRING_TO_ENUM',[G],[string,G]). % G is enumerated set
1358 expects_type('STRING_TO_ENUM').
1359 expects_spaninfo('STRING_TO_ENUM').
1360 :- public 'STRING_TO_ENUM'/4.
1361 :- block 'STRING_TO_ENUM'(-,-,?,?).
1362 'STRING_TO_ENUM'(string(S),FD,global(Type),Span) :- !, string_to_enum2(S,FD,Type,Span).
1363 'STRING_TO_ENUM'(_,_,Type,Span) :- pretty_type(Type,TS),
1364 add_error('STRING_TO_ENUM','Illegal type for STRING_TO_ENUM (requires a SET type): ',TS,Span),fail.
1365
1366 :- block string_to_enum2(-,-,?,?).
1367 string_to_enum2(S,Res,Type,Span) :- nonvar(S),!,
1368 (b_global_sets:lookup_global_constant(S,FD),
1369 FD = fd(_,GS)
1370 -> check_type_aux(Type,GS,S,Span),
1371 Res=FD % fd(Nr,GS)
1372 ; % TO DO: use add_wd_error_set_result
1373 add_error('STRING_TO_ENUM','Could not convert string to enumerated set element: ',S,Span),fail).
1374 string_to_enum2(S,fd(Nr,GS),Type,Span) :-
1375 string_to_enum3(S,Nr,GS,Type,Span).
1376
1377
1378 check_type_aux(Type,GS,S,Span) :- Type \= GS,!,
1379 ajoin(['String value "',S,'" has illegal type ',GS,', expected: '],Msg),
1380 add_error('STRING_TO_ENUM',Msg,Type,Span),
1381 fail.
1382 check_type_aux(_,_,_,_).
1383
1384 :- block string_to_enum3(-,-,?,?,?),string_to_enum3(-,?,-,?,?).
1385 string_to_enum3(S,Nr,GS,Type,Span) :- nonvar(S),!,
1386 (b_global_sets:lookup_global_constant(S,fd(SNr,SGS))
1387 -> check_type_aux(Type,SGS,S,Span),
1388 (SGS,SNr) = (GS,Nr)
1389 ; add_error('STRING_TO_ENUM','Could not convert string to enumerated set element: ',S,Span),fail).
1390 string_to_enum3(S,Nr,GS,_,Span) :-
1391 (b_global_sets:is_b_global_constant_hash(GS,Nr,GNS)
1392 -> GNS=S
1393 ; add_error('STRING_TO_ENUM','Could not convert deferred set element to string: ',GS:Nr,Span),fail).
1394
1395 :- use_module(kernel_strings,[b_string_is_int/2]).
1396 external_fun_type('STRING_IS_INT',[],[string,boolean]).
1397 :- public 'GET_STRING_IS_INT'/2.
1398 'STRING_IS_INT'(S,Res) :- b_string_is_int(S,Res).
1399
1400 :- use_module(kernel_strings,[b_string_is_number/2]).
1401 external_fun_type('STRING_IS_NUMBER',[],[string,boolean]).
1402 :- public 'GET_STRING_IS_NUMBER'/2.
1403 'STRING_IS_NUMBER'(S,Res) :- b_string_is_number(S,Res).
1404
1405 :- use_module(kernel_strings,[b_string_is_decimal/2]).
1406 external_fun_type('STRING_IS_DECIMAL',[],[string,boolean]).
1407 :- public 'GET_STRING_IS_DECIMAL'/2.
1408 'STRING_IS_DECIMAL'(S,Res) :- b_string_is_decimal(S,Res).
1409
1410 external_fun_type('STRING_IS_ALPHANUMERIC',[],[string,boolean]).
1411 :- use_module(kernel_strings,[b_string_is_alphanumerical/2]).
1412 :- public 'GET_STRING_IS_ALPHANUMERIC'/2.
1413 'STRING_IS_ALPHANUMERIC'(X,Res) :- b_string_is_alphanumerical(X,Res).
1414
1415 % synonyms as use for functions to BOOL rather than predicates
1416 'GET_STRING_EQUAL_CASE_INSENSITIVE'(S1,S2,Res) :- 'STRING_EQUAL_CASE_INSENSITIVE'(S1,S2,Res).
1417 'GET_STRING_IS_ALPHANUMERIC'(S,Res) :- 'STRING_IS_ALPHANUMERIC'(S,Res).
1418 'GET_STRING_IS_DECIMAL'(S,Res) :- 'STRING_IS_DECIMAL'(S,Res).
1419 'GET_STRING_IS_NUMBER'(S,Res) :- 'STRING_IS_NUMBER'(S,Res).
1420 'GET_STRING_IS_INT'(S,Res) :- 'STRING_IS_INT'(S,Res).
1421
1422 % A Utility to convert Decimal Strings to Integers
1423 % TO DO: make a more precise version using just integers: currently DEC_STRING_TO_INT("1024.235",2) = 102423 !
1424 external_fun_has_wd_condition('DEC_STRING_TO_INT').
1425 expects_spaninfo('DEC_STRING_TO_INT').
1426 expects_waitflag('DEC_STRING_TO_INT').
1427 external_fun_type('DEC_STRING_TO_INT',[],[string,integer,integer]).
1428
1429 :- assert_must_succeed((atom_codes(A,"1024"),
1430 external_functions:'DEC_STRING_TO_INT'(string(A),int(0),int(1024),unknown,no_wf_available))).
1431 :- assert_must_succeed((atom_codes(A,"1024.1"),
1432 external_functions:'DEC_STRING_TO_INT'(string(A),int(1),int(10241),unknown,no_wf_available))).
1433 :- public 'DEC_STRING_TO_INT'/5.
1434 :- block 'DEC_STRING_TO_INT'(-,?,?,?,?),'DEC_STRING_TO_INT'(?,-,?,?,?).
1435 'DEC_STRING_TO_INT'(string(S),int(Precision),int(Res),Span,WF) :-
1436 dec_str_to_int(S,Precision,Res,Span,WF).
1437
1438 :- use_module(tools,[split_chars/3]).
1439 :- block dec_str_to_int(-,?,?,?,?),dec_str_to_int(?,-,?,?,?).
1440 dec_str_to_int(S,Precision,Res,Span,WF) :-
1441 atom_codes(S,Codes),
1442 split_chars(Codes,".",[Left|T]),
1443 (T=[] -> Right="", dec_str_to_int2(Left,Right,Precision,Res,Span,WF)
1444 ; T = [Right] -> dec_str_to_int2(Left,Right,Precision,Res,Span,WF)
1445 ; %add_error(external_functions,'Expecting integer or decimal number:',S,Span),fail
1446 add_wd_error_span('String contains multiple dots, expecting integer or decimal number for DEC_STRING_TO_INT:',S,Span,WF)
1447 ).
1448
1449
1450 get_sign([45|T],-1,Res) :- !,strip_ws(T,Res).
1451 get_sign([32|T],PosNeg,Res) :- !, get_sign(T,PosNeg,Res).
1452 get_sign(L,1,L).
1453 strip_ws([32|T],R) :- !, strip_ws(T,R).
1454 strip_ws(R,R).
1455
1456 ?rounding([H|_]) :- member(H,"56789").
1457
1458 is_zero(48). % code of 0
1459 is_digit(Code) :- Code >= 48, Code =< 57.
1460 check_digits(Codes,_,_,Res) :- maplist(is_digit,Codes),!,Res=ok.
1461 check_digits(Codes,Span,WF,ko) :-
1462 append([39|Codes],[39],C2), atom_codes(A,C2), % generate atom with quotes
1463 %add_error(external_functions,'Illegal number: ',A,Span),fail.
1464 add_wd_error_span('String contains illegal characters, expecting integer or decimal number for DEC_STRING_TO_INT:',A,Span,WF).
1465
1466 dec_safe_number_codes(Number,[],_,_) :- !, Number=0.
1467 dec_safe_number_codes(Number,Codes,Span,WF) :-
1468 (safe_number_codes(Nr,Codes) -> Number=Nr
1469 ; append([39|Codes],[39],C2), atom_codes(A,C2),
1470 %add_error(external_functions,'Cannot convert to number: ',A,Span),fail
1471 add_wd_error_span('Cannot convert string to number for DEC_STRING_TO_INT:',A,Span,WF),
1472 Number='$WDERROR$'
1473 ).
1474
1475 dec_str_to_int2(Left,Right,Precision,Res,Span,WF) :-
1476 maplist(is_zero,Right), Precision >= 0,
1477 !,
1478 dec_safe_number_codes(LeftNumber,Left,Span,WF),
1479 (LeftNumber=='$WDERROR$' -> true
1480 ; safe_is('DEC_STRING_TO_INT',Res,LeftNumber*(10^Precision),Span,WF)).
1481 dec_str_to_int2(Left,Right,Precision,Res,Span,WF) :- get_sign(Left,Sign,NewLeft),
1482 check_digits(NewLeft,Span,WF,Res1), check_digits(Right,Span,WF,Res2),
1483 (Res1==ok,Res2==ok
1484 -> shift(Precision,NewLeft,Right,ResL,ResR),
1485 dec_safe_number_codes(LeftInteger,ResL,Span,WF),
1486 ? (rounding(ResR)
1487 -> Res is Sign*(LeftInteger+1)
1488 ; Res is Sign*LeftInteger)
1489 ; true).
1490
1491 :- use_module(library(lists),[append_length/4]).
1492 % shift decimal values left or right depending on precision argument
1493 shift(0,Left,Right,Left,Right) :- !.
1494 shift(Pos,Left,Right,ResL,ResR) :- Pos>0,!,
1495 append(Left,Left2,ResL),
1496 length(Right,RLen),
1497 (RLen >= Pos -> append_length(Left2,ResR,Right,Pos) % take first Pos elements from R and shift left of .
1498 ; append(Right,Zeros,Left2), % take all of Right and add Zeros
1499 ResR = [],
1500 NrZeros is Pos - RLen,
1501 length(Zeros,NrZeros), maplist(is_zero,Zeros)
1502 ).
1503 shift(Pos,Left,Right,ResL,ResR) :- % Pos < 0
1504 length(Left,LLen), PPos is -Pos,
1505 (LLen >= PPos
1506 -> Shift is LLen-PPos, append_length(ResL,L2,Left,Shift), append(L2,Right,ResR)
1507 ; %Result always 0.0...
1508 NrZeros is PPos - LLen,length(Zeros,NrZeros), maplist(is_zero,Zeros),
1509 ResL = "0",
1510 append(Zeros,LR,ResR),
1511 append(Left,Right,LR)).
1512
1513 :- public 'STRING_PADLEFT'/6.
1514 external_fun_has_wd_condition('STRING_PADLEFT'). % PadChar must be string of length 1
1515 expects_waitflag('STRING_PADLEFT').
1516 expects_spaninfo('STRING_PADLEFT').
1517 external_fun_type('STRING_PADLEFT',[],[string,integer,string,string]).
1518 :- block 'STRING_PADLEFT'(-,?,?,?,?,?),'STRING_PADLEFT'(?,-,?,?,?,?),'STRING_PADLEFT'(?,?,-,?,?,?).
1519 'STRING_PADLEFT'(string(S),int(Width),string(PadChar),Res,Span,WF) :-
1520 string_pad_left(S,Width,PadChar,Res,Span,WF).
1521
1522 :- block string_pad_left(-,?,?,?,?,?),string_pad_left(?,-,?,?,?,?),string_pad_left(?,?,-,?,?,?).
1523 string_pad_left(_S,_Width,PadChar,_Res,Span,WF) :-
1524 atom_length(PadChar,Len), Len \= 1,
1525 !,
1526 add_wd_error_span('STRING_PADLEFT requires padding string of length 1: ',PadChar,Span,WF).
1527 string_pad_left(S,Width,PadChar,Res,_Span,_WF) :-
1528 atom_length(S,Len),
1529 (Len >= Width % no padding necessary
1530 -> Res = string(S)
1531 ; ToPad is Width-Len,
1532 atom_codes(PadChar,[PadCode]),
1533 atom_codes(S,Codes),
1534 pad_char(ToPad,PadCode,PaddedCodes,Codes),
1535 atom_codes(ResStr,PaddedCodes),
1536 Res = string(ResStr)
1537 ).
1538
1539 pad_char(0,_,Res,Tail) :- !, Res=Tail.
1540 pad_char(Nr,Code,[Code|TR],Tail) :- N1 is Nr-1, pad_char(N1,Code,TR,Tail).
1541
1542
1543
1544
1545 :- use_module(kernel_strings,[b_string_to_int_wf/4]).
1546 external_fun_has_wd_condition('STRING_TO_INT').
1547 expects_waitflag('STRING_TO_INT').
1548 expects_spaninfo('STRING_TO_INT').
1549 external_fun_type('STRING_TO_INT',[],[string,integer]).
1550 :- public 'STRING_TO_INT'/4.
1551 :- block 'STRING_TO_INT'(-,-,?,?).
1552 'STRING_TO_INT'(S,I,Span,WF) :- b_string_to_int_wf(S,I,Span,WF).
1553
1554
1555 :- use_module(kernel_strings,[int_to_b_string/2]).
1556 external_fun_type('INT_TO_STRING',[],[integer,string]).
1557 :- public 'INT_TO_STRING'/2.
1558 'INT_TO_STRING'(I,S) :- int_to_b_string(I,S).
1559
1560 :- use_module(kernel_strings,[int_to_dec_b_string/3, real_to_dec_b_string/4]).
1561 external_fun_type('INT_TO_DEC_STRING',[],[integer,integer,string]).
1562 :- public 'INT_TO_DEC_STRING'/3.
1563 'INT_TO_DEC_STRING'(I,Precision,S) :- int_to_dec_b_string(I,Precision,S).
1564
1565 external_fun_type('REAL_TO_DEC_STRING',[],[real,integer,string]).
1566 expects_spaninfo('REAL_TO_DEC_STRING').
1567 :- public 'REAL_TO_DEC_STRING'/4.
1568 'REAL_TO_DEC_STRING'(R,Precision,S,Span) :- real_to_dec_b_string(R,Precision,S,Span).
1569
1570 :- use_module(tools,[safe_read_term_from_atom/2]).
1571 % only for internal use in XTL mode! (used in execute by predicate to pass terms as parameters in a B predicate)
1572 external_fun_type('STRING_TO_TERM',[],[string,string]).
1573 :- public 'STRING_TO_TERM'/2.
1574 :- block 'STRING_TO_TERM'(-,?).
1575 'STRING_TO_TERM'(string(S),Res) :- !, Res = term(Term),
1576 safe_read_term_from_atom(S,Term).
1577 'STRING_TO_TERM'(Obj,_) :-
1578 add_error(external_functions,'Illegal type for STRING_TO_TERM, only accepts strings:',Obj),
1579 fail.
1580
1581
1582 :- use_module(kernel_strings,[to_b_string_with_type/3,to_b_string_with_type_and_options/4,format_to_b_string/3,format_to_b_string_with_type/4]).
1583 external_fun_type('TO_STRING',[X],[X,string]).
1584 expects_waitflag('TO_STRING').
1585 expects_spaninfo('TO_STRING').
1586 expects_unevaluated_args('TO_STRING').
1587 :- public 'TO_STRING'/5.
1588 'TO_STRING'(Value,S,[TExpr],Span,WF) :-
1589 get_large_finite_wait_flag(to_string,WF,AWF), %get_enumeration_finished_wait_flag(WF,AWF),
1590 tostring6(Value,TExpr,S,Span,WF,AWF).
1591
1592 :- block tostring6(-,?,?,?,?,-).
1593 tostring6(Value,TExpr,S,_,_WF,_AWF) :- (nonvar(Value); nonvar(S)),!,
1594 get_texpr_type(TExpr, Type),
1595 to_b_string_with_type(Value,Type,S).
1596 tostring6(Val,_,string(S),Span,WF,_) :-
1597 add_wd_error_span('Could not compute value in TO_STRING',Val,Span,WF),
1598 S = '<<WELL-DEF-ERROR>>'.
1599
1600 external_fun_type('TO_STRING_UNICODE',[X],[X,string]).
1601 expects_unevaluated_args('TO_STRING_UNICODE').
1602 :- public 'TO_STRING_UNICODE'/3.
1603 'TO_STRING_UNICODE'(Value,S,[TExpr]) :-
1604 get_texpr_type(TExpr, Type),
1605 to_b_string_with_type_and_options(Value,Type,[unicode],S).
1606
1607 external_fun_type('FORMAT_TO_STRING',[X],[string,seq(X),string]).
1608 expects_unevaluated_args('FORMAT_TO_STRING').
1609 :- public 'FORMAT_TO_STRING'/4.
1610 'FORMAT_TO_STRING'(FormatString,ListOfStrings,Res,[_,TExprs]) :-
1611 (get_texpr_type(TExprs, seq(Type)) % if the type of the given format args is a sequence we can use the contained type
1612 -> format_to_b_string_with_type(FormatString,ListOfStrings,Type,Res)
1613 ; format_to_b_string(FormatString,ListOfStrings,Res)).
1614
1615
1616 external_fun_type('STRINGIFY',[X],[X,string]).
1617 expects_unevaluated_args('STRINGIFY').
1618 :- public 'PRETTY_PRINT_TO_STRING'/3.
1619 :- public 'STRINGIFY'/3.
1620 % pretty print a formula to string, the value is not used (but will currently be evaluated !)
1621 % TO DO: should we enforce a certain mode? (ascii, unicode, ...)
1622
1623 'PRETTY_PRINT_TO_STRING'(V,R,A) :- 'STRINGIFY'(V,R,A). % old name
1624 'STRINGIFY'(_Value,Res,[AST]) :-
1625 translate:translate_bexpression(AST,S),
1626 Res = string(S).
1627
1628 external_fun_type('HASH',[X],[X,integer]).
1629 :- public 'HASH'/2.
1630 :- block 'HASH'(-,?).
1631 'HASH'(Value,Int) :-
1632 % TO DO: use ground_value_check
1633 when(ground(Value),(term_hash(Value,H),Int=int(H))).
1634
1635
1636 external_fun_type('TO_INT',[X],[X,integer]). % can translate enumerated/deferred set elements to integer
1637 expects_waitflag('TO_INT').
1638 expects_spaninfo('TO_INT').
1639 :- public 'TO_INT'/4.
1640 :- block 'TO_INT'(-,?,?,?).
1641 'TO_INT'(fd(X,_),I,_,_) :- !, I=int(X).
1642 'TO_INT'(int(X),I,_,_) :- !, I=int(X).
1643 'TO_INT'(string(X),I,Span,WF) :- !, 'STRING_TO_INT'(string(X),I,Span,WF).
1644 'TO_INT'(Val,_,Span,_WF) :- !, translate:translate_bvalue(Val,VS),
1645 add_error(external_functions,'Illegal argument type for TO_INT:',VS,Span).
1646
1647
1648 external_fun_has_wd_condition('INT_TO_ENUM').
1649 expects_waitflag('INT_TO_ENUM').
1650 expects_spaninfo('INT_TO_ENUM').
1651 external_fun_type('INT_TO_ENUM',[T],[set(T),integer,T]).
1652 :- public 'INT_TO_ENUM'/5.
1653 :- block 'INT_TO_ENUM'(?,-,?,?,?),'INT_TO_ENUM'(-,?,?,?,?).
1654 'INT_TO_ENUM'(GSTypeExpr,int(I),Res,Span,WF) :-
1655 get_global_set_value_type(GSTypeExpr,'INT_TO_ENUM',GS),
1656 int2enum(GS,GSTypeExpr,I,Res,Span,WF).
1657 :- use_module(b_global_sets,[b_get_fd_type_bounds/3]).
1658
1659 :- use_module(library(clpfd), []). % for .. operator
1660 :- block int2enum(?,?,-,?,?,?).
1661 int2enum(GS,_,I,_,Span,WF) :-
1662 b_get_fd_type_bounds(GS,Low,Up),
1663 (I<Low ; integer(Up),I>Up),!,
1664 ajoin(['INT_TO_ENUM integer value ',I,' is not in expected range for ',GS,' :'],Msg),
1665 add_wd_error_span(Msg,Low..Up,Span,WF).
1666 int2enum(GS,GSTypeExpr,I,Res,Span,WF) :- Res = fd(I,GS),
1667 membership_test_wf(GSTypeExpr,Res,MemTest,WF),
1668 check_value(MemTest,I,GS,Res,I,GSTypeExpr,Span,WF).
1669
1670 % -------------------------------
1671 % REGULAR EXPRESSION FUNCTIONS
1672 % Using ECMAScript syntax: http://www.cplusplus.com/reference/regex/ECMAScript/
1673
1674 :- use_module(extension('regexp/regexp'),
1675 [regexp_match/4, is_regexp/1, regexp_replace/5,
1676 regexp_search_first/4, regexp_search_first_detailed/5]).
1677 external_fun_type('REGEX_MATCH',[],[string,string,boolean]).
1678 expects_spaninfo('REGEX_MATCH').
1679 :- public 'REGEX_MATCH'/4, 'REGEX_IMATCH'/4.
1680 :- block 'REGEX_MATCH'(-,?,?,?), 'REGEX_MATCH'(?,-,?,?).
1681 'REGEX_MATCH'(string(String),string(Pattern),Res,Span) :-
1682 block_regex_match(String,Pattern,match_case,Res,Span).
1683
1684 external_fun_type('REGEX_IMATCH',[],[string,string,boolean]).
1685 expects_spaninfo('REGEX_IMATCH').
1686 :- block 'REGEX_IMATCH'(-,?,?,?), 'REGEX_IMATCH'(?,-,?,?).
1687 'REGEX_IMATCH'(string(String),string(Pattern),Res,Span) :-
1688 block_regex_match(String,Pattern,ignore_case,Res,Span).
1689
1690 :- block block_regex_match(-,?,?,?,?), block_regex_match(?,-,?,?,?).
1691 block_regex_match(String,Pattern,IgnoreCase,Res,Span) :-
1692 (regexp_match(String,Pattern,IgnoreCase,Span) -> Res=pred_true ; Res=pred_false).
1693
1694 external_fun_type('IS_REGEX',[],[string,boolean]).
1695 :- public 'IS_REGEX'/2.
1696 :- block 'IS_REGEX'(-,?).
1697 'IS_REGEX'(string(Pattern),Res) :- block_is_regexp(Pattern,Res).
1698 :- block block_is_regexp(-,?).
1699 block_is_regexp(Pattern,Res) :-
1700 (is_regexp(Pattern) -> Res=pred_true ; Res=pred_false).
1701
1702
1703 :- public 'GET_IS_REGEX'/2.
1704 :- public 'GET_IS_REGEX_MATCH'/4.
1705 :- public 'GET_IS_REGEX_IMATCH'/4.
1706 expects_spaninfo('GET_IS_REGEX_MATCH').
1707 expects_spaninfo('GET_IS_REGEX_IMATCH').
1708 % synonyms as use for functions to BOOL rather than predicates
1709 'GET_IS_REGEX'(A,Res) :- 'IS_REGEX'(A,Res).
1710 'GET_IS_REGEX_MATCH'(S1,S2,Res,Span) :- 'REGEX_MATCH'(S1,S2,Res,Span).
1711 'GET_IS_REGEX_IMATCH'(S1,S2,Res,Span) :- 'REGEX_IMATCH'(S1,S2,Res,Span).
1712
1713 external_fun_type('REGEX_REPLACE',[],[string,string,string,string]).
1714 :- public 'REGEX_REPLACE'/4.
1715 :- block 'REGEX_REPLACE'(-,?,?,?), 'REGEX_REPLACE'(?,-,?,?), 'REGEX_REPLACE'(?,?,-,?).
1716 'REGEX_REPLACE'(string(String),string(Pattern),string(ReplString),Res) :-
1717 block_regex_replace(String,Pattern,match_case,ReplString,Res).
1718
1719 external_fun_type('REGEX_IREPLACE',[],[string,string,string,string]).
1720 :- public 'REGEX_IREPLACE'/4.
1721 :- block 'REGEX_IREPLACE'(-,?,?,?), 'REGEX_IREPLACE'(?,-,?,?), 'REGEX_IREPLACE'(?,?,-,?).
1722 'REGEX_IREPLACE'(string(String),string(Pattern),string(ReplString),Res) :-
1723 block_regex_replace(String,Pattern,ignore_case,ReplString,Res).
1724
1725 :- block block_regex_replace(-,?,?,?,?), block_regex_replace(?,-,?,?,?), block_regex_replace(?,?,?,-,?).
1726 block_regex_replace(String,Pattern,IgnoreCase,ReplString,Result) :-
1727 regexp_replace(String,Pattern,IgnoreCase,ReplString,Res), Result=string(Res).
1728
1729
1730 external_fun_type('REGEX_SEARCH_STR',[],[string,string,string]).
1731 :- public 'REGEX_SEARCH_STR'/3, 'REGEX_ISEARCH_STR'/3.
1732 :- block 'REGEX_SEARCH_STR'(-,?,?), 'REGEX_SEARCH_STR'(?,-,?).
1733 'REGEX_SEARCH_STR'(string(String),string(Pattern),Res) :- block_regex_search_first(String,Pattern,match_case,Res).
1734 external_fun_type('REGEX_ISEARCH_STR',[],[string,string,string]).
1735 :- block 'REGEX_ISEARCH_STR'(-,?,?), 'REGEX_ISEARCH_STR'(?,-,?).
1736 'REGEX_ISEARCH_STR'(string(String),string(Pattern),Res) :- block_regex_search_first(String,Pattern,ignore_case,Res).
1737 :- block block_regex_search_first(-,?,?,?), block_regex_search_first(?,-,?,?).
1738 block_regex_search_first(String,Pattern,IgnoreCase,Result) :-
1739 regexp_search_first(String,Pattern,IgnoreCase,Res), Result=string(Res).
1740
1741 external_fun_type('REGEX_SEARCH',[],[string,integer,string,
1742 record([field(length,integer),field(position,integer),
1743 field(string,string),
1744 field(submatches,seq(string))])]).
1745 :- public 'REGEX_SEARCH'/4, 'REGEX_ISEARCH'/4.
1746 'REGEX_SEARCH'(S,From,Pat,Res) :- 'REGEX_SEARCH5'(S,From,Pat,match_case,Res).
1747 external_fun_type('REGEX_ISEARCH',TV,T) :- external_fun_type('REGEX_SEARCH',TV,T).
1748 'REGEX_ISEARCH'(S,From,Pat,Res) :- 'REGEX_SEARCH5'(S,From,Pat,ignore_case,Res).
1749
1750 :- block 'REGEX_SEARCH5'(-,?,?,?,?), 'REGEX_SEARCH5'(?,-,?,?,?), 'REGEX_SEARCH5'(?,?,-,?,?).
1751 'REGEX_SEARCH5'(string(String),int(From),string(Pattern),IgnoreCase,Res) :-
1752 block_regex_search_first_detailed(String,From,Pattern,IgnoreCase,Res).
1753
1754 :- block block_regex_search_first_detailed(-,?,?,?,?),
1755 block_regex_search_first_detailed(?,-,?,?,?), block_regex_search_first_detailed(?,?,-,?,?).
1756 block_regex_search_first_detailed(String,FromIndex,Pattern,IgnoreCase,Result) :-
1757 regexp_search_first_detailed(String,FromIndex,Pattern,IgnoreCase,Res),
1758 construct_match_result(Res,Result).
1759
1760 construct_match_result(match(Pos,Len,[Str|SubMatches]),Res) :- !,
1761 BPos is Pos+1,
1762 maplist(mkstring,SubMatches,SubMatchesStr),
1763 convert_list_to_seq(SubMatchesStr,SubList),
1764 Res = rec([field(length,int(Len)), field(position,int(BPos)),
1765 field(string,string(Str)), field(submatches,SubList)]).
1766 construct_match_result('no-match',Res) :- !,
1767 Res = rec([field(length,int(-1)), field(position,int(-1)), field(string,string('')), field(submatches,[])]).
1768
1769 mkstring(A,string(A)).
1770
1771 :- use_module(extension('regexp/regexp'), [regexp_search_all/4]).
1772 external_fun_type('REGEX_SEARCH_ALL',[],[string,string,seq(string)]).
1773 :- public 'REGEX_SEARCH_ALL'/3, 'REGEX_ISEARCH_ALL'/3.
1774 :- block 'REGEX_SEARCH_ALL'(-,?,?), 'REGEX_SEARCH_ALL'(?,-,?).
1775 'REGEX_SEARCH_ALL'(string(String),string(Pattern),Res) :- block_regex_search_all(String,Pattern,match_case,Res).
1776
1777 external_fun_type('REGEX_ISEARCH_ALL',[],[string,string,seq(string)]).
1778 :- block 'REGEX_ISEARCH_ALL'(-,?,?), 'REGEX_ISEARCH_ALL'(?,-,?).
1779 'REGEX_ISEARCH_ALL'(string(String),string(Pattern),Res) :- block_regex_search_all(String,Pattern,ignore_case,Res).
1780
1781 :- block block_regex_search_all(-,?,?,?), block_regex_search_all(?,-,?,?).
1782 block_regex_search_all(String,Pattern,IgnoreCase,Result) :-
1783 regexp_search_all(String,Pattern,IgnoreCase,Matches),
1784 maplist(mkstring,Matches,MatchesStr),
1785 convert_list_to_seq(MatchesStr,Result).
1786
1787
1788 % -------------------------------
1789
1790 external_fun_type('SHA_HASH',[X],[X,set(couple(integer,integer))]).
1791 expects_waitflag('SHA_HASH').
1792 :- use_module(extension('probhash/probhash'),[raw_sha_hash/2]).
1793 :- use_module(store,[normalise_value_for_var/3]).
1794 :- public 'SHA_HASH'/3.
1795 :- block 'SHA_HASH'(-,?,?).
1796 'SHA_HASH'(Value,Res,WF) :-
1797 normalise_value_for_var('SHA_HASH',Value,NValue),
1798 ground_value_check(NValue,Gr),
1799 sha_hash(NValue,Gr,Res,WF).
1800 :- block sha_hash(?,-,?,?).
1801 sha_hash(Value,_,Res,WF) :-
1802 raw_sha_hash(Value,List),
1803 convert_to_int_seq(List,1,Seq),
1804 equal_object_optimized_wf(Seq,Res,'SHA_HASH',WF).
1805
1806 convert_to_int_seq([],_,[]).
1807 convert_to_int_seq([H|T],N,[(int(N),int(H))|CT]) :- N1 is N+1, convert_to_int_seq(T,N1,CT).
1808
1809 external_fun_type('SHA_HASH_HEX',[X],[X,string]).
1810 :- public 'SHA_HASH_HEX'/2.
1811 :- block 'SHA_HASH_HEX'(-,?).
1812 'SHA_HASH_HEX'(Value,Res) :-
1813 normalise_value_for_var('SHA_HASH_HEX',Value,NValue),
1814 ground_value_check(NValue,Gr),
1815 sha_hash_string(NValue,Gr,Res).
1816 :- block sha_hash_string(?,-,?).
1817 sha_hash_string(Value,_,Res) :-
1818 sha_hash_as_hex_codes(Value,SHAHexCodes), atom_codes(Atom,SHAHexCodes),
1819 Res = string(Atom).
1820
1821 :- use_module(extension('probhash/probhash'),[raw_sha_hash_file/3]).
1822 performs_io('SHA_HASH_FILE_HEX').
1823 expects_spaninfo('SHA_HASH_FILE_HEX').
1824 external_fun_type('SHA_HASH_FILE_HEX',[],[string,string]).
1825 :- public 'SHA_HASH_FILE_HEX'/3.
1826 :- block 'SHA_HASH_FILE_HEX'(-,?,?).
1827 'SHA_HASH_FILE_HEX'(string(File),Res,Span) :-
1828 sha_hash_file(File,Res,Span).
1829 :- block sha_hash_file(-,?,?).
1830 sha_hash_file(File,Res,Span) :-
1831 b_absolute_file_name(File,AFile),
1832 raw_sha_hash_file(AFile,Term,Span),
1833 get_hex_bytes(Term,SHAHexCodes), atom_codes(Atom,SHAHexCodes),
1834 Res = string(Atom).
1835
1836 % -------------------------------
1837
1838 % STRING FILE SYSTEM FUNCTIONS
1839
1840
1841 :- use_module(kernel_objects).
1842 :- use_module(library(file_systems)).
1843 performs_io('FILES').
1844 external_fun_type('FILES',[],[string,set(string)]).
1845 :- public 'FILES'/2.
1846 :- block 'FILES'(-,?).
1847 'FILES'(string(A),L) :- files2(A,L).
1848 :- block files2(-,?).
1849 files2(Dir,List) :- b_absolute_file_name(Dir,ADir),
1850 findall(string(F),file_member_of_directory(ADir,F,_FLong),L),
1851 equal_object_optimized(L,List,files2).
1852 performs_io('FULL_FILES').
1853 external_fun_type('FULL_FILES',[],[string,set(string)]).
1854 :- public 'FULL_FILES'/2.
1855 :- block 'FULL_FILES'(-,?).
1856 'FULL_FILES'(string(A),L) :- full_files2(A,L).
1857 :- block full_files2(-,?).
1858 full_files2(Dir,List) :-
1859 b_absolute_file_name(Dir,ADir),
1860 findall(string(FLong),file_member_of_directory(ADir,_F,FLong),L),
1861 equal_object_optimized(L,List,full_files2).
1862
1863
1864 performs_io('DIRECTORIES').
1865 external_fun_type('DIRECTORIES',[],[string,set(string)]).
1866 :- public 'DIRECTORIES'/2.
1867 :- block 'DIRECTORIES'(-,?).
1868 'DIRECTORIES'(string(A),L) :- dir2(A,L).
1869 :- block dir2(-,?).
1870 dir2(Dir,List) :- b_absolute_file_name(Dir,ADir),
1871 findall(string(F),directory_member_of_directory(ADir,F,_FLong),L),
1872 equal_object_optimized(L,List,dir2).
1873 performs_io('FULL_DIRECTORIES').
1874 external_fun_type('FULL_DIRECTORIES',[],[string,set(string)]).
1875 :- public 'FULL_DIRECTORIES'/2.
1876 :- block 'FULL_DIRECTORIES'(-,?).
1877 'FULL_DIRECTORIES'(string(A),L) :- full_dir2(A,L).
1878 :- block full_dir2(-,?).
1879 full_dir2(Dir,List) :- b_absolute_file_name(Dir,ADir),
1880 findall(string(FLong),directory_member_of_directory(ADir,_,FLong),L),
1881 equal_object_optimized(L,List,full_dir2).
1882
1883 :- public 'GET_FILE_EXISTS'/2.
1884 'GET_FILE_EXISTS'(S,PREDRES) :- 'FILE_EXISTS'(S,PREDRES). % synonym as external function
1885 performs_io('FILE_EXISTS').
1886 external_fun_type('FILE_EXISTS',[],[string,boolean]).
1887 :- public 'FILE_EXISTS'/2.
1888 :- block 'FILE_EXISTS'(-,?).
1889 'FILE_EXISTS'(string(A),PREDRES) :- file_exists2(A,PREDRES).
1890 :- block file_exists2(-,?).
1891 file_exists2(A,PREDRES) :- b_absolute_file_name(A,AA),
1892 (file_exists(AA) -> PREDRES=pred_true ; PREDRES=pred_false).
1893
1894 :- public 'GET_DIRECTORY_EXISTS'/2.
1895 'GET_DIRECTORY_EXISTS'(S,PREDRES) :- 'DIRECTORY_EXISTS'(S,PREDRES). % synonym as external function
1896 performs_io('DIRECTORY_EXISTS').
1897 external_fun_type('DIRECTORY_EXISTS',[],[string,boolean]).
1898 :- public 'DIRECTORY_EXISTS'/2.
1899 :- block 'DIRECTORY_EXISTS'(-,?).
1900 'DIRECTORY_EXISTS'(string(A),PREDRES) :- dir_exists2(A,PREDRES).
1901 :- block dir_exists2(-,?).
1902 dir_exists2(A,PREDRES) :- b_absolute_file_name(A,AA),
1903 (directory_exists(AA) -> PREDRES=pred_true ; PREDRES=pred_false).
1904
1905 :- use_module(tools,[get_parent_directory/2]).
1906 % a variant of the predicate b_absolute_file_name_relative_to_main_machine in bmachine using safe_call (with span):
1907 b_absolute_file_name(File,AbsFileName) :- b_absolute_file_name(File,AbsFileName,unknown).
1908 b_absolute_file_name(File,AbsFileName,Span) :-
1909 bmachine:b_get_main_filename(MainFileName),!,
1910 get_parent_directory(MainFileName,Directory),
1911 % in Jupyter main file is (machine from Jupyter cell).mch, which confuses SICStus as the file does not exist
1912 safe_call(
1913 absolute_file_name(File,AbsFileName,[relative_to(Directory)]),
1914 Span).
1915 b_absolute_file_name(File,AbsFileName,Span) :-
1916 % call is executed without machine context; we could simply throw an error and fail
1917 safe_call(
1918 absolute_file_name(File,AbsFileName),
1919 Span).
1920
1921 :- public 'GET_FILE_PROPERTY'/3.
1922 'GET_FILE_PROPERTY'(S1,S2,PREDRES) :- 'FILE_PROPERTY'(S1,S2,PREDRES). % synonym as external function
1923 performs_io('FILE_PROPERTY').
1924 external_fun_type('FILE_PROPERTY',[],[string,string,boolean]).
1925 :- public 'FILE_PROPERTY'/3.
1926 :- block 'FILE_PROPERTY'(-,?,?), 'FILE_PROPERTY'(?,-,?).
1927 'FILE_PROPERTY'(string(A),string(P),BoolRes) :-
1928 file_property2(A,P,BoolRes).
1929 :- block file_property2(-,?,?), file_property2(?,-,?).
1930 file_property2(File,Prop,BoolRes) :-
1931 b_absolute_file_name(File,AFile),
1932 file_property(AFile,Prop) -> BoolRes=pred_true ; BoolRes=pred_false.
1933 % possible properties: readable, writable, executable
1934
1935 performs_io('FILE_PROPERTY_VALUE').
1936 external_fun_type('FILE_PROPERTY_VALUE',[],[string,string,integer]).
1937 :- public 'FILE_PROPERTY_VALUE'/3.
1938 :- block 'FILE_PROPERTY_VALUE'(-,?,?), 'FILE_PROPERTY_VALUE'(?,-,?).
1939 'FILE_PROPERTY_VALUE'(string(A),string(P),int(R)) :-
1940 file_property_val2(A,P,R).
1941 :- block file_property_val2(-,?,?), file_property_val2(?,-,?).
1942 file_property_val2(File,Prop,Res) :-
1943 b_absolute_file_name(File,AFile),
1944 file_property(AFile,Prop,Val) -> Res=Val
1945 ; add_error(external_functions,'Illegal FILE_PROPERTY',Prop),Res=int(-1).
1946 % possible properties:
1947 % size_in_bytes, create_timestamp, modify_timestamp, access_timestamp
1948 % + on unix the follwing is also an integer: owner_user_id, owner_group_id
1949
1950 :- public 'GET_DIRECTORY_PROPERTY'/3.
1951 'GET_DIRECTORY_PROPERTY'(S1,S2,PREDRES) :- 'DIRECTORY_PROPERTY'(S1,S2,PREDRES). % synonym as external function
1952 performs_io('DIRECTORY_PROPERTY').
1953 external_fun_type('DIRECTORY_PROPERTY',[],[string,string,boolean]).
1954 :- public 'DIRECTORY_PROPERTY'/3.
1955 :- block 'DIRECTORY_PROPERTY'(-,?,?), 'DIRECTORY_PROPERTY'(?,-,?).
1956 'DIRECTORY_PROPERTY'(string(A),string(P),BoolRes) :-
1957 dir_property2(A,P,BoolRes).
1958 :- block dir_property2(-,?,?), dir_property2(?,-,?).
1959 dir_property2(File,Prop,BoolRes) :-
1960 b_absolute_file_name(File,AFile),
1961 directory_property(AFile,Prop) -> BoolRes=pred_true ; BoolRes=pred_false.
1962
1963 performs_io('DIRECTORY_PROPERTY_VALUE').
1964 external_fun_type('DIRECTORY_PROPERTY_VALUE',[],[string,string,integer]).
1965 :- public 'DIRECTORY_PROPERTY_VALUE'/3.
1966 :- block 'DIRECTORY_PROPERTY_VALUE'(-,?,?), 'DIRECTORY_PROPERTY_VALUE'(?,-,?).
1967 'DIRECTORY_PROPERTY_VALUE'(string(A),string(P),int(R)) :-
1968 dir_property_val2(A,P,R).
1969 :- block dir_property_val2(-,?,?), dir_property_val2(?,-,?).
1970 dir_property_val2(File,Prop,Res) :-
1971 b_absolute_file_name(File,AFile),
1972 directory_property(AFile,Prop,Val) -> Res=Val
1973 ; add_error(external_functions,'Illegal DIRECTORY_PROPERTY',Prop), Res=int(-1).
1974 % --------------------------------
1975
1976 % I/O
1977
1978
1979 % printf as predicate; can also be used as a function to BOOL
1980 expects_spaninfo('fprintf').
1981 external_pred_always_true('fprintf').
1982 :- public fprintf/5.
1983 :- block fprintf(-,?,?,?,?), fprintf(?,-,?,?,?), fprintf(?,?,-,?,?).
1984 fprintf(string(File),string(FormatString),Value,PredRes,Span) :- !, PredRes = pred_true,
1985 when((ground(FormatString),ground(Value)),
1986 fprintf2(File,FormatString,Value,Span)).
1987 fprintf(File,F,V,P,S) :- add_internal_error('Illegal call: ',fprintf(File,F,V,P,S)), P=pred_true.
1988
1989 expects_spaninfo('printf_opt_trace').
1990 external_pred_always_true('printf_opt_trace').
1991 :- public printf_opt_trace/5.
1992 :- block printf_opt_trace(-,?,?,?,?), printf_opt_trace(?,-,?,?,?).
1993 printf_opt_trace(string(FormatString),Value,Trace,PredRes,Span) :- !, PredRes = pred_true,
1994 when((ground(FormatString),ground(Value)),
1995 (fprintf2(user_output,FormatString,Value,Span),
1996 (Trace==pred_true -> try_trace ; true)
1997 )
1998 ).
1999 printf_opt_trace(F,V,T,P,S) :- add_internal_error('Illegal call: ',printf_opt_trace(F,V,T,P,S)), P=pred_true.
2000
2001 % try to perform trace commend if we are not in compiled version
2002 try_trace :-
2003 catch(trace, error(existence_error(_,_),_), (
2004 format('Cannot trace into source code in compiled version of ProB!~n<<<Type RETURN-Key to continue>>>',[]),
2005 read_line(user_input,_),nl
2006 )).
2007
2008 expects_spaninfo('printf').
2009 external_pred_always_true('printf').
2010 external_fun_type('printf',[T],[string,seq(T),boolean]).
2011
2012 :- assert_must_succeed(external_functions:printf(string('test ok = ~w~n'),[(int(1),pred_true)],pred_true,unknown)).
2013 :- block printf(-,?,?,?), printf(?,-,?,?).
2014 printf(string(FormatString),Value,PredRes,Span) :- !, PredRes = pred_true,
2015 when((ground(FormatString),ground(Value)),
2016 fprintf2(user_output,FormatString,Value,Span)).
2017 printf(F,V,P,S) :- add_internal_error('Illegal call: ',printf(F,V,P,S)), P=pred_true.
2018
2019 expects_spaninfo('printf_two'). % print two values, triggers as soon as first value is known
2020 external_pred_always_true('printf_two').
2021 :- assert_must_succeed(external_functions:printf_two(string('test ok = ~w~n'),[(int(1),pred_true)],string('test ok = ~w~n'),[(int(1),pred_true)],pred_true,unknown)).
2022 :- public printf_two/6.
2023 :- block printf_two(-,?,?,?,?,?), printf_two(?,-,?,?,?,?).
2024 printf_two(string(FormatString),Value,string(FormatString2),Value2,PredRes,Span) :- !, PredRes = pred_true,
2025 when((ground(FormatString),ground(Value)),
2026 (fprintf2(user_output,FormatString,Value,Span),
2027 fprintf2(user_output,FormatString2,Value2,Span))).
2028 printf_two(F,V,F2,V2,P,S) :- add_internal_error('Illegal call: ',printf_two(F,V,F2,V2,P,S)), P=pred_true.
2029
2030
2031 expects_spaninfo('printf_nonvar'). % print as soon as value becomes nonvar (printf waits until the value is ground)
2032 external_pred_always_true('printf_nonvar').
2033 :- public printf_nonvar/4.
2034 :- block printf_nonvar(-,?,?,?), printf_nonvar(?,-,?,?).
2035 printf_nonvar(string(FormatString),Value,PredRes,Span) :- !, PredRes = pred_true,
2036 when((ground(FormatString),nonvar(Value)),
2037 fprintf2(user_output,FormatString,Value,Span)).
2038 printf_nonvar(F,V,P,S) :- add_internal_error('Illegal call: ',printf(F,V,P,S)), P=pred_true.
2039
2040
2041 expects_spaninfo('dprintf'). % a version of printf which delays setting itself to TRUE until printing is performed
2042 external_pred_always_true('dprintf').
2043 :- public dprintf/4.
2044 :- block dprintf(-,?,?,?), dprintf(?,-,?,?).
2045 dprintf(string(FormatString),Value,PredRes,Span) :- !,
2046 when((ground(FormatString),ground(Value)),
2047 (fprintf2(user_output,FormatString,Value,Span),PredRes = pred_true)).
2048 dprintf(F,V,P,S) :- add_internal_error('Illegal call: ',dprintf(F,V,P,S)), P=pred_true.
2049
2050 :- use_module(kernel_strings,[convert_b_sequence_to_list_of_atoms/3]).
2051 fprintf2(File,FormatString,Value,Span) :-
2052 convert_b_sequence_to_list_of_atoms(Value,ListOfAtoms,Done),
2053 when(nonvar(Done),
2054 (file_format(File,FormatString,ListOfAtoms,Span),
2055 print_hash((FormatString,Value)),
2056 print_stats,
2057 fprint_log_info(File,Span)
2058 )).
2059 %fprintf2(File,FormatString,Value,Span) :- print('BACKTRACKING ') , file_format(File,FormatString,['?'],Span),nl,fail.
2060 % warning: format can call an argument as goal with ~@; this is dangerous
2061 % and we should prohibit this
2062 % Luckily PRINTF("@: <>~@<>~n","print(danger)") where print(danger)
2063 % is arbitrary code is not a security exploit:
2064 % our PRINTF translates the argument to an atom, i.e., one could
2065 % only call Prolog predicates without arguments, anything else leads to an exception
2066 % (even PRINTF("@: <>~@<>~n","nl") leads to an exception)
2067
2068
2069 :- use_module(hashing,[my_term_hash/2]).
2070 % optionally print hash and allow breakpoints
2071 print_hash(V) :-
2072 external_fun_pref(printf_hash,'TRUE'), % use SET_PREF("printf_hash","TRUE")
2073 !,
2074 my_term_hash(V,H), format('% HASH = ~w~n',H),
2075 %((H = 158201315 ; H=29759067) -> trace ; true),
2076 true.
2077 print_hash(_).
2078
2079
2080 :- use_module(probsrc(tools),[statistics_memory_used/1]).
2081 :- dynamic nr_of_printfs/1.
2082 nr_of_printfs(0).
2083 print_stats :-
2084 external_fun_pref(printf_stats,PFS), % use SET_PREF("printf_stats","TRUE")
2085 PFS='TRUE',
2086 retract(nr_of_printfs(N)),
2087 !,
2088 N1 is N+1,
2089 assertz(nr_of_printfs(N1)),
2090 statistics(walltime,[X,SL]),
2091 statistics_memory_used(M), MB is M / 1000000, % used instead of deprecated 1048576,
2092 statistics(gc_count,GCs),
2093 format('% Call ~w at walltime ~w ms (since last ~w ms), memory ~3f MB (~w GCs)~n',[N1,X,SL,MB,GCs]).
2094 print_stats.
2095
2096 :- dynamic external_fun_pref/2.
2097 % valid keys: log_info
2098 valid_external_fun_pref(log_info).
2099 valid_external_fun_pref(printf_stats).
2100 valid_external_fun_pref(printf_hash).
2101
2102 fprint_log_info(File,Span) :- external_fun_pref(log_info,X),
2103 'GET_INFO'(string(X),string(Res)),
2104 file_format(File,'%%% ~w~n',[Res],Span).
2105 fprint_log_info(_,_).
2106
2107 % example usage SET_PREF("log_info","time") or SET_PREF("printf_stats","TRUE")
2108 external_fun_type('SET_PREF',[],[string,string,boolean]).
2109 :- public 'SET_PREF'/3.
2110 :- block 'SET_PREF'(-,?,?), 'SET_PREF'(?,-,?).
2111 'SET_PREF'(string(S),string(Val),R) :-
2112 preferences:eclipse_preference(S,Pref),!, R=pred_true,
2113 format('Setting ProB preference ~w := ~w~n',[S,Val]),
2114 preferences:set_preference(Pref,Val).
2115 'SET_PREF'(string(S),string(Val),R) :- valid_external_fun_pref(S),!,
2116 R=pred_true,
2117 retractall(external_fun_pref(S,_)),
2118 format('Setting external function preference ~w := ~w~n',[S,Val]),
2119 assertz(external_fun_pref(S,Val)).
2120 'SET_PREF'(P,V,R) :-
2121 add_internal_error('Illegal call: ','SET_PREF'(P,V,R)), R=pred_false.
2122
2123 external_fun_type('GET_PREF',[],[string,string]).
2124 expects_waitflag('GET_PREF').
2125 expects_spaninfo('GET_PREF').
2126 :- assert_must_succeed(external_functions:'GET_PREF'(string('CLPFD'),string(_),unknown,_)).
2127 :- public 'GET_PREF'/4.
2128 'GET_PREF'(Str,Res,Span,WF) :-
2129 kernel_waitflags:get_wait_flag(10,'GET_PREF',WF,WF10), % will enumerate possible input strings
2130 get_pref2(Str,Res,_,WF10,Span).
2131 external_fun_type('GET_PREF_DEFAULT',[],[string,string]).
2132 expects_waitflag('GET_PREF_DEFAULT').
2133 expects_spaninfo('GET_PREF_DEFAULT').
2134 :- assert_must_succeed(external_functions:'GET_PREF_DEFAULT'(string('CLPFD'),string(true),unknown,_)).
2135 :- public 'GET_PREF_DEFAULT'/4.
2136 'GET_PREF_DEFAULT'(Str,Res,Span,WF) :-
2137 (nonvar(Str) -> true
2138 ; kernel_waitflags:get_wait_flag(10,'GET_PREF',WF,WF10)), % will enumerate possible input strings
2139 get_pref2(Str,_,Res,WF10,Span).
2140
2141 :- block get_pref2(-,?,?,-,?).
2142 get_pref2(string(S),Res,Res2,_,Span) :-
2143 if((preferences:eclipse_preference(S,Pref),
2144 preferences:get_preference(Pref,Val),
2145 preferences:preference_default_value(Pref,DefVal)),
2146 (make_string(Val,Res),make_string(DefVal,Res2)),
2147 (add_error(external_functions,'Illegal argument for GET_PREF: ',S,Span),
2148 fail)).
2149
2150
2151 % printf followed by fail; useful for print fail loops in the REPL
2152 expects_spaninfo('printfail').
2153 :- assert_must_fail(external_functions:printfail(string('test ok = ~w~n'),[(int(1),pred_true)],pred_true,unknown)).
2154 :- block printfail(-,?,?,?), printfail(?,-,?,?).
2155 printfail(string(FormatString),Value,PredRes,Span) :- !, PredRes = pred_true,
2156 when((ground(FormatString),ground(Value)),
2157 (fprintf2(user_output,FormatString,Value,Span),fail)).
2158 printfail(F,V,P,S) :-
2159 add_internal_error('Illegal call: ',printfail(F,V,P,S)), P=pred_true.
2160
2161 % a version of printf with automatic indenting and backtracking feedback
2162 expects_spaninfo('iprintf').
2163 external_pred_always_true('iprintf').
2164 :- assert_must_succeed(external_functions:iprintf(string('test ok = ~w~n'),[(int(1),pred_true)],pred_true,unknown)).
2165 :- block iprintf(-,?,?,?), iprintf(?,-,?,?).
2166 iprintf(string(FormatString),Value,PredRes,Span) :- !, PredRes = pred_true,
2167 when((ground(FormatString),ground(Value)),
2168 ifprintf2(user_output,FormatString,Value,no_trace,Span)).
2169 iprintf(F,V,P,S) :- add_internal_error('Illegal call: ',iprintf(F,V,P,S)), P=pred_true.
2170 ifprintf2(File,FormatString,Value,Trace,Span) :-
2171 my_term_hash((FormatString,Value),Hash),
2172 format(user_output,'[hash ~w] ',[Hash]), % (Hash=1087266573122589201 -> (trace ; trace,fail) ; true),
2173 translate:translate_bvalue(Value,TV),
2174 indent_format(File,FormatString,[TV],Trace),
2175 fprint_log_info(File,Span).
2176 expects_spaninfo('itprintf').
2177 external_pred_always_true('itprintf').
2178 :- public itprintf/4.
2179 :- block itprintf(-,?,?,?), itprintf(?,-,?,?).
2180 itprintf(string(FormatString),Value,PredRes,Span) :- PredRes = pred_true,
2181 when((ground(FormatString),ground(Value)),
2182 ifprintf2(user_output,FormatString,Value,trace,Span)).
2183
2184 % ---------------
2185
2186 % a more light-weight version of observe_indent below
2187 :- public observe/5.
2188 expects_spaninfo('observe').
2189 expects_unevaluated_args('observe').
2190 expects_waitflag('observe').
2191 external_pred_always_true('observe').
2192 external_fun_type('observe',[T],[T,boolean]).
2193 observe(Value,PredRes,[Arg],Span,WF) :-
2194 observe6(Value,PredRes,[Arg],Span,_,WF).
2195
2196 % a version which does not print instantiations; just registers them and the patterns
2197 % can be inspected later with -prob-profile (calling portray_instantiations)
2198 :- public observe_silent/5.
2199 expects_spaninfo('observe_silent').
2200 expects_unevaluated_args('observe_silent').
2201 expects_waitflag('observe_silent').
2202 external_pred_always_true('observe_silent').
2203 external_fun_type('observe_silent',[T],[T,boolean]).
2204 observe_silent(Value,PredRes,[Arg],Span,WF) :-
2205 observe6(Value,PredRes,[Arg],Span,silent,WF).
2206
2207 observe6(Value,PredRes,[Arg],_Span,IndentVar,WF) :-
2208 observe_couples(Value,Arg,IndentVar,WF),
2209 PredRes=pred_true,
2210 (Arg\=b(couple(_,_),_,_)
2211 -> true
2212 ; translate_bexpression(Arg,AS),
2213 ground_value_check(Value,GrVal),
2214 block_print_value_complete(GrVal,AS,Value,IndentVar,WF)
2215 ).
2216
2217 observe_couples((V1,V2),b(couple(A1,A2),_,_),IndentVar,WF) :- !,
2218 observe_couples(V1,A1,IndentVar,WF),
2219 observe_couples(V2,A2,IndentVar,WF).
2220 observe_couples(Val,Arg,IndentVar,WF) :-
2221 translate_bexpression(Arg,ArgString),
2222 (IndentVar==silent -> true ; format(user_output,' observing ~w~n',[ArgString])), % for values we could print_span
2223 ground_value_check(Val,GrVal),
2224 block_print_value(GrVal,ArgString,Val,IndentVar,WF).
2225
2226 :- block block_print_value(-,?,?,?,?).
2227 block_print_value(_,ArgString,V,IndentVar,WF) :-
2228 print_value(ArgString,V,IndentVar,WF).
2229 print_value(ArgString,V,IndentVar,WF) :-
2230 register_instantiation_wf(ArgString,WF),
2231 (IndentVar==silent -> true
2232 ; translate_bvalue(V,VS), statistics(walltime,[WT,_]),
2233 get_wf_summary(WF,WS),
2234 indent_var(IndentVar),
2235 format(user_output,' ~w = ~w (walltime: ~w ms) ~w~n',[ArgString,VS,WT,WS])
2236 %,set_prolog_flag(profiling,on), print_profile
2237 ).
2238 :- block block_print_value_complete(-,?,?,?,?).
2239 block_print_value_complete(_,ArgString,V,IndentVar,WF) :- print_value_complete(ArgString,V,IndentVar,WF).
2240 print_value_complete(ArgString,V,IndentVar,WF) :-
2241 register_instantiation_wf(ArgString,WF),
2242 (IndentVar==silent -> true
2243 ; translate_bvalue(V,VS), statistics(walltime,[WT,_]),
2244 get_wf_summary(WF,WS),
2245 indent_var(IndentVar),
2246 format(user_output,'* Value complete: ~w = ~w (walltime: ~w ms) ~w~n------~n',[ArgString,VS,WT,WS])
2247 %,set_prolog_flag(profiling,on), print_profile,trace
2248 ).
2249 % TODO: determine indentation based on overall instantiation of full value
2250
2251 :- use_module(kernel_waitflags,[get_minimum_waitflag_prio/3]).
2252 get_wf_summary(WF,R) :- debug_mode(on),get_minimum_waitflag_prio(WF,MinPrio,_Info),!, R=MinPrio.
2253 get_wf_summary(_,'').
2254
2255 % TODO: store indent var in WF store; so that we can share results/indentation amongst multiple observes
2256 % indent based upon a shared variable and increment it; it displays indentation locally for every observe call
2257 % using put_wf_dynamic_info we could display it for every WF store
2258 indent_var(X) :- var(X),!, X=inst(_). %, register_instantiation(ArgStr,Pred,Level).
2259 indent_var(inst(X)) :- !,print('.'), indent_var(X).
2260 indent_var(_) :- print('***').
2261
2262 % a small utility to observe list of atomic variable names with Prolog value terms
2263 % can be used on Ids,Vars for calls to set_up_localstate(Ids,Vars,LocalState,LetState)
2264 :- public observe_variables/2. %useful for debugging
2265 observe_variables(ListOfIDs,ListOfVals) :- observe_variables(ListOfIDs,ListOfVals,_).
2266 observe_variables([],[],_).
2267 observe_variables([TID|T],[Val|TV],IndentVar) :-
2268 (atomic(TID) -> ID=TID ; get_texpr_id(TID,ID) -> true ; ID=TID),
2269 ground_value_check(Val,GrVal),
2270 block_print_value(GrVal,ID,Val,IndentVar,no_wf_available),
2271 observe_variables(T,TV,IndentVar).
2272
2273 :- dynamic instantiation_link/4, instantiation_level_reached/1.
2274 % keep track of how variables are instantiated in which order
2275 register_instantiation(ArgStr,Pred,Level) :-
2276 (instantiation_level_reached(Level) -> true ; assertz(instantiation_level_reached(Level))),
2277 (retract(instantiation_link(Pred,ArgStr,Level,Hits))
2278 -> H1 is Hits+1
2279 ; H1 is 1),
2280 assertz(instantiation_link(Pred,ArgStr,Level,H1)).
2281
2282 :- use_module(probsrc(preferences), [get_preference/2]).
2283 % register information that this argument/variable is now instantiated:
2284 register_instantiation_wf(ArgInstantiated,WF) :-
2285 (get_wf_dynamic_info(WF,instantiation_info,lvl_prev(Level,PrevArgInstantiated))
2286 -> true
2287 ; Level=0,
2288 (get_preference(provide_trace_information,false)
2289 -> Infos=[] % only have one virtual root
2290 ; get_wait_flag_infos(WF,Infos) %portray_wait_flag_infos(Infos),
2291 % Warning: these Infos can be large terms which get asserted below; they contain the call-stack
2292 ),
2293 PrevArgInstantiated = root(Infos)
2294 ),
2295 register_instantiation(ArgInstantiated,PrevArgInstantiated,Level),
2296 L1 is Level+1,
2297 put_wf_dynamic_info(WF,instantiation_info,lvl_prev(L1,ArgInstantiated)).
2298
2299 reset_observe :- retractall(instantiation_level_reached(_)),
2300 retractall(instantiation_link(_,_,_,_)).
2301
2302 portray_instantiations :-
2303 (instantiation_level_reached(0) -> true),
2304 format('--- ProB instantiation patterns observed ---~n',[]),
2305 instantiation_link(root(Infos),_,0,_),
2306 format('*PATTERNS*~n',[]),
2307 portray_wait_flag_infos(Infos),
2308 (Infos=[],get_preference(provide_trace_information,false)
2309 -> format(' (Set TRACE_INFO preference to TRUE to obtain more information.)~n',[])
2310 ; true),
2311 portray_inst(0,root(Infos)),
2312 fail.
2313 portray_instantiations.
2314
2315 % portray how the instantiations occurred
2316 portray_inst(Level,ArgStr) :-
2317 instantiation_link(ArgStr,Successor,Level,Hits),
2318 i_indent(Level), format(' ~w hits : ~w~n',[Hits,Successor]),
2319 L1 is Level+1,
2320 portray_inst(L1,Successor).
2321
2322 i_indent(X) :- X < 1, !, write('->').
2323 i_indent(X) :- write('-+'), X1 is X-1, i_indent(X1).
2324
2325 % ---------------
2326
2327 :- public observe_indent/5.
2328 expects_spaninfo('observe_indent').
2329 expects_unevaluated_args('observe_indent').
2330 expects_waitflag('observe_indent').
2331 external_pred_always_true('observe_indent').
2332 external_fun_type('observe_indent',[T],[T,boolean]).
2333 % observe pairs of values
2334 observe_indent(Value,PredRes,UnEvalArgs,Span,WF) :-
2335 observe2(Value,PredRes,UnEvalArgs,no_trace,Span,WF).
2336
2337 :- public tobserve/5.
2338 expects_spaninfo('tobserve'). % observe_indent but with tracing enabled
2339 expects_unevaluated_args('tobserve').
2340 expects_waitflag('tobserve').
2341 external_pred_always_true('tobserve').
2342 tobserve(Value,PredRes,UnEvalArgs,Span,WF) :-
2343 observe2(Value,PredRes,UnEvalArgs,trace,Span,WF).
2344
2345 observe2(Value,PredRes,[Arg],Trace,Span,WF) :- PredRes=pred_true,
2346 %kernel_waitflags:portray_waitflags(WF),
2347 kernel_waitflags:get_wait_flag0(WF,WF0),
2348 kernel_waitflags:get_wait_flag1(observe,WF,WF1),
2349 when(nonvar(WF0),(indent_format(user_output,'WAITFLAG 0 set~n',[],no_trace),kernel_waitflags:portray_waitflags(WF))),
2350 when(nonvar(WF1),(indent_format(user_output,'WAITFLAG 1 set~n',[],no_trace),kernel_waitflags:portray_waitflags(WF))),
2351 Hook = print_value_as_table_if_possible(Arg,Value),
2352 observe_aux(Value,Arg,1,_,Trace,Span,Hook),
2353 iprintf(string("observe full value complete: ~w~n~n"),Value,_,Span).
2354
2355 :- use_module(extrasrc(table_tools),[print_value_as_table/2]).
2356 :- public print_value_as_table_if_possible/2. % used as hook above
2357 %print_value_as_table_if_possible(_,_) :- !.
2358 print_value_as_table_if_possible(Arg,Value) :-
2359 translate:print_bexpr(Arg),nl,
2360 (print_value_as_table(Arg,Value) -> true ; true).
2361
2362 observe_aux((V1,V2),b(couple(A1,A2),_,_),Nr,R,Trace,Span,Hook) :- !,
2363 observe_aux(V1,A1,Nr,N1,Trace,Span,Hook),
2364 observe_aux(V2,A2,N1,R,Trace,Span,Hook).
2365 observe_aux(V,Arg,Nr,R,Trace,Span,Hook) :- R is Nr+1,
2366 translate:translate_bexpression(Arg,ArgString), %print(obs(Nr,ArgString)),nl,
2367 atom_codes(ArgString,ArgCodes),
2368 observe_value(V,ArgCodes,Nr,Trace,Span,Hook).
2369
2370 % entry for other modules:
2371 observe_value(Value,Info) :- (Info=[_|_] -> PCodes = Info ; atom_codes(Info,PCodes)),
2372 observe_value(Value,PCodes,1,no_trace,unknown,true).
2373
2374 observe_value(Value,ArgCodes,Nr,Trace,Span,Hook) :- %print(obs(Nr,ArgString)),nl,
2375 number_codes(Nr,NrCodes), append(NrCodes,") = ~w~n",Tail1), append(" (",Tail1,Tail2),
2376 append(ArgCodes,Tail2,FormatString),
2377 observe_set(Value,ArgCodes,1,Trace,Span,Value,Hook),
2378 when((ground(FormatString),ground(Value)),ifprintf2(user_output,FormatString,Value,Trace,Span)).
2379 observe_value_with_full_value(Value,ArgCodes,Nr,Trace,Span,FullValue,Hook) :- %print(obs(Nr,ArgString)),nl,
2380 number_codes(Nr,NrCodes), append(NrCodes,"):FULL = ~w~n",Tail1), append(" (",Tail1,Tail2),
2381 append(ArgCodes,Tail2,FormatString),
2382 observe_set(Value,ArgCodes,1,Trace,Span,Value,Hook),
2383 when((ground(FormatString),ground(Value)),
2384 observe_ground(FormatString,Value,FullValue,Trace,Span,Hook)).
2385
2386 observe_ground(FormatString,Value,FullValue,Trace,Span,Hook) :-
2387 ifprintf2(user_output,FormatString,rec([field(value,Value),field(full,FullValue)]),Trace,Span),
2388 (call(Hook) -> true ; print(hook_failed(Hook)),nl).
2389
2390
2391
2392 % observe sets and records:
2393 :- block observe_set(-,?,?,?,?,?,?).
2394 observe_set([],_ArgCodes,_,_Trace,_Span,_,_) :- !.
2395 observe_set([Value|T],ArgCodes,Pos,Trace,Span,FullValue,Hook) :- !, %print(obs(Value,Pos)),nl,
2396 append(ArgCodes," el -> ",ArgN),
2397 observe_value_with_full_value(Value,ArgN,Pos,Trace,Span,FullValue,Hook),
2398 %tools_files:put_codes(ArgN,user_output),print(Pos),print(' = '),tools_printing:print_arg(Value),nl,
2399 P1 is Pos+1, observe_set(T,ArgCodes,P1,Trace,Span,FullValue,Hook).
2400 observe_set((V1,V2),ArgCodes,Pos,Trace,Span,FullValue,Hook) :-
2401 preferences:preference(observe_precise_values,true),
2402 !, %print(obs(Value,Pos)),nl,
2403 append(ArgCodes," prj1 -> ",ArgN1),
2404 observe_value_with_full_value(V1,ArgN1,Pos,Trace,Span,FullValue,Hook),
2405 %tools_files:put_codes(ArgN,user_output),print(Pos),print(' = '),tools_printing:print_arg(Value),nl,
2406 Pos2 is Pos+1,
2407 append(ArgCodes," prj2 -> ",ArgN2),
2408 observe_value_with_full_value(V2,ArgN2,Pos2,Trace,Span,FullValue,Hook).
2409 observe_set(rec(Fields),ArgCodes,Pos,Trace,Span,_FullValue,Hook) :-
2410 preferences:preference(observe_precise_values,true),
2411 !,
2412 append(ArgCodes," rec -> ",ArgN),
2413 observe_field(Fields,ArgN,Pos,Trace,Span,Hook).
2414 observe_set(_,_,_,_,_,_,_).
2415
2416 :- block observe_field(-,?,?,?,?,?).
2417 observe_field([],ArgN,Pos,Trace,Span,_Hook) :-
2418 append(ArgN," complete (~w)~n",FormatString),
2419 ifprintf2(user_output,FormatString,Pos,Trace,Span).
2420 observe_field([field(Name,Value)|TFields],ArgN,Pos,Trace,Span,Hook) :-
2421 observe_value((string(Name),Value),ArgN,Pos,Trace,Span,Hook),
2422 observe_field(TFields,ArgN,Pos,Trace,Span,Hook).
2423
2424 :- use_module(bsyntaxtree,[get_texpr_id/2]).
2425 :- use_module(store,[lookup_value_with_span_wf/6]).
2426 % utility function for other modules to use observe on parameters
2427 observe_parameters(Parameters,LocalState) :-
2428 skel(LocalState,SetupDone),
2429 reset_ident, reset_walltime,
2430 when(nonvar(SetupDone),observe_parameters_aux(Parameters,1,LocalState)).
2431 :- block skel(-,?).
2432 skel([],pred_true).
2433 skel([_|T],Done) :- skel(T,Done).
2434 :- block observe_parameters_aux(-,?,?), observe_parameters_aux(?,?,-).
2435 observe_parameters_aux([],_,_).
2436 observe_parameters_aux([TID|T],Nr,LS) :-
2437 safe_get_texpr_id(TID,ID), atom_codes(ID,PCodes),
2438 lookup_value_with_span_wf(ID,[],LS,Value,TID,no_wf_available),
2439 debug_println(9,observing(ID,Value,LS)),
2440 Hook = print_value_as_table_if_possible(TID,Value),
2441 observe_value(Value,PCodes,Nr,no_trace,unknown,Hook),
2442 N1 is Nr+1,
2443 observe_parameters_aux(T,N1,LS).
2444 safe_get_texpr_id(TID,ID) :- (atom(TID) -> ID=TID ; get_texpr_id(TID,ID)).
2445
2446 construct_bind(Id,V,bind(Id,V)).
2447 % observe a list of identifiers and values
2448 :- public observe_state/2. % debugging utility
2449 observe_state(Ids,Values) :-
2450 maplist(construct_bind,Ids,Values,State),!,
2451 observe_state(State).
2452 observe_state(Ids,Values) :- add_internal_error('Illegal id and value lists: ',observe_state(Ids,Values)).
2453
2454 % utility to observe a state using the observe external function
2455 observe_state(State) :-
2456 reset_ident, reset_walltime,
2457 observe_state_aux(State,1).
2458 :- block observe_state_aux(-,?).
2459 observe_state_aux(no_state,_) :- !.
2460 observe_state_aux([],_) :- !.
2461 observe_state_aux(concrete_constants(C),Nr) :- !, observe_state_aux(C,Nr).
2462 observe_state_aux([Binding|T],Nr) :- get_binding_value(Binding,Nr,PCodes,Value),!,
2463 %print(observe(Id,Value,Nr,T)),nl,
2464 observe_value(Value,PCodes,Nr,no_trace,unknown,true),
2465 N1 is Nr+1,
2466 observe_state_aux(T,N1).
2467 observe_state_aux(State,Nr) :- add_internal_error('Illegal state: ',observe_state_aux(State,Nr)).
2468
2469 :- block get_binding_value(-,?,?,?).
2470 get_binding_value(bind(Id,Value),_,PCodes,Value) :- atom_codes(Id,PCodes).
2471 get_binding_value(typedval(Value,_Type,Id,_Trigger),_,PCodes,Value) :- atom_codes(Id,PCodes).
2472 get_binding_value(Value,Nr,PCodes,Value) :- number_codes(Nr,PCodes). % we have just a list of values without ids
2473
2474
2475 external_fun_type('observe_fun',[X],[X,boolean]).
2476 expects_unevaluated_args('observe_fun').
2477 external_pred_always_true('observe_fun').
2478 :- public observe_fun/3.
2479 % a specific predicate to observe enumeration of functions,...
2480 :- block observe_fun(-,-,?).
2481 observe_fun(Value,PredRes,[UnEvalArg]) :-
2482 translate:translate_bexpression(UnEvalArg,Str), format('Observe function : ~w~n',[Str]),
2483 obs_fun(Value,Str,Value),PredRes=pred_true.
2484
2485 :- block obs_fun(-,?,?).
2486 obs_fun([],_,_) :- !.
2487 obs_fun([(A,B)|T],Str,FullVal) :- !,
2488 obs_idx(A,B,Str,FullVal),
2489 obs_fun(T,Str,FullVal).
2490 obs_fun(V,Str,_) :- print(uncovered_obs_fun(V,Str)),nl.
2491
2492 :- block obs_idx(-,?,?,?), obs_idx(?,-,?,?).
2493 obs_idx(A,B,Str,FullVal) :-
2494 when(ground((A,B)),obs_idx_complete(FullVal,A,B,Str)).
2495
2496 obs_idx_complete(FullVal,A,B,Str) :-
2497 format('~n ~w = ',[Str]),obs_idx_complete_aux(FullVal,A,B).
2498 obs_idx_complete(FullVal,A,B,Str) :-
2499 format('~n [BACKTRACK] ~w = ',[Str]),obs_idx_complete_aux(FullVal,A,B),fail.
2500
2501 obs_idx_complete_aux(V,_,_) :- var(V),!,print(' OPEN '),nl.
2502 obs_idx_complete_aux([],_,_) :- !, nl.
2503 obs_idx_complete_aux([(X,Y)|T],A,B) :- !,
2504 ((X,Y)==(A,B) -> print(' * ') ; print(' ')), print_bvalue((X,Y)),
2505 obs_idx_complete_aux(T,A,B).
2506 obs_idx_complete_aux(_,_,_) :- print(unknown),nl.
2507
2508
2509 % -----------------------------
2510
2511 :- public tprintf/4.
2512 expects_spaninfo('tprintf').
2513 external_pred_always_true('tprintf').
2514 % a debugging version that switches into trace mode
2515 :- block tprintf(-,?,?,?), tprintf(?,-,?,?).
2516 tprintf(string(FormatString),Value,PredRes,Span) :- PredRes = pred_true,
2517 when((ground(FormatString),ground(Value)),
2518 (fprintf2(user_output,FormatString,Value,Span),
2519 try_trace %,print_profile,set_prolog_flag(profiling,on)
2520 )).
2521
2522 :- public 'prolog_printf'/5.
2523 expects_spaninfo('prolog_printf').
2524 expects_waitflag('prolog_printf').
2525 external_pred_always_true('prolog_printf').
2526 prolog_printf(string(FormatString),Value,PredRes,Span,WF) :- PredRes = pred_true,
2527 file_format(user_output,FormatString,[initial(Value,WF)],Span),
2528 when(nonvar(Value),file_format(user_output,FormatString,[nonvar(Value,WF)],Span)),
2529 when((ground(FormatString),ground(Value)),
2530 fprintf2(user_output,FormatString,Value,Span)).
2531
2532 % vprintf: expression which returns argument as value
2533 expects_spaninfo('vprintf').
2534 external_fun_type('vprintf',[T],[string,T,T]).
2535 :- public vprintf/4.
2536 vprintf(Format,Value,ValueRes,Span) :-
2537 printf(Format,[(int(1),Value)],pred_true,Span), % use itprintf for tracing
2538 equal_object(Value,ValueRes,vprintf). % we could generate a version which only instantiates when printing done
2539 expects_spaninfo('fvprintf').
2540 :- public fvprintf/5.
2541 fvprintf(File,Format,Value,ValueRes,Span) :-
2542 fprintf(File,Format,[(int(1),Value)],pred_true,Span),
2543 equal_object(Value,ValueRes,fvprintf). % we could generate a version which only instantiates when printing done
2544
2545
2546 % PRINT a single value as substitution
2547 performs_io('PRINT').
2548 external_subst_enabling_condition('PRINT',_,Truth) :- create_texpr(truth,pred,[],Truth).
2549 does_not_modify_state('PRINT').
2550 :- public 'PRINT'/3.
2551 :- block 'PRINT'(-,?,?), 'PRINT'(?,-,?).
2552 'PRINT'(Val,_Env,OutEnv) :- %print('PRINT : '), print(Env),nl,
2553 assert_side_effect_occurred(user_output),
2554 print_value(Val),nl, OutEnv=[].
2555
2556 % PRINT a single value as substitution; show backtracking
2557 performs_io('PRINT_BT').
2558 perform_directly('PRINT_BT').
2559 external_subst_enabling_condition('PRINT_BT',_,Truth) :- create_texpr(truth,pred,[],Truth).
2560 does_not_modify_state('PRINT_BT').
2561 :- public 'PRINT_BT'/3.
2562 :- block 'PRINT_BT'(-,?,?), 'PRINT_BT'(?,-,?).
2563 'PRINT_BT'(Val,_Env,OutEnv) :- %print('PRINT : '), print(Env),nl,
2564 assert_side_effect_occurred(user_output),
2565 print_value(Val),nl, OutEnv=[].
2566 'PRINT_BT'(Val,_Env,_OutEnv) :-
2567 assert_side_effect_occurred(user_output),
2568 print('BACKTRACKING: '),print_value(Val),nl, fail.
2569
2570 print_value(Val) :- translate:translate_bvalue(Val,TV), print(TV).
2571
2572
2573 performs_io('DEBUG_PRINT_STATE').
2574 external_subst_enabling_condition('DEBUG_PRINT_STATE',_,Truth) :- create_texpr(truth,pred,[],Truth).
2575 does_not_modify_state('DEBUG_PRINT_STATE').
2576 :- public 'DEBUG_PRINT_STATE'/3.
2577 :- block 'DEBUG_PRINT_STATE'(-,?,?).
2578 'DEBUG_PRINT_STATE'(Value,Env,OutEnv) :-
2579 assert_side_effect_occurred(user_output),
2580 print_value(Value),translate:print_bstate(Env),nl, OutEnv=[].
2581
2582 % PRINTF as substitution
2583 expects_spaninfo('PRINTF').
2584 performs_io('PRINTF').
2585 external_subst_enabling_condition('PRINTF',_,Truth) :- create_texpr(truth,pred,[],Truth).
2586 does_not_modify_state('PRINTF').
2587 :- public 'PRINTF'/5.
2588 :- block 'PRINTF'(-,?,?,?,?), 'PRINTF'(?,-,?,?,?), 'PRINTF'(?,?,-,?,?).
2589 'PRINTF'(string(FormatString),Value,_Env,OutEnvModifications,Span) :-
2590 % print('PRINTF'(FormatString,Value,_Env)),nl,
2591 when((ground(FormatString),ground(Value)),
2592 (fprintf2(user_output,FormatString,Value,Span),
2593 OutEnvModifications=[] /* substitution finished */
2594 )).
2595
2596 expects_spaninfo('FPRINTF').
2597 performs_io('FPRINTF').
2598 external_subst_enabling_condition('FPRINTF',_,Truth) :- create_texpr(truth,pred,[],Truth).
2599 does_not_modify_state('FPRINTF').
2600 :- public 'FPRINTF'/6.
2601 :- block 'FPRINTF'(-,?,?,?,?,?), 'FPRINTF'(?,-,?,?,?,?), 'FPRINTF'(?,?,-,?,?,?).
2602 'FPRINTF'(string(File),string(FormatString),Value,_Env,OutEnvModifications,Span) :-
2603 when((ground(FormatString),ground(Value)),
2604 (fprintf2(File,FormatString,Value,Span),
2605 OutEnvModifications=[] /* substitution finished */
2606 )).
2607
2608 file_format(user_output,FormatString,Args,Span) :- !,
2609 assert_side_effect_occurred(user_output),
2610 safe_call(myformat(user_output,FormatString,Args,Span),Span).
2611 file_format(File,FormatString,Args,Span) :-
2612 open(File,append,Stream,[encoding(utf8)]),
2613 assert_side_effect_occurred(file),
2614 safe_call(myformat(Stream,FormatString,Args,Span),Span),
2615 close(Stream). % TO DO: call_cleanup
2616
2617 % Simple check if the user forgot to put format specifiers in the format string.
2618 format_string_is_missing_tildes(FormatString) :-
2619 atom_codes(FormatString, Codes),
2620 \+ memberchk(0'~, Codes).
2621
2622 :- meta_predicate catch_format_error(0, 0).
2623 catch_format_error(Goal, Recover) :-
2624 catch(
2625 catch(
2626 Goal,
2627 error(consistency_error(_,_,format_arguments),_), % SICStus
2628 Recover),
2629 error(format(_Message),_), % SWI
2630 Recover).
2631
2632 :- public myformat/4.
2633 myformat(Stream,FormatString,Args,Span) :-
2634 catch_format_error(
2635 (Args \== [], format_string_is_missing_tildes(FormatString) ->
2636 % backup: the user has not provided ~w annotations:
2637 % instead print just the format string and then all arguments separately.
2638 % This case was previously detected by catching format errors,
2639 % but this causes problems with incomplete or duplicated output on SWI,
2640 % because SWI reports errors only during printing
2641 % (unlike SICStus, which checks the entire format string before printing anything).
2642 format(Stream,FormatString,[]),
2643 nl(Stream),
2644 format_args(Stream,Args)
2645 ; format(Stream,FormatString,Args)
2646 ),
2647 (length(Args,NrArgs),
2648 ajoin(['Illegal format string, expecting ',NrArgs,' ~w arguments (see SICStus Prolog reference manual for syntax):'],Msg),
2649 add_error(external_functions,Msg,FormatString,Span),
2650 format_args(Stream,Args))
2651 ),
2652 flush_output(Stream).
2653
2654 format_args(_Stream,[]).
2655 format_args(Stream,[H|T]) :- format(Stream,'~w~n',H), format_args(Stream,T).
2656
2657 % a format with indentation and backtracking info:
2658 :- dynamic indentation_level/1.
2659 indentation_level(0).
2660 inc_indent :- retract(indentation_level(X)), X1 is X+1, assertz(indentation_level(X1)).
2661 dec_indent :- retract(indentation_level(X)), X1 is X-1, assertz(indentation_level(X1)).
2662 reset_ident :- retractall(indentation_level(_)), assertz(indentation_level(0)).
2663 get_indent_level(L) :- indentation_level(LL), L is ceiling(sqrt(LL)).
2664 indent(Stream) :- get_indent_level(L), %(L>28 -> trace ; true),
2665 indent_aux(L,Stream).
2666 indent_aux(X,Stream) :- X < 1, !, write(Stream,' ').
2667 indent_aux(X,Stream) :- write(Stream,'+-'), X1 is X-1, indent_aux(X1,Stream).
2668
2669 indent_format(Stream,Format,Args,Trace) :- inc_indent,
2670 indent(Stream), format(Stream,Format,Args),
2671 print_walltime(Stream),
2672 % my_term_hash(Args,Hash), format(Stream,'[hash ~w]~n',[Hash]), (Hash=101755762 -> trace ; true), %%
2673 flush_output(Stream),
2674 (Trace=trace -> try_trace ; true).
2675 %indent_format(_Stream,_Format,Args,_Trace) :- my_term_hash(Args,Hash),(Hash=553878463258718990 -> try_trace).
2676 indent_format(Stream,Format,Args,Trace) :-
2677 indent(Stream), write(Stream,'BACKTRACKING '),
2678 % my_term_hash(Args,Hash), format(Stream,'[hash ~w] ',[Hash]), %% (Hash=553878463258718990 -> try_trace ; true), %%
2679 format(Stream,Format,Args),
2680 print_walltime(Stream), %% comment in to see walltime info
2681 flush_output(Stream),
2682 dec_indent,
2683 (Trace=trace -> try_trace ; true),
2684 fail.
2685
2686 :- dynamic ref_walltime/1, prev_walltime/1.
2687 reset_walltime :- retractall(prev_walltime(_)), retractall(ref_walltime(_)),
2688 statistics(walltime,[WT,_]),
2689 assertz(prev_walltime(WT)),
2690 assertz(ref_walltime(WT)).
2691 print_walltime(File) :- statistics(walltime,[WT,_]),
2692 (ref_walltime(RefWT) -> RWT is WT-RefWT ; RWT = 0, assertz(ref_walltime(WT))),
2693 (retract(prev_walltime(PWT)) -> T is WT-PWT, indent(File),format(File,' ~w ms (walltime; total ~w ms)~n',[T,RWT])
2694 ; true),
2695 assertz(prev_walltime(WT)).
2696 :- public 'TRACE'/2.
2697 :- block 'TRACE'(-,?).
2698 'TRACE'(pred_true,R) :- !,trace,R=pred_true.
2699 'TRACE'(pred_false,pred_true).
2700
2701 % --------------------------------------------
2702
2703 % ARGV, ARGC
2704
2705 :- dynamic argv_string/2, argc_number/1.
2706 argc_number(0).
2707 reset_argv :-
2708 retractall(argv_string(_,_)),
2709 retractall(argc_number(_)),
2710 assertz(argc_number(0)).
2711
2712 :- use_module(kernel_strings,[split_atom_string/3]).
2713 % call to set the commandline arguments, e.g., from probcli
2714 set_argv_from_atom(X) :-
2715 retractall(argv_string(_,_)),
2716 retractall(argc_number(_)),
2717 split_atom_string(X,' ',List),
2718 set_argv_from_list(List).
2719 set_argv_from_list(List) :-
2720 retractall(argv_string(_,_)),
2721 retractall(argc_number(_)),
2722 set_argv_from_list_aux(List).
2723 set_argv_from_list_aux(List) :-
2724 length(List,Len),
2725 assertz(argc_number(Len)),
2726 debug:debug_println(9,argc(Len)),
2727 nth1(N,List,String), % we number the arguments in B style
2728 debug:debug_println(9,argv(N,String)),
2729 assertz(argv_string(N,String)),
2730 fail.
2731 set_argv_from_list_aux(_).
2732
2733 external_fun_type('ARGV',[],[integer,string]).
2734 % access to the command-line arguments provided to probcli (after --)
2735 % first argument is ARGV(1) not ARGV(0)
2736 :- public 'ARGV'/2.
2737 :- block 'ARGV'(-,?).
2738 'ARGV'(int(N),S) :- argv2(N,S).
2739 :- block argv2(-,?).
2740 argv2(Nr,Res) :- % print(get_argv(Nr,Res)),nl,
2741 (argv_string(Nr,S) -> Res=string(S)
2742 ; Nr=0 -> add_error(external_functions,'Command-line argument does not exist, numbering starts at 1: ',Nr), Res=string('')
2743 ; add_error(external_functions,'Command-line argument does not exist: ',Nr), Res=string('')).
2744
2745 external_fun_type('ARGC',[],[integer]).
2746 :- public 'ARGC'/1.
2747 'ARGC'(int(X)) :- argc_number(X).
2748
2749 % --------------------------------------------
2750
2751 % RANDOM
2752
2753
2754 :- assert_must_succeed(( external_functions:call_external_function('RANDOM',[0,1],[int(0),int(1)],int(0),integer,unknown,_WF) )).
2755 :- use_module(library(random),[random/3, random/1]).
2756
2757 % Generate a random number >= Low and < Up
2758 % warning: this is not a mathematical function
2759 % example usage r=RANDOM(1,6)
2760 :- public 'RANDOM'/3.
2761 is_not_declarative('RANDOM').
2762 external_fun_type('RANDOM',[],[integer,integer,integer]).
2763 :- block 'RANDOM'(-,?,?), 'RANDOM'(?,-,?).
2764 'RANDOM'(int(Low),int(Up),int(R)) :- random2(Low,Up,R).
2765 :- block random2(-,?,?), random2(?,-,?).
2766 random2(L,U,R) :- random(L, U, R). % also works with reals
2767
2768 :- public 'RAND'/3.
2769 % example usage r=RAND(0.0,1.0)
2770 is_not_declarative('RAND').
2771 external_fun_type('RAND',[],[real,real,real]).
2772 :- block 'RAND'(-,?,?), 'RAND'(?,-,?).
2773 'RAND'(RLow,Rup,RR) :- is_real(RLow,Low),
2774 is_real(Rup,Up), is_real(RR,R),
2775 random2(Low,Up,R).
2776
2777
2778 :- use_module(library(between),[between/3]).
2779 :- public 'RAND_SAMPLES'/4.
2780 % example usage r=RAND_SAMPLES(5,0.0,1.0) % takes 5 samples and returns as set
2781 is_not_declarative('RAND_SAMPLES').
2782 external_fun_type('RAND_SAMPLES',[],[integer,real,real,set(real)]).
2783 :- block 'RAND_SAMPLES'(-,?,?,?), 'RAND_SAMPLES'(?,-,?,?), 'RAND_SAMPLES'(?,?,-,?).
2784 'RAND_SAMPLES'(int(Samples),RLow,Rup,RSet) :- is_real(RLow,Low),
2785 is_real(Rup,Up), is_real(RR,R),
2786 findall(RR,(between(1,Samples,_),random2(Low,Up,R)), List),
2787 kernel_objects:equal_object_optimized(List,RSet).
2788
2789
2790 :- public 'RAND_BOOL'/2.
2791 % example usage r=RAND_BOOL(0.2) -> 20 % chance of returning TRUE
2792 is_not_declarative('RAND_BOOL').
2793 external_fun_type('RAND_BOOL',[],[real,boolean]).
2794 :- block 'RAND_BOOL'(-,?).
2795 'RAND_BOOL'(Rlim,RR) :- is_real(Rlim,Limit),
2796 random(X),
2797 (X =< Limit -> RR=pred_true ; RR=pred_false).
2798
2799 % TODO: RANDOM_VALUE({0.2|->"a",0.8|->"b"})
2800
2801 % pick a random element from a set
2802 :- public 'random_element'/4.
2803 is_not_declarative('random_element').
2804 external_fun_type('random_element',[T],[set(T),T]).
2805 expects_waitflag('random_element').
2806 expects_spaninfo('random_element').
2807 :- block 'random_element'(-,?,?,?).
2808 random_element([],_,Span,WF) :- !,
2809 add_wd_error_span('random_element applied to empty set: ',[],Span,WF).
2810 random_element([H|T],El,_,WF) :- !,
2811 expand_custom_set_to_list_wf(T,ET,_Done,'random_element',WF),
2812 block_length(ET,1,Len),
2813 random_select_from_list([H|ET],Len,El).
2814 random_element(CS,Res,_,_) :- is_interval_closure_or_integerset(CS,Low,Up,finite),!, % TODO: also support reals
2815 U1 is Up+1,
2816 random(Low,U1,H), Res = int(H).
2817 random_element(CS,X,Span,WF) :-
2818 custom_explicit_sets:expand_custom_set_wf(CS,ER,random_element,WF),
2819 random_element(ER,X,Span,WF).
2820
2821 :- block block_length(-,?,?).
2822 block_length([],Acc,Acc).
2823 block_length([_|T],Acc,R) :- A1 is Acc+1, block_length(T,A1,R).
2824
2825 :- use_module(library(random),[random_member/2]).
2826 :- block random_select_from_list(?,-,?).
2827 random_select_from_list(List,_,Res) :-
2828 random_member(El,List),
2829 kernel_objects:equal_object(El,Res).
2830
2831 :- use_module(library(random),[random_numlist/4]).
2832 :- public 'random_numset'/6.
2833 is_not_declarative('random_numset').
2834 external_fun_type('random_numset',[],[integer,integer,integer,integer,set(integer)]).
2835 expects_waitflag('random_numset').
2836 :- block random_numset(-,?,?,?,?,?),random_numset(?,-,?,?,?,?),random_numset(?,?,-,?,?,?),random_numset(?,?,?,-,?,?).
2837 random_numset(int(P),int(Q),int(Low),int(Up),Res,WF) :-
2838 Prob is P/Q,
2839 random_numlist(Prob,Low,Up,List),
2840 maplist(gen_int,List,IntList),
2841 kernel_objects:equal_object_optimized_wf(IntList,Res,random_numset,WF).
2842
2843 gen_int(I,int(I)).
2844
2845
2846 :- public 'NORMAL'/3.
2847 is_not_declarative('NORMAL').
2848 external_fun_type('NORMAL',[],[integer,integer,integer]).
2849 % GAUSSIAN Distribution
2850 :- block 'NORMAL'(-,?,?), 'NORMAL'(?,-,?).
2851 'NORMAL'(int(Mu),int(Sigma),int(R)) :- random_normal(Mu,Sigma,R).
2852
2853 :- block random_normal(-,?,-), random_normal(?,-,?).
2854 random_normal(Mu,Sigma,R) :-
2855 random_normal(N),
2856 R is round(Mu+N*Sigma).
2857
2858 :- use_module(kernel_reals,[is_real/2]).
2859 :- public 'RNORMAL'/3.
2860 is_not_declarative('RNORMAL').
2861 external_fun_type('RNORMAL',[],[real,real,real]).
2862 :- block 'RNORMAL'(-,?,?), 'RNORMAL'(?,-,?).
2863 'RNORMAL'(RMU,RSigma,RR) :- is_real(RMU,MU),
2864 is_real(RSigma,Sigma), is_real(RR,R),
2865 random_normal_real(MU,Sigma,R).
2866
2867 :- block random_normal_real(-,?,-), random_normal_real(?,-,?).
2868 random_normal_real(Mu,Sigma,R) :-
2869 random_normal(N),
2870 R is (Mu+N*Sigma).
2871
2872 % inspired by: https://stackoverflow.com/questions/44503752/how-to-generate-normal-distributed-random-numbers-in-prolog
2873 % https://en.wikipedia.org/wiki/Box–Muller_transform
2874 :- dynamic cached_gauss/1.
2875 :- use_module(library(random),[random/1]).
2876 random_normal(R) :- retract(cached_gauss(N)),!,R=N.
2877 random_normal(R) :-
2878 random(U1), random(U2),
2879 Z0 is sqrt(-2 * log(U1)) * cos(2*pi*U2),
2880 Z1 is sqrt(-2 * log(U1)) * sin(2*pi*U2),
2881 assertz(cached_gauss(Z1)),
2882 R = Z0.
2883
2884 :- public 'RPOISSON_COUNT'/2.
2885 is_not_declarative('RPOISSON_COUNT').
2886 external_fun_type('RPOISSON_COUNT',[],[real,integer]).
2887 % draw number of arrivals (integer) within a time-unit of a Poisson distribution
2888 % Note: REXP(-746.0) = 0.0 -> so all values >= 746 lead to same distribution
2889 % TODO: try out other implementation, https://www.johndcook.com/blog/2010/06/14/generating-poisson-random-values/?
2890 :- block 'RPOISSON_COUNT'(-,?).
2891 'RPOISSON_COUNT'(RLambda,Res) :-
2892 is_real(RLambda,Lambda),
2893 poisson_real(Lambda,Res).
2894 :- block poisson_real(-,?).
2895 poisson_real(Lambda,Res) :-
2896 L is exp(-Lambda),
2897 iterate_poisson(0,1.0,L,Res).
2898
2899 % Knuth's Algorithm for generating random samples from a Poisson distribution
2900 % The complexity is linear in the returned value k, which is λ on average.
2901 % https://en.wikipedia.org/wiki/Poisson_distribution#Generating_Poisson-distributed_random_variables
2902 iterate_poisson(K,P,L,Res) :-
2903 random(U), P1 is P*U,
2904 P1 > L,!,
2905 K1 is K+1, iterate_poisson(K1,P1,L,Res).
2906 iterate_poisson(K,_,_,int(K)).
2907
2908 :- public 'RPOISSON_WAIT'/2.
2909 % RPOISSON_WAIT(lambda) == -RLOGe(RAND(0.0,1.0))/lambda;
2910 is_not_declarative('RPOISSON_WAIT').
2911 external_fun_type('RPOISSON_WAIT',[],[real,real]).
2912 % draw number of arrivals (integer) within a time-unit of a Poisson distribution
2913 :- block 'RPOISSON_WAIT'(-,?).
2914 'RPOISSON_WAIT'(RLambda,Res) :-
2915 is_real(RLambda,Lambda),
2916 poisson_wait_real(Lambda,Res).
2917 :- block poisson_wait_real(-,?).
2918 poisson_wait_real(Lambda,Res) :-
2919 random(U),
2920 R is -log(U)/Lambda,
2921 is_real(Res,R).
2922
2923
2924 % generates a random subset of a finite set
2925 :- public 'random_subset'/4.
2926 is_not_declarative('random_subset').
2927 external_fun_type('random_subset',[T],[set(T),set(T)]).
2928 expects_waitflag('random_subset').
2929 expects_spaninfo('random_subset').
2930 :- block 'random_subset'(-,?,?,?).
2931 random_subset(Set,Subset,Span,WF) :- !,
2932 expand_custom_set_to_list_wf(Set,ESet,Done,'random_subset',WF),
2933 random_subset_aux(Done,ESet,Subset,Span,WF).
2934
2935 :- use_module(library(random),[random_subseq/3]).
2936 :- block random_subset_aux(-,?,?,?,?).
2937 random_subset_aux(_Done,ESet,Subset,_Span,WF) :-
2938 random_subseq(ESet,Result,_Rest),
2939 kernel_objects:equal_object_wf(Result,Subset,WF).
2940
2941 % generates a random subset of a finite set
2942 :- public 'random_ordering'/4.
2943 is_not_declarative('random_ordering').
2944 external_fun_type('random_ordering',[T],[set(T),seq(T)]).
2945 expects_waitflag('random_ordering').
2946 expects_spaninfo('random_ordering').
2947 :- block 'random_ordering'(-,?,?,?).
2948 random_ordering(Set,Permutation,Span,WF) :- !,
2949 expand_custom_set_to_list_wf(Set,ESet,Done,'random_ordering',WF),
2950 random_perm_aux(Done,ESet,Permutation,Span,WF).
2951
2952 :- use_module(library(random),[random_permutation/2]).
2953 :- block random_perm_aux(-,?,?,?,?).
2954 random_perm_aux(_Done,ESet,Permutation,_Span,_WF) :-
2955 random_permutation(ESet,Result),
2956 convert_list_to_seq(Result,Permutation). % should we call WF version
2957
2958 % generates a random subset of a finite sequence
2959 :- public 'random_permutation'/4.
2960 is_not_declarative('random_permutation').
2961 external_fun_type('random_permutation',[T],[seq(T),seq(T)]).
2962 expects_waitflag('random_permutation').
2963 expects_spaninfo('random_permutation').
2964 :- block 'random_permutation'(-,?,?,?).
2965 random_permutation(Set,Permutation,Span,WF) :- !,
2966 expand_custom_set_to_list_wf(Set,ESet,Done,'random_permutation',WF),
2967 random_perm_seq_aux(Done,ESet,Permutation,Span,WF).
2968
2969 :- block random_perm_seq_aux(-,?,?,?,?).
2970 random_perm_seq_aux(_Done,ESet,Permutation,_Span,_WF) :-
2971 sort(ESet,Sorted),
2972 maplist(drop_index,Sorted,PrologList),
2973 random_permutation(PrologList,Result),
2974 convert_list_to_seq(Result,Permutation). % should we call WF version
2975
2976 drop_index((int(_),El),El).
2977
2978 :- use_module(library(system)).
2979
2980 :- assert_must_succeed(( external_functions:call_external_function('TIME',[y],[string(year)],int(Y),integer,unknown,_WF), number(Y), Y>2011 )).
2981 :- assert_must_succeed(( external_functions:call_external_function('TIME',[m],[string(month)],int(M),integer,unknown,_WF), number(M), M>0, M<13 )).
2982 external_fun_type('TIME',[],[string,integer]).
2983 :- public 'TIME'/2.
2984 is_not_declarative('TIME'). % as time can change with next call
2985 'TIME'(string(S),int(N)) :- time2(S,N).
2986 :- block time2(-,?).
2987 time2(now,N) :- !, now(N). % provide UNIX timesstamp
2988 time2(year,N) :- !,datime(datime(N,_,_,_,_,_)).
2989 time2(month,N) :- !,datime(datime(_,N,_,_,_,_)).
2990 time2(day,N) :- !,datime(datime(_,_,N,_,_,_)).
2991 time2(hour,N) :- !,datime(datime(_,_,_,N,_,_)).
2992 time2(min,N) :- !,datime(datime(_,_,_,_,N,_)).
2993 time2(sec,N) :- !,datime(datime(_,_,_,_,_,N)).
2994 time2(OTHER,_) :- add_error(time2,'Illegal time field (must be now,year,month,day,hour,min,sec): ',OTHER),fail.
2995
2996 :- assert_must_succeed(( external_functions:call_external_function('GET_INFO',[time],[string(time)],string(M),string,unknown,_WF), atom(M) )).
2997 external_fun_type('GET_INFO',[],[string,string]).
2998 :- public 'GET_INFO'/2.
2999 'GET_INFO'(string(S),Res) :- get_info2(S,Res).
3000 :- use_module(library(codesio)).
3001 :- block get_info2(-,?).
3002 get_info2(time,Res) :- !, datime(datime(Year,Month,Day,Hour,Min,Sec)),
3003 (Min<10
3004 -> format_to_codes('~w/~w/~w - ~wh0~w ~ws',[Day,Month,Year,Hour,Min,Sec],Codes)
3005 ; format_to_codes('~w/~w/~w - ~wh~w ~ws',[Day,Month,Year,Hour,Min,Sec],Codes)
3006 ),
3007 atom_codes(INFO, Codes), Res=string(INFO).
3008 get_info2(OTHER,_) :- add_error(time2,'Illegal GET_INFO field (must be time): ',OTHER),fail.
3009
3010 :- public 'TIMESTAMP_INFO'/3.
3011 :- assert_must_succeed(external_functions:'TIMESTAMP_INFO'(string('year'),int(1498484624),int(2017))).
3012 :- assert_must_succeed(external_functions:'TIMESTAMP_INFO'(string('month'),int(1498484624),int(6))).
3013 % second argument is ticks obtained by TIME("now")
3014 external_fun_type('TIMESTAMP_INFO',[],[string,integer,integer]).
3015 :- block 'TIMESTAMP_INFO'(-,-,-).
3016 'TIMESTAMP_INFO'(string(S),int(Ticks),int(Res)) :- time_info2(S,Ticks,Res).
3017 :- block time_info2(-,?,?), time_info2(?,-,?).
3018 time_info2(year,Ticks,N) :- !,datime(Ticks,datime(N,_,_,_,_,_)).
3019 time_info2(month,Ticks,N) :- !,datime(Ticks,datime(_,N,_,_,_,_)).
3020 time_info2(day,Ticks,N) :- !,datime(Ticks,datime(_,_,N,_,_,_)).
3021 time_info2(hour,Ticks,N) :- !,datime(Ticks,datime(_,_,_,N,_,_)).
3022 time_info2(min,Ticks,N) :- !,datime(Ticks,datime(_,_,_,_,N,_)).
3023 time_info2(sec,Ticks,N) :- !,datime(Ticks,datime(_,_,_,_,_,N)).
3024 time_info2(OTHER,_,_) :- add_error(time_info2,'Illegal time field (must be now,year,month,day,hour,min,sec): ',OTHER),fail.
3025
3026 :- public 'TIMESTAMP'/7.
3027 % TIMESTAMP/datime converts between a Unix timestamp (UTC) and *local* time.
3028 % To avoid depending on the system time zone,
3029 % build the timestamp dynamically based on the expected test date.
3030 % This way the timestamp varies slightly depending on the system time zone,
3031 % but the date will always be consistent.
3032 % in LibraryIO.def
3033 :- assert_must_succeed((
3034 datime(Timestamp, datime(2017,6,26,15,43,44)),
3035 % Sanity check to ensure that Timestamp is roughly in the right range.
3036 Timestamp >= 1498437824, Timestamp =< 1498545824,
3037 external_functions:'TIMESTAMP'(int(2017),int(6),int(26),int(H),int(Min),int(S),int(Timestamp)),
3038 H==15, Min==43, S==44
3039 )).
3040 external_fun_type('TIMESTAMP',[],[integer,integer,integer,integer,integer,integer,integer]).
3041 :- block 'TIMESTAMP'(-,-,-,-,-,-,-).
3042 'TIMESTAMP'(int(Y),int(M),int(D),int(H),int(Min),int(S),int(Res)) :-
3043 timestamp2(Y,M,D,H,Min,S,Res).
3044
3045 :- block timestamp2(-,?,?,?,?,?,-), timestamp2(?,-,?,?,?,?,-), timestamp2(?,?,-,?,?,?,-),
3046 timestamp2(?,?,?,-,?,?,-), timestamp2(?,?,?,?,?,-,-).
3047 timestamp2(Y,M,D,H,Min,S,ResTimeStamp) :- datime(ResTimeStamp, datime(Y,M,D,H,Min,S)).
3048
3049
3050 :- public 'WALLTIME'/1.
3051 is_not_declarative('WALLTIME'). % as time can change with next call
3052 'WALLTIME'(int(X)) :- statistics(walltime,[X,_]).
3053
3054 :- volatile last_walltime/1.
3055 :- dynamic last_walltime/1.
3056 :- public 'DELTA_WALLTIME'/1.
3057 is_not_declarative('DELTA_WALLTIME'). % as time can change with next call
3058 'DELTA_WALLTIME'(int(D)) :- statistics(walltime,[X,_]),
3059 (retract(last_walltime(L)) -> D is X-L ; D = 0),
3060 assertz(last_walltime(X)).
3061
3062 :- public 'RUNTIME'/1.
3063 is_not_declarative('RUNTIME'). % as time can change with next call
3064 'RUNTIME'(int(X)) :- statistics(runtime,[X,_]).
3065
3066 :- public 'SLEEP'/3.
3067 external_subst_enabling_condition('SLEEP',_,Truth) :- create_texpr(truth,pred,[],Truth).
3068 :- use_module(library(system),[sleep/1]).
3069 :- block 'SLEEP'(-,?,?), 'SLEEP'(?,-,?).
3070 'SLEEP'(int(X),_Env,OutEnvModifications) :- when(nonvar(X),
3071 (Seconds is X / 1000, sleep(Seconds), OutEnvModifications=[])).
3072 'SLEEP'(term(floating(X)),_Env,OutEnvModifications) :- when(nonvar(X),
3073 (Seconds is X / 1000, sleep(Seconds), OutEnvModifications=[])).
3074
3075
3076 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3077 % check if a given expression is valued in the deterministic phase; warn otherwise
3078
3079 :- use_module(kernel_tools,[ground_value_check/2]).
3080 expects_spaninfo('CHECK_DET').
3081 expects_unevaluated_args('CHECK_DET').
3082 expects_waitflag('CHECK_DET').
3083 :- public 'CHECK_DET'/5.
3084 'CHECK_DET'(Value,PredRes,[UnEvalArg],Span,WF) :-
3085 ground_value_check(Value,Ground),
3086 kernel_waitflags:get_wait_flag0(WF,WF0),
3087 kernel_waitflags:get_wait_flag1(WF,WF1),
3088 PredRes=pred_true,
3089 check_det_aux(Ground,Value,WF0,WF1,UnEvalArg,Span).
3090
3091 :- block check_det_aux(-,?,?,-,?,?).
3092 check_det_aux(Ground,Value,_WF0,_WF1,UnEvalArg,Span) :- var(Ground),!,
3093 translate:translate_bexpression(UnEvalArg,S),
3094 add_error(external_functions,'Argument has not been computed deterministically: ',S,Span),
3095 translate:print_bvalue(Value),nl.
3096 check_det_aux(_Ground,Value,WF0,WF1,UnEvalArg,_Span) :- debug:debug_mode(on),!,
3097 translate:translate_bexpression(UnEvalArg,S),
3098 format('Value determined (WF0=~w,WF1=~w) : ~w~n',[WF0,WF1,S]),
3099 translate:print_bvalue(Value),nl.
3100 check_det_aux(_Ground,_Value,_WF0,_WF1,_UnEvalArgs,_Span).
3101
3102 % check if a given expression has already a ground value when
3103 % the predicate is called
3104
3105 % the predicate is true when the value is ground, false otherwise
3106 :- public 'IS_DETERMINED'/2.
3107 'IS_DETERMINED'(Value,PredRes) :- ground(Value),!,PredRes=pred_true.
3108 'IS_DETERMINED'(_Value,pred_false).
3109
3110 % other variant: the predicate is always true, the information if the variable is written
3111 % to a file to check it later.
3112 expects_spaninfo('IS_DETERMINED_INTO_FILE').
3113 :- public 'IS_DETERMINED_INTO_FILE'/5.
3114 'IS_DETERMINED_INTO_FILE'(FileValue,VariableValue,Value,PredRes,SpanInfo) :-
3115 check_value_is_string(FileValue,'IS_DETERMINED_INTO_FILE','file name',SpanInfo,File),
3116 check_value_is_string(VariableValue,'IS_DETERMINED_INTO_FILE','variable name',SpanInfo,Varname),
3117 ( ground(File) ->
3118 open(File,write,S,[encoding(utf8)]),
3119 call_cleanup( check_determined2(Value,S,Varname), close(S))
3120 ;
3121 add_error(external_functions,'### EXTERNAL Unspecified file in check_determined','',SpanInfo)),
3122 PredRes = pred_true.
3123 check_determined2(Value,S,Varname) :-
3124 check_determined3(Value,Varname,Term),
3125 writeq(S,Term),write(S,'.\n').
3126 check_determined3(Value,Name,Term) :- ground(Value),!,Term=determined_value(Name,Value).
3127 check_determined3(_Value,Name,not_determined_value(Name)).
3128
3129 check_value_is_string(string(S),_PredName,_Location,_SpanInfo,String) :-
3130 !, String=S.
3131 check_value_is_string(Value,PredName,Location,SpanInfo,_String) :-
3132 atom_concat('### EXTERNAL ',PredName,Msg1),
3133 atom_concat(Msg1,': Type error, expected string as ',Msg2),
3134 atom_concat(Msg2,Location,Msg),
3135 add_error(external_functions,Msg,Value,SpanInfo),
3136 fail.
3137
3138
3139 :- public 'SEE'/3.
3140 is_not_declarative('SEE').
3141 :- dynamic open_stream/2.
3142 'SEE'(string(File),_S,[]) :- b_absolute_file_name(File,AFile),
3143 open_stream(AFile,_),!,
3144 print('File already open: '), print(File),nl.
3145 'SEE'(string(File),_S,[]) :-
3146 b_absolute_file_name(File,AFile),
3147 open_absolute_file_for_reading(AFile,_Stream).
3148
3149 open_file_for_reading_if_necessary(File,Stream) :-
3150 b_absolute_file_name(File,AFile),
3151 (open_stream(AFile,S) -> Stream=S
3152 ; open_absolute_file_for_reading(AFile,Stream)).
3153 open_absolute_file_for_reading(AFile,Stream) :-
3154 open(AFile,read,Stream,[encoding(utf8)]),
3155 print(opened_file(AFile,Stream)),nl,
3156 assert_side_effect_occurred(file),
3157 assertz(open_stream(AFile,Stream)).
3158
3159 %correct_file_open_mode(read).
3160 %correct_file_open_mode(write).
3161 %correct_file_open_mode(append).
3162
3163 :- public 'GET_CODE'/2.
3164 performs_io('GET_CODE').
3165 'GET_CODE'(string(File),int(Code)) :-
3166 b_absolute_file_name(File,AFile),
3167 open_stream(AFile,S),
3168 assert_side_effect_occurred(file),
3169 get_code(S,Code). %,print(got_code(S,Code)),nl.
3170
3171 :- public 'GET_CODE_STDIN'/1.
3172 performs_io('GET_CODE_STDIN').
3173 'GET_CODE_STDIN'(int(Code)) :-
3174 get_code(user_input,Code). % can be problematic if called in ProB2UI
3175 % TODO: check get_prob_application_type(prob2) ?
3176
3177 :- public 'SEEN'/3.
3178 is_not_declarative('SEEN').
3179 'SEEN'(string(File),_S,[]) :- b_absolute_file_name(File,AFile),
3180 retract(open_stream(AFile,S)),
3181 assert_side_effect_occurred(file),
3182 close(S).
3183
3184 close_all_files :- retract(open_stream(_File,S)),
3185 close(S),fail.
3186 close_all_files.
3187
3188
3189 open_utf8_file_for_reading(AFile,Stream,SpanInfo) :-
3190 safe_call(open(AFile,read,Stream,[encoding(utf8)]),SpanInfo).
3191
3192 :- public 'READ_FILE_AS_STRINGS'/3.
3193 performs_io('READ_FILE_AS_STRINGS').
3194 external_subst_enabling_condition('READ_FILE_AS_STRINGS',_,Truth) :- create_texpr(truth,pred,[],Truth).
3195 expects_spaninfo('READ_FILE_AS_STRINGS').
3196 :- block 'READ_FILE_AS_STRINGS'(-,?,?).
3197 'READ_FILE_AS_STRINGS'(string(File),Res,SpanInfo) :-
3198 read_file_as_strings2(File,Res,SpanInfo).
3199 'READ_FILE_AS_STRINGS'(string(File),_Res,_SpanInfo) :-
3200 format('% Opening file failed: ~w~n',[File]),fail.
3201 :- block read_file_as_strings2(-,?,?).
3202 read_file_as_strings2(File,Res,SpanInfo) :-
3203 b_absolute_file_name(File,AFile,SpanInfo),
3204 open_utf8_file_for_reading(AFile,Stream,SpanInfo),!,
3205 format('% Opened file: ~w~n',[File]),
3206 % no side-effect: as everything read in one go
3207 call_cleanup(read_lines(Stream,Res),
3208 close(Stream)).
3209
3210 read_lines(File,Res) :- read_lines_loop(1,File,Lines),
3211 kernel_objects:equal_object(Res,Lines).
3212 read_lines_loop(Nr,Stream,Lines) :- read_line(Stream,Line),
3213 debug:debug_println(9,read_line(Nr,Line)),
3214 (Line = end_of_file -> Lines = []
3215 ; atom_codes(Atom,Line), Lines = [(int(Nr),string(Atom))|T],
3216 N1 is Nr+1,read_lines_loop(N1,Stream,T)).
3217
3218
3219 :- public 'READ_FILE_AS_STRING'/3.
3220 performs_io('READ_FILE_AS_STRING').
3221 external_subst_enabling_condition('READ_FILE_AS_STRING',_,Truth) :- create_texpr(truth,pred,[],Truth).
3222 expects_spaninfo('READ_FILE_AS_STRING').
3223 :- block 'READ_FILE_AS_STRING'(-,?,?).
3224 'READ_FILE_AS_STRING'(string(File),Res,SpanInfo) :-
3225 read_file_as_string2(File,Res,SpanInfo).
3226 :- block read_file_as_string2(-,?,?).
3227 read_file_as_string2(File,Res,SpanInfo) :-
3228 b_absolute_file_name(File,AFile,SpanInfo),
3229 open_utf8_file_for_reading(AFile,Stream,SpanInfo),!,
3230 format('% Opened file: ~w~n',[File]),
3231 % no side-effect: as everything read in one go
3232 call_cleanup(read_all_codes(Stream,All,[]),
3233 close(Stream)),
3234 atom_codes(ResStr,All), Res = string(ResStr).
3235
3236 % read all codes in the stream:
3237 read_all_codes(Stream) --> {read_line(Stream,Line), Line \= end_of_file, !},
3238 Line, "\n",
3239 read_all_codes(Stream).
3240 read_all_codes(_) --> "".
3241
3242
3243 :- public 'READ_LINE'/3.
3244 expects_spaninfo('READ_LINE').
3245 external_subst_enabling_condition('READ_LINE',_,Truth) :- create_texpr(truth,pred,[],Truth).
3246 performs_io('READ_LINE').
3247 :- block 'READ_LINE'(-,?,?).
3248 'READ_LINE'(string(File),Res,SpanInfo) :-
3249 read_line2(File,Res,SpanInfo).
3250 :- block read_line2(-,?,?).
3251 read_line2(File,Res,_SpanInfo) :-
3252 open_file_for_reading_if_necessary(File,Stream),
3253 read_line(Stream,Line),
3254 debug:debug_println(9,read_line(Line)),
3255 assert_side_effect_occurred(file),
3256 (Line = end_of_file
3257 -> add_error(external_functions,'Attempting to read past EOF: ',File),
3258 Res = ""
3259 ; atom_codes(Atom,Line), Res = string(Atom)).
3260
3261 is_not_declarative('EOF').
3262 :- public 'EOF'/2.
3263 :- block 'EOF'(-,?).
3264 'EOF'(string(File),Res) :- eof2(File,Res).
3265 :- block eof2(-,?).
3266 eof2(File,Res) :-
3267 open_file_for_reading_if_necessary(File,Stream),
3268 ((peek_code(Stream,C), C = -1) -> Res = pred_true ; Res = pred_false). % for Linux compatibility
3269 % (at_end_of_stream(Stream) -> Res = pred_true ; Res=pred_false).
3270
3271 is_not_declarative('EOF_STDIN').
3272 :- public 'EOF_STDIN'/2.
3273 'EOF_STDIN'(_,Res) :- % dummy argument to enable valid external predicate type declarations
3274 ((peek_code(user_input,C), C = -1) -> Res = pred_true ; Res = pred_false).
3275
3276
3277 external_fun_type('CURRENT_FILE_POSITION',[],[string,string,integer]).
3278 is_not_declarative('CURRENT_FILE_POSITION').
3279 :- public 'CURRENT_FILE_POSITION'/3.
3280 'CURRENT_FILE_POSITION'(string(File),string(Field),Res) :-
3281 open_file_for_reading_if_necessary(File,Stream),
3282 stream_position(Stream,Pos),
3283 % POS must be one of byte_count [only for binary streams], line_count, character_count, line_position
3284 stream_position_data(Field,Pos,R), Res=int(R).
3285
3286 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3287
3288 :- public 'ADD_ERROR'/6.
3289 expects_spaninfo('ADD_ERROR').
3290 expects_waitflag('ADD_ERROR').
3291 performs_io('ADD_ERROR').
3292 'ADD_ERROR'(string(Msg),Expr,_State,[],SpanInfo,WF) :-
3293 add_error_wf('ADD_ERROR',Msg,Expr,SpanInfo,WF).
3294
3295 :- public 'ADD_STATE_ERROR'/6.
3296 expects_spaninfo('ADD_STATE_ERROR').
3297 expects_waitflag('ADD_STATE_ERROR').
3298 performs_io('ADD_STATE_ERROR').
3299 'ADD_STATE_ERROR'(string(Msg),Expr,_State,[],SpanInfo,WF) :-
3300 %add_wd_error_span_now(Msg,Expr,SpanInfo,WF).
3301 %add_wd_error_span(Msg,Expr,SpanInfo,WF).
3302 add_state_error_wf('ADD_STATE_ERROR',Msg,Expr,SpanInfo,WF). % does not fail
3303
3304 :- public 'ADD_WARNING'/6.
3305 expects_spaninfo('ADD_WARNING').
3306 expects_waitflag('ADD_WARNING').
3307 performs_io('ADD_WARNING').
3308 'ADD_WARNING'(string(Msg),Expr,_State,[],SpanInfo,WF) :-
3309 add_warning_wf('ADD_WARNING',Msg,Expr,SpanInfo,WF).
3310
3311
3312 :- public 'ADD_ERRORS'/5.
3313 expects_spaninfo('ADD_ERRORS').
3314 expects_waitflag('ADD_ERRORS').
3315 performs_io('ADD_ERRORS').
3316 :- block 'ADD_ERRORS'(-,?,?,?,?).
3317 'ADD_ERRORS'(SetOfStrings,_State,[],SpanInfo,WF) :-
3318 expand_custom_set_to_list_wf(SetOfStrings,ESet,_,add_errors,WF),
3319 add_errors_aux(ESet,SpanInfo,WF).
3320 :- block add_errors_aux(-,?,?).
3321 add_errors_aux([],_SpanInfo,_WF).
3322 add_errors_aux([string(Msg)|T],SpanInfo,WF) :-
3323 add_error('ADD_ERRORS',Msg,'',SpanInfo),
3324 add_errors_aux(T,SpanInfo,WF).
3325
3326 :- public 'ADD_STATE_ERRORS'/5.
3327 expects_spaninfo('ADD_STATE_ERRORS').
3328 expects_waitflag('ADD_STATE_ERRORS').
3329 performs_io('ADD_STATE_ERRORS').
3330 :- block 'ADD_STATE_ERRORS'(-,?,?,?,?).
3331 'ADD_STATE_ERRORS'(SetOfStrings,_State,[],SpanInfo,WF) :-
3332 expand_custom_set_to_list_wf(SetOfStrings,ESet,_,add_state_errors,WF),
3333 add_state_errors_aux(ESet,SpanInfo,WF).
3334 :- block add_state_errors_aux(-,?,?).
3335 add_state_errors_aux([],_SpanInfo,_WF).
3336 add_state_errors_aux([string(Msg)|T],SpanInfo,WF) :-
3337 add_state_error_wf('ADD_STATE_ERRORS',Msg,'',SpanInfo,WF),
3338 add_state_errors_aux(T,SpanInfo,WF).
3339
3340 :- public 'ADD_WARNINGS'/5.
3341 expects_spaninfo('ADD_WARNINGS').
3342 expects_waitflag('ADD_WARNINGS').
3343 performs_io('ADD_WARNINGS').
3344 :- block 'ADD_WARNINGS'(-,?,?,?,?).
3345 'ADD_WARNINGS'(SetOfStrings,_State,[],SpanInfo,WF) :-
3346 expand_custom_set_to_list_wf(SetOfStrings,ESet,_,add_warnings,WF),
3347 add_warnings_aux(ESet,SpanInfo,WF).
3348 :- block add_warnings_aux(-,?,?).
3349 add_warnings_aux([],_SpanInfo,_WF).
3350 add_warnings_aux([string(Msg)|T],SpanInfo,WF) :-
3351 add_warning('ADD_WARNINGS',Msg,'',SpanInfo),
3352 % we do not add with WF and call stack: call stack contains call to ADD_WARNINGS with all error messages again
3353 add_warnings_aux(T,SpanInfo,WF).
3354
3355 :- public 'ASSERT_TRUE'/5.
3356 expects_spaninfo('ASSERT_TRUE').
3357 expects_waitflag('ASSERT_TRUE').
3358 external_fun_has_wd_condition('ASSERT_TRUE').
3359 external_fun_type('ASSERT_TRUE',[],[boolean,string,boolean]). % external predicate in LibraryProB.def
3360
3361 'ASSERT_TRUE'(PredVal,string(Msg),PredRes,SpanInfo,WF) :-
3362 assert_true(PredVal,Msg,PredRes,SpanInfo,WF).
3363
3364 :- block assert_true(-,?,?,?,?).
3365 assert_true(pred_true,_Msg,pred_true,_SpanInfo,_WF).
3366 assert_true(pred_false,Msg,Res,SpanInfo,WF) :-
3367 debug_format(19,'% Waiting for enumeration to finish to raise ASSERT_TRUE:~n ~w~n',[Msg]),
3368 add_error_ef('ASSERT_TRUE',Msg,'',SpanInfo,WF,Res).
3369
3370 % we could also use: add_wd_error_set_result
3371 add_error_ef(Source,Msg,Term,Span,WF,Res) :-
3372 get_enumeration_finished_wait_flag(WF,AWF),
3373 add_error_ef_aux(AWF,Source,Msg,Term,Span,WF,Res).
3374
3375 :- block add_error_ef_aux(-,?,?,?,?,?,?).
3376 add_error_ef_aux(_AWF,Source,Msg,Term,Span,_WF,Res) :-
3377 add_error(Source,Msg,Term,Span),
3378 Res = pred_false.
3379
3380 :- public 'ASSERT_EXPR'/6.
3381 expects_spaninfo('ASSERT_EXPR').
3382 expects_waitflag('ASSERT_EXPR').
3383 external_fun_has_wd_condition('ASSERT_EXPR').
3384 external_fun_type('ASSERT_EXPR',[T],[boolean,string,T,T]).
3385
3386 'ASSERT_EXPR'(PredVal,string(Msg),ExprVal,Res,SpanInfo,WF) :-
3387 % TO DO: call assertion_expression(Cond,ErrMsg,Expr) or a variant there-of
3388 % current problem: Expr is evaluated even if PredVal is false; if evaluation fails we do not get an error message
3389 % ideally we want to delay evaluating Expr until Predval is true
3390 assert_expr(PredVal,Msg,ExprVal,Res,SpanInfo,WF).
3391
3392 :- block assert_expr(-,?,?,?,?,?).
3393 assert_expr(pred_true,_Msg,ExprVal,Res,_SpanInfo,_WF) :-
3394 Res = ExprVal.
3395 assert_expr(pred_false,Msg,_ExprVal,Res,SpanInfo,WF) :-
3396 add_error_ef('ASSERT_EXPR',Msg,'',SpanInfo,WF,Res).
3397
3398 % --------------------------
3399 % Reflection Functions
3400
3401 external_fun_type('STATE_AS_STRING',[],[integer,string]).
3402 external_function_requires_state('STATE_AS_STRING').
3403 :- public 'STATE_AS_STRING'/3.
3404 expects_waitflag('STATE_AS_STRING').
3405 'STATE_AS_STRING'(int(X),StateStr,WF) :-
3406 state_space:get_state_space_stats(NrNodes,_NrTransitions,_ProcessedNodes),
3407 get_wait_flag(NrNodes,'STATE_AS_STRING',WF,LWF),
3408 get_state2(X,StateStr,LWF).
3409 :- block get_state2(-,?,-).
3410 get_state2(X,StateStr,_) :-
3411 convert_id_to_nr(IDX,X),
3412 state_space:visited_expression(IDX,S),
3413 translate:translate_any_state(S,Str),
3414 StateStr = string(Str).
3415
3416 :- public 'CURRENT_STATE_AS_TYPED_STRING'/1.
3417 external_function_requires_state('CURRENT_STATE_AS_TYPED_STRING').
3418 external_fun_type('CURRENT_STATE_AS_TYPED_STRING',[],[string]).
3419 % translate current state values as parseable string
3420 'CURRENT_STATE_AS_TYPED_STRING'(string(Translation)) :-
3421 'VARS_AS_TYPED_STRING'(string(''),string(Translation)).
3422
3423 external_function_requires_state('VARS_AS_TYPED_STRING').
3424 external_fun_type('VARS_AS_TYPED_STRING',[],[string,string]).
3425 :- block 'VARS_AS_TYPED_STRING'(-,?).
3426 'VARS_AS_TYPED_STRING'(string(Prefix),string(Translation)) :- % the name is a bit misleading, as it is also searched for constants
3427 get_current_state_id(ID),
3428 visited_expression(ID,State),
3429 state_corresponds_to_fully_setup_b_machine(State,FullState),
3430 b_get_machine_constants(Constants),
3431 include(identifier_matches_prefix(Prefix),Constants,C1),
3432 b_get_machine_variables(Vars),
3433 include(identifier_matches_prefix(Prefix),Vars,V1),
3434 append(C1,V1,Ids),
3435 translate_ids_to_typed_parseable(Ids,FullState,Translation).
3436
3437 translate_ids_to_typed_predicate(Ids,FullState,Pred) :-
3438 findall(Equality,(member(TID,Ids),
3439 generate_equality(TID,FullState,Equality)),Eqs),
3440 generate_typing_predicates(Ids,TypePreds),
3441 append(TypePreds,Eqs,Ps),
3442 conjunct_predicates(Ps,Pred).
3443 translate_ids_to_typed_parseable(Ids,FullState,Translation) :-
3444 translate_ids_to_typed_predicate(Ids,FullState,Pred),
3445 translate_bexpr_to_parseable(Pred,Translation).
3446
3447 :- use_module(probsrc(tools_strings), [atom_prefix/2]).
3448 identifier_matches_prefix(Prefix,b(identifier(ID),_,_)) :- atom_prefix(Prefix,ID).
3449
3450 generate_equality(TID,FullState,Equality) :- TID = b(identifier(ID),Type,_),
3451 if(member(bind(ID,Val),FullState),
3452 safe_create_texpr(equal(TID,b(value(Val),Type,[])),pred,Equality),
3453 add_error_fail('VARS_AS_TYPED_STRING','Could not find identifier:',TID)).
3454
3455 external_function_requires_state('IDS_AS_TYPED_STRING').
3456 expects_waitflag('IDS_AS_TYPED_STRING').
3457 external_fun_type('IDS_AS_TYPED_STRING',[],[set(string),string]).
3458 :- public 'IDS_AS_TYPED_STRING'/3.
3459 :- block 'IDS_AS_TYPED_STRING'(-,?,?).
3460 'IDS_AS_TYPED_STRING'(SetOfStrings,string(Translation),WF) :-
3461 expand_custom_set_to_list_wf(SetOfStrings,StringIds,_,'IDS_AS_TYPED_STRING',WF),
3462 get_current_state_id(ID),
3463 ids_as_typed_string_for_state(ID,StringIds,Pred),
3464 translate_bexpr_to_parseable(Pred,Translation).
3465
3466 :- block ids_as_typed_string_for_state(-,-,?).
3467 ids_as_typed_string_for_state(StateId,StringIds,Pred) :-
3468 visited_expression(StateId,State),
3469 state_corresponds_to_fully_setup_b_machine(State,FullState),
3470 b_get_machine_constants(Constants),
3471 b_get_machine_variables(Vars),
3472 (StringIds=[] -> C1=Constants ; include(identifier_member_exact(StringIds),Constants,C1)),
3473 (StringIds=[] -> V1=Vars ; include(identifier_member_exact(StringIds),Vars,V1)),
3474 append(C1,V1,Ids),
3475 translate_ids_to_typed_predicate(Ids,FullState,Pred).
3476
3477 identifier_member_exact(StringIds,b(identifier(ID),_,_)) :- member(string(ID),StringIds), !.
3478 identifier_member_exact(StringIds,b(identifier(ID),_,_)) :- member(ID,StringIds).
3479
3480 external_function_requires_state('WRITE_CURRENT_STATE_AS_MACHINE').
3481 expects_waitflag('WRITE_CURRENT_STATE_AS_MACHINE').
3482 performs_io('WRITE_CURRENT_STATE_AS_MACHINE').
3483 external_fun_type('WRITE_CURRENT_STATE_AS_MACHINE',[],[string,set(string)]). % output path, set of IDs
3484 :- public 'WRITE_CURRENT_STATE_AS_MACHINE'/4.
3485 :- block 'WRITE_CURRENT_STATE_AS_MACHINE'(-,-,?,?).
3486 'WRITE_CURRENT_STATE_AS_MACHINE'(string(OutputPath),SetOfStrings,Res,WF) :-
3487 expand_custom_set_to_list_wf(SetOfStrings,StringIds,_,'WRITE_CURRENT_STATE_AS_MACHINE',WF),
3488 get_current_state_id(ID),
3489 write_state_as_machine_string(OutputPath,ID,StringIds),
3490 Res = pred_true.
3491 :- block write_state_as_machine_string(-,-,-).
3492 write_state_as_machine_string(OutputPath,StateId,StringIds) :-
3493 ids_as_typed_string_for_state(StateId,StringIds,Pred),
3494 tools:get_modulename_filename(OutputPath,MchName),
3495 translate:translate_predicate_into_machine(Pred,MchName,Machine),
3496 tools_io:safe_open_file(OutputPath,write,Stream,[encoding(utf8)]),
3497 write(Stream,Machine), close(Stream).
3498
3499
3500 :- use_module(state_space,[visited_expression/2]).
3501 :- use_module(probsrc(tools_strings),[match_atom/3]).
3502 :- use_module(specfile,[property/2, xtl_mode/0]).
3503 :- public 'STATE_PROPERTY'/3.
3504 % a useful function for VisB and XTL or CSP models to query state of model
3505 expects_spaninfo('STATE_PROPERTY').
3506 external_function_requires_state('STATE_PROPERTY').
3507 external_fun_type('STATE_PROPERTY',[],[string,string]).
3508 :- block 'STATE_PROPERTY'(-,?,?).
3509 'STATE_PROPERTY'(string(Prop),Res,Span) :- state_property2(Prop,Res,Span).
3510 :- block state_property2(-,?,?).
3511 state_property2(Prop,Res,Span) :-
3512 get_current_state_id(ID),
3513 visited_expression(ID,State),
3514 atom_codes(Prop,PC),
3515 (property(State,'='(StateProp,Val)), % TODO: this leads to error in B mode due to atom_codes error
3516 match_atom(Prop,PC,StateProp)
3517 -> (atom(Val) -> Res = string(Val)
3518 ; number(Val), number_codes(Val,CC), atom_codes(Atom,CC) -> Res = string(Atom)
3519 ; add_message(external_functions,'Cannot convert STATE_PROPERTY value to STRING ',Val,Span),
3520 Res = string('UNKNOWN')
3521 )
3522 ; xtl_mode -> Res = string('UNKNOWN') % the user can define their own properties in prop/2; see test 2511
3523 ; add_message(external_functions,'Unknown value for STATE_PROPERTY: ',Prop,Span),
3524 Res = string('UNKNOWN')
3525 ).
3526
3527 :- public 'STATE_PROPERTIES'/2.
3528 % query all available state properties with prefix Pref
3529 external_function_requires_state('STATE_PROPERTIES').
3530 external_fun_type('STATE_PROPERTIES',[],[string,set(string)]).
3531 :- block 'STATE_PROPERTIES'(-,?).
3532 'STATE_PROPERTIES'(string(Prefix),Res) :- state_properties_aux(Prefix,Res).
3533 :- block state_properties_aux(-,?).
3534 state_properties_aux(Prefix,Res) :-
3535 get_current_state_id(ID),
3536 visited_expression(ID,State),
3537 findall(Prop,property(State,'='(Prop,_Val)),PropIds),
3538 include(atom_prefix(Prefix),PropIds,PrefIds),
3539 maplist(mkstring,PrefIds,Res).
3540
3541 :- public 'STATE_SUCC'/5.
3542 external_fun_type('STATE_SUCC',[],[integer,integer,boolean]).
3543 expects_waitflag('STATE_SUCC').
3544 expects_spaninfo('STATE_SUCC').
3545 'STATE_SUCC'(X,Y,Res,Span,WF) :- 'STATE_TRANS'(X,_,Y,Res,Span,WF).
3546
3547 % synonym for function to BOOL rather than predicate
3548 'GET_IS_ENABLED'(OperationName,Res,Span,WF) :- 'ENABLED'(OperationName,Res,Span,WF).
3549 :- public 'GET_IS_ENABLED'/4.
3550 expects_waitflag('ENABLED').
3551 expects_waitflag('GET_IS_ENABLED').
3552 expects_spaninfo('ENABLED').
3553 expects_spaninfo('GET_IS_ENABLED').
3554 external_function_requires_state('ENABLED').
3555 external_function_requires_state('GET_IS_ENABLED').
3556 external_fun_type('ENABLED',[],[string,boolean]).
3557 'ENABLED'(OperationName,Res,Span,WF) :-
3558 get_current_state_id(ID),
3559 tcltk_interface:compute_all_transitions_if_necessary(ID,false),
3560 NrOps = 10, get_wait_flag(NrOps,'ENABLED',WF,LWF),
3561 % format('Checking ENABLED of ~w in state ~w~n',[OperationName,ID]),
3562 enabled_op(ID,OperationName,Res,Span,LWF).
3563
3564 :- use_module(probsrc(specfile),[b_or_z_mode/0, get_possible_event/1]).
3565 :- block enabled_op(?,-,?,?,-).
3566 enabled_op(ID,string(OpName),Res,Span,_) :-
3567 (var(OpName) -> get_possible_event(OpName) % is b_top_level_operation in b_or_z_mode
3568 ; b_or_z_mode, \+ get_possible_event(OpName)
3569 -> (b_is_operation_name(OpName)
3570 -> add_warning('ENABLED','Not a top-level operation, use GET_GUARD_STATUS for: ',OpName,Span)
3571 ; add_warning('ENABLED','Unknown operation/event: ',OpName,Span)
3572 )
3573 ; true
3574 ),
3575 (state_space_transition(ID,_,string(OpName),_,unknown) -> Res=pred_true
3576 ; Res=pred_false,
3577 (get_preference(maxNrOfEnablingsPerOperation,0)
3578 -> add_warning('ENABLED','MAX_OPERATIONS is 0, you may want to use GET_GUARD_STATUS instead for: ',OpName,Span); true)
3579 ).
3580
3581
3582 :- use_module(b_operation_guards,[get_quantified_operation_enabling_condition/5]).
3583 :- public 'GET_GUARD_STATUS'/4.
3584 expects_waitflag('GET_GUARD_STATUS').
3585 expects_spaninfo('GET_GUARD_STATUS').
3586 %expects_state('GET_GUARD_STATUS'). % passing state does not always work: to the outside it looks like this call requires no variables and constants
3587 external_function_requires_state('GET_GUARD_STATUS').
3588 external_fun_type('GET_GUARD_STATUS',[],[string,boolean]).
3589 % in contrast to ENABLED, this external function works by computing the guard and evaluating it
3590 % ENABLED just checks the state space; which is in principle more efficient but does not work when
3591 % either MAX_OPERATIONS=0 or subsidiary operations are inspected
3592 'GET_GUARD_STATUS'(Op,PredRes,Span,WF) :-
3593 get_current_state_id(ID),
3594 NrOps = 10, get_wait_flag(NrOps,'GET_GUARD_STATUS',WF,LWF),
3595 get_guard_status(ID,Op,PredRes,Span,WF,LWF).
3596 :- block get_guard_status(?,-,?,?,?,-).
3597 get_guard_status(ID,string(OpName),PredRes,Span,WF,_) :-
3598 Simplify=true,
3599 if(get_quantified_operation_enabling_condition(OpName, BExpr, _BSVars, Precise, Simplify),
3600 ((Precise=precise -> true
3601 ; add_message('GET_GUARD_STATUS','Guard of operation/event not precise: ',OpName,Span)),
3602 test_formula_in_state(ID,BExpr,PredRes,WF)),
3603 (add_error('GET_GUARD_STATUS','Unknown operation/event: ',OpName,Span),
3604 PredRes=pred_false)).
3605
3606
3607 :- public 'GET_IS_ENABLED_TRANSITION'/3.
3608 :- public 'ENABLED_TRANSITION'/3.
3609 % a variation of ENABLED where we can check for arguments; useful for VisB but it relies on argument order
3610 external_fun_type('ENABLED_TRANSITION',[],[string,boolean]).
3611 expects_waitflag('ENABLED_TRANSITION').
3612 expects_waitflag('GET_IS_ENABLED_TRANSITION').
3613 external_function_requires_state('ENABLED_TRANSITION').
3614 external_function_requires_state('GET_IS_ENABLED_TRANSITION').
3615 'ENABLED_TRANSITION'(TransString,Res,WF) :- get_enabled_transition(event,TransString,Res,WF).
3616 % synonym for function to BOOL rather than predicate
3617 'GET_IS_ENABLED_TRANSITION'(TransString,Res,WF) :- get_enabled_transition(event,TransString,Res,WF).
3618 :- public 'GET_IS_ENABLED_TRANSITION_DESCRIPTION'/3.
3619 'GET_IS_ENABLED_TRANSITION_DESCRIPTION'(TransString,Res,WF) :- get_enabled_transition(description,TransString,Res,WF).
3620 external_fun_type('GET_IS_ENABLED_TRANSITION_DESCRIPTION',[],[string,boolean]).
3621 expects_waitflag('GET_IS_ENABLED_TRANSITION_DESCRIPTION').
3622
3623 get_enabled_transition(Kind,TransString,Res,WF) :-
3624 get_current_state_id(ID),
3625 tcltk_interface:compute_all_transitions_if_necessary(ID,false),
3626 NrOps = 10, get_wait_flag(NrOps,'GET_IS_ENABLED_TRANSITION',WF,LWF),
3627 % format('Checking ENABLED_TRANSITION of ~w in state ~w~n',[TransString,ID]),
3628 enabled_trans(Kind,ID,TransString,Res,LWF).
3629
3630 :- block enabled_trans(?,?,-,?,-),enabled_trans(?,?,-,-,?).
3631 enabled_trans(Kind,ID,string(TransitionStr),Res,LWF) :-
3632 enabled_trans2(Kind,ID,TransitionStr,Res,LWF).
3633 :- block enabled_trans2(?,?,-,?,-),enabled_trans2(?,?,-,-,?).
3634 enabled_trans2(Kind,ID,TransitionStr,Res,_) :- var(TransitionStr),!,
3635 (Res==pred_true -> transition_string(Kind,ID,Str,1000,_), TransitionStr=Str
3636 ; enabled_trans2(Kind,ID,TransitionStr,Res2,_), % wait until TransitionStr is known
3637 Res = Res2
3638 ).
3639 enabled_trans2(Kind,ID,TransitionStr,Res,_) :-
3640 atom_length(TransitionStr,Limit),
3641 (transition_string(Kind,ID,TransitionStr,Limit,_) -> Res=pred_true ; Res=pred_false).
3642
3643 :- use_module(state_space,[transition/4]).
3644 :- use_module(translate,[translate_event_with_src_and_target_id/5]).
3645 :- use_module(probsrc(specfile),[get_operation_description_for_transition/4]).
3646 transition_string(Kind,ID,TransitionStr,Limit,ToID) :-
3647 transition(ID,TransitionTerm,_TransID,ToID),
3648 % This will currently also output --> Res for operation results; probably we do not want that
3649 ( Kind=event,
3650 translate_event_with_src_and_target_id(TransitionTerm,ID,ToID,Limit,TransitionStr)
3651 ; Kind=description,
3652 get_operation_description_for_transition(ID,TransitionTerm,ToID,TransitionStr)
3653 ).
3654
3655 :- public 'NON_DET_STATE'/1.
3656 %is_not_declarative('NON_DET_STATE'). % depends on current state, but for any given state it is declarative
3657 external_fun_type('NON_DET_STATE',[],[boolean]).
3658 external_function_requires_state('NON_DET_STATE').
3659 % check if there is a non-deterministic transition: same transition different target state
3660 % similar to tcltk_goto_a_non_deterministic_node
3661 'NON_DET_STATE'(Res) :- get_current_state_id(ID),
3662 non_det_transition(ID,_OperationName,_,_), !,
3663 Res = pred_true.
3664 'NON_DET_STATE'(pred_false).
3665
3666 :- public 'NON_DET_OUTPUT_STATE'/1.
3667 %is_not_declarative('NON_DET_OUTPUT_STATE'). % depends on current state, but for any given state it is declarative
3668 external_function_requires_state('NON_DET_OUTPUT_STATE').
3669 external_fun_type('NON_DET_OUTPUT_STATE',[],[boolean]).
3670 % check if there is a non-deterministic transition: same transition different classic B operation result
3671 % similar to tcltk_goto_a_non_deterministic_output_node
3672 'NON_DET_OUTPUT_STATE'(Res) :- get_current_state_id(ID),
3673 non_det_output_transition2(ID,_OperationName), !,
3674 Res = pred_true.
3675 'NON_DET_OUTPUT_STATE'(pred_false).
3676
3677 % check if we find a state ID where OperationName leads to two different states with same arguments
3678 non_det_transition(ID,OperationName,TID1,TID2) :-
3679 tcltk_interface:compute_all_transitions_if_necessary(ID,false),
3680 transition(ID,Transition,TID1,ID1),
3681 get_operation_name(Transition,OperationName),
3682 get_operation_arguments(Transition,OperationArgs),
3683 transition(ID,Transition2,TID2,ID2),
3684 TID2 > TID1, ID1 \= ID2,
3685 get_operation_name(Transition2,OperationName), % same operation
3686 get_operation_arguments(Transition2,OperationArgs). % same arguments
3687
3688 :- use_module(probltlsrc(ltl_propositions), [non_det_output_transition/4]).
3689 % check if we find a state where an operation with output/result parameters is non-det in the output
3690 non_det_output_transition2(ID,OperationName) :-
3691 tcltk_interface:compute_all_transitions_if_necessary(ID,false), % TODO: detect if we are looping and computing guards/actions
3692 non_det_output_transition(ID,OperationName,_TID1,_TID2).
3693
3694 :- public 'GET_IS_DET'/3.
3695 expects_spaninfo('GET_IS_DET').
3696 external_function_requires_state('GET_IS_DET').
3697 external_fun_type('GET_IS_DET',[],[string,boolean]).
3698 % check if there is a non-deterministic transition for a given operation: same transition different target state
3699 :- block 'GET_IS_DET'(-,?,?).
3700 'GET_IS_DET'(string(OperationName),Res,Span) :-
3701 get_current_state_id(ID),
3702 nondet_op2(ID,OperationName,'GET_IS_DET',Res,Span).
3703
3704
3705 :- public 'GET_IS_DET_OUTPUT'/3.
3706 expects_spaninfo('GET_IS_DET_OUTPUT').
3707 external_function_requires_state('GET_IS_DET_OUTPUT').
3708 external_fun_type('GET_IS_DET_OUTPUT',[],[string,boolean]).
3709 % check if there is a non-deterministic transition for a given operation: same transition different target state
3710 :- block 'GET_IS_DET_OUTPUT'(-,?,?).
3711 'GET_IS_DET_OUTPUT'(string(OperationName),Res,Span) :-
3712 get_current_state_id(ID),
3713 nondet_op2(ID,OperationName,'GET_IS_DET_OUTPUT',Res,Span).
3714
3715 :- block nondet_op2(?,-,?,?,?).
3716 nondet_op2(_ID,OperationName,XFUN,Res,Span) :- \+ b_top_level_operation(OperationName),!,
3717 add_error(XFUN,'Not a valid top-level operation:',OperationName,Span),
3718 Res = pred_false.
3719 % Check if it has outputs and throw warning if not ?
3720 nondet_op2(ID,OperationName,'GET_IS_DET',Res,_Span) :-
3721 non_det_transition(ID,OperationName,_,_),
3722 !,
3723 Res = pred_false.
3724 nondet_op2(ID,OperationName,'GET_IS_DET_OUTPUT',Res,_Span) :-
3725 non_det_output_transition2(ID,OperationName),
3726 !,
3727 Res = pred_false.
3728 nondet_op2(_,_,_,pred_true,_Span).
3729
3730 :- public 'NON_DET_OUTPUT_OPERATIONS'/1.
3731 external_function_requires_state('NON_DET_OUTPUT_OPERATIONS').
3732 external_fun_type('NON_DET_OUTPUT_OPERATIONS',[],[set(string)]).
3733 'NON_DET_OUTPUT_OPERATIONS'(Res) :-
3734 get_current_state_id(ID),
3735 findall(string(OpName),
3736 non_det_output_transition2(ID,OpName),
3737 List),
3738 sort(List,SList),
3739 kernel_objects:equal_object_optimized(SList,Res).
3740
3741
3742 % -------------------
3743
3744 % usage e.g. for scheduler.mch: {x|x:PID & GET_IS_ENABLED_WITH_ARGS("new",x)=TRUE}
3745 expects_waitflag('GET_IS_ENABLED_WITH_ARGS').
3746 external_fun_type('GET_IS_ENABLED_WITH_ARGS',[X],[string,X,boolean]).
3747 expects_spaninfo('GET_IS_ENABLED_WITH_ARGS').
3748 external_function_requires_state('GET_IS_ENABLED_WITH_ARGS').
3749 expects_unevaluated_args('GET_IS_ENABLED_WITH_ARGS').
3750 :- public 'GET_IS_ENABLED_WITH_ARGS'/6.
3751 :- block 'GET_IS_ENABLED_WITH_ARGS'(-,?,?,?,?,?).
3752 % we would expect the operation name to be known statically, as the type of the arguments may differ amongst operations
3753 'GET_IS_ENABLED_WITH_ARGS'(OperationName,OperationArgs,Res,[OpNameExpr,UnEvalArgs|_],SpanInfo,WF) :-
3754 OperationName = string(OpName),
3755 check_operation_name_and_arg_type(OpName,UnEvalArgs,'GET_IS_ENABLED_WITH_ARGS',OpNameExpr),
3756 get_current_state_id(CurID),
3757 tcltk_interface:compute_all_transitions_if_necessary(CurID,false),
3758 'STATE_TRANS_ARGS'(int(CurID),OperationName,OperationArgs,_,Res,SpanInfo,WF).
3759
3760 %:- block check_operation_name(-,?,?).
3761 %check_operation_name(OpName,_,_) :- b_top_level_operation(OpName),!.
3762 %check_operation_name(OpName,XFUN,Span) :-
3763 % add_error(XFUN,'Unknown operation name:',OpName,Span).
3764 :- use_module(bmachine,[b_get_machine_operation_for_animation/4, b_is_operation_name/1]).
3765 :- block check_operation_name_and_arg_type(-,?,?,?).
3766 check_operation_name_and_arg_type(OpName,Args,XFUN,_) :- b_top_level_operation(OpName),!,
3767 get_texpr_type(Args,ArgType),
3768 b_get_machine_operation_for_animation(OpName,_Results,Parameters,_Body),
3769 check_argument_type_against_params(Parameters,OpName,ArgType,XFUN,Args).
3770 check_operation_name_and_arg_type(OpName,_,XFUN,Span) :- b_is_operation_name(OpName),!,
3771 % will never be executed as transition in state_space
3772 add_warning(XFUN,'Not a top-level operation name:',OpName,Span).
3773 check_operation_name_and_arg_type(OpName,_,XFUN,Span) :-
3774 add_error(XFUN,'Unknown operation name:',OpName,Span).
3775
3776 check_argument_type_against_params([],OpName,_,XFUN,Args) :- !,
3777 add_error(XFUN,'Operation has no arguments, use GET_IS_ENABLED instead:',OpName,Args).
3778 check_argument_type_against_params([Para],_OpName,ArgType,XFUN,Args) :- !,
3779 check_type(Para,ArgType,XFUN,Args).
3780 check_argument_type_against_params([Para|TParas],OpName,couple(PType1,PTypeRest),XFUN,Args) :- !,
3781 check_type(Para,PType1,XFUN,Args),
3782 check_argument_type_against_params(TParas,OpName,PTypeRest,XFUN,Args).
3783 check_argument_type_against_params(_,OpName,_ArgType,XFUN,Args) :- !,
3784 add_error(XFUN,'Not enough arguments provided for operation:',OpName,Args).
3785
3786 :- use_module(probsrc(btypechecker), [lookup_type_for_expr/2, unify_types_werrors/4]).
3787 check_type(Arg1,Type2,XFUN,Pos) :-
3788 get_texpr_type(Arg1,Type1),
3789 unify_types_werrors(Type1,Type2,Pos,XFUN).
3790
3791 :- use_module(probltlsrc(ltl),[parse_and_preprocess_formula/3]).
3792 :- use_module(probltlsrc(ltl_verification), [evaluate_ltl_state_property/3]).
3793 external_fun_type('EVAL_LTL_STATE_PROPERTY',[],[string,boolean]).
3794 expects_waitflag('EVAL_LTL_STATE_PROPERTY').
3795 expects_spaninfo('EVAL_LTL_STATE_PROPERTY').
3796 external_function_requires_state('EVAL_LTL_STATE_PROPERTY').
3797 :- public 'EVAL_LTL_STATE_PROPERTY'/4.
3798 :- block 'EVAL_LTL_STATE_PROPERTY'(-,?,?,?).
3799 % we would expect the operation name to be known statically, as the type of the arguments may differ amongst operations
3800 'EVAL_LTL_STATE_PROPERTY'(string(LTLFormula),Result,SpanInfo,WF) :-
3801 get_current_state_id(CurID),
3802 parse_and_preprocess_formula(LTLFormula,ltl,TypeCheckedCondition), % TODO: cache parsing
3803 (evaluate_ltl_state_property(TypeCheckedCondition,CurID,Res)
3804 -> ( Res=false -> Result=pred_false
3805 ; Res=true -> Result=pred_true
3806 ; add_wd_error_span('EVAL_LTL_STATE_PROPERTY result unknown:',string(LTLFormula),SpanInfo,WF)
3807 )
3808 ; add_error('EVAL_LTL_STATE_PROPERTY', 'Could not evaluate LTL formula:', LTLFormula, SpanInfo)
3809 ).
3810
3811 external_fun_type('STATE_TRANS',[],[integer,string,integer,boolean]).
3812 expects_waitflag('STATE_TRANS').
3813 expects_spaninfo('STATE_TRANS').
3814 'STATE_TRANS'(int(X),OperationName,int(Y),Res,SpanInfo,WF) :-
3815 'STATE_TRANS_ARGS'(int(X),OperationName,_,int(Y),Res,SpanInfo,WF).
3816
3817 external_fun_type('STATE_TRANS_ARGS',[X],[integer,string,X,integer,boolean]).
3818 expects_waitflag('STATE_TRANS_ARGS').
3819 expects_spaninfo('STATE_TRANS_ARGS').
3820 'STATE_TRANS_ARGS'(int(X),OperationName,OperationArgs,int(Y),Res,SpanInfo,WF) :-
3821 (nonvar(X)
3822 -> true
3823 ; state_space:get_state_space_stats(NrNodes,_NrTransitions,_ProcessedNodes),
3824 get_wait_flag(NrNodes,'STATE_TRANS',WF,LWF)
3825 ),
3826 get_wait_flag1('STATE_TRANS_ARGS',WF,WF1),
3827 get_succ2(X,OperationName,OperationArgs,Y,Res,LWF,WF1,SpanInfo).
3828 :- block get_succ2(-,?,?,-,?,-,?,?),
3829 get_succ2(?,?,?,?,?,?,-,?). % wait at least until WF1 (or at least wf0); as we do non-deterministic enumeration ! (e.g., otherwise b_interpreter_components gets confused !!)
3830 get_succ2(X,OperationName,OperationArgs,Y,Res,_,_,Pos) :- convert_id_to_nr(IDX,X),
3831 if((state_space_transition(IDX,IDY,OperationName,OperationArgs,Pos),
3832 convert_id_to_nr(IDY,Y)),
3833 Res=pred_true,Res=pred_false).
3834
3835 state_space_transition(IDX,IDY,OperationName,OperationArgs,Pos) :-
3836 state_space:transition(IDX,Transition,IDY),
3837 op_functor(Transition,OperationName),
3838 op_args(Transition,OperationArgs,Pos).
3839
3840 % root is represented as -1
3841 :- block convert_id_to_nr(-,-).
3842 convert_id_to_nr(ID,X) :- ID==root, !, X is -1.
3843 convert_id_to_nr(ID,X) :- X == -1, !, ID=root.
3844 convert_id_to_nr(X,X).
3845
3846 :- use_module(specfile,[get_operation_name/2,get_operation_arguments/2, get_operation_return_values_and_arguments/3]).
3847 op_functor(OpTerm,Res) :- get_operation_name(OpTerm,Name),
3848 Res = string(Name).
3849
3850 :- use_module(tools,[convert_list_into_pairs/2]).
3851 op_args(OpTerm,OperationArgs,Pos) :-
3852 get_operation_arguments(OpTerm,As),
3853 convert_list_into_pairs(As,ArgTerm),
3854 % first check if types are compatible; user could have provided wrong types;
3855 % TODO: sometimes we check_operation_name_and_arg_type and could remove this check in then
3856 kernel_objects:check_values_have_same_type(OperationArgs,ArgTerm,Pos),
3857 kernel_objects:equal_object(OperationArgs,ArgTerm).
3858
3859
3860 :- public 'STATE_SAT'/4.
3861 expects_waitflag('STATE_SAT').
3862 external_fun_type('STATE_SAT',[],[integer,string,boolean]).
3863 % check whether formula as string holds in a state
3864 :- block 'STATE_SAT'(?,-,?,?).
3865 'STATE_SAT'(int(X),string(Formula),Res,WF) :- %print(parsing(Formula)),nl, trace,
3866 parse_pred(Formula,TFormula),
3867 state_space:get_state_space_stats(NrNodes,_NrTransitions,_ProcessedNodes),
3868 get_wait_flag(NrNodes,'STATE_SAT',WF,LWF),
3869 state_sat2(X,TFormula,Res,LWF,WF).
3870 :- block state_sat2(?,-,?,?,?),state_sat2(-,?,?,-,?).
3871 state_sat2(X,TFormula,PredRes,_,WF) :-
3872 (number(X) -> test_formula_in_state(X,TFormula,PredRes,WF)
3873 ; test_formula_in_state(ID,TFormula,PredRes,WF), ID \= root, X=ID % avoid CLPFD errors on X
3874 ).
3875
3876 :- use_module(b_global_sets,[add_prob_deferred_set_elements_to_store/3]).
3877 :- use_module(specfile,[state_corresponds_to_fully_setup_b_machine/2]).
3878 %:- use_module(b_interpreter,[b_try_check_boolean_expression_wf/5]).
3879 test_formula_in_state(ID,Pred,PredRes,WF) :-
3880 state_space:visited_expression(ID,State),
3881 state_corresponds_to_fully_setup_b_machine(State,FullState),
3882 add_prob_deferred_set_elements_to_store(FullState,FullState1,visible),
3883 debug_println(9,check(Pred,FullState1,PredRes)),
3884 b_interpreter:b_try_check_boolean_expression_wf(Pred,[],FullState1,WF,PredRes).
3885
3886
3887 :- public 'EVAL'/6.
3888 expects_waitflag('EVAL'). % external function with unknown return type
3889 expects_type('EVAL').
3890 expects_spaninfo('EVAL').
3891 :- block 'EVAL'(?,-,?,?,?,?).
3892 'EVAL'(int(X),string(Expr),Value,Type,Span,WF) :-
3893 state_eval1(X,Expr,Value,pred_true,Type,Span,WF).
3894
3895 % evaluate expression and check whether value corresponds to provided value
3896 % (needed for type inference of the external predicate)
3897 %:- block 'STATE_EVAL'(?,-,?,?,?,?,?).
3898 %'STATE_EVAL'(int(X),string(Expr),Value,PredRes,Span,WF) :-
3899 % state_eval1(X,Expr,Value,PredRes,any,Span,WF).
3900
3901 :- use_module(btypechecker, [unify_types_strict/2]).
3902 :- block state_eval1(?,-,?,?,?,?,?).
3903 state_eval1(X,Expr,Value,PredRes,ExpectedType,Span,WF) :-
3904 % string must be provided ; we assume it will be ground
3905 parse_expr(Expr,TExpr),
3906 get_texpr_type(TExpr,Type),
3907 (unify_types_strict(ExpectedType,Type) -> true
3908 ; pretty_type(Type,TS), pretty_type(ExpectedType,ETS),
3909 ajoin(['Type ',TS, ' does not match expected type ', ETS, ' for:'],Msg),
3910 add_error('EVAL',Msg,Expr,Span),fail
3911 ),
3912 state_space:get_state_space_stats(NrNodes,_NrTransitions,_ProcessedNodes),
3913 get_wait_flag(NrNodes,'STATE_SAT',WF,LWF),
3914 state_eval2(X,TExpr,Value,LWF,PredRes).
3915 :- block state_eval2(?,-,?,?,?),state_eval2(-,?,?,-,?).
3916 state_eval2(X,TExpr,Value,_,PredRes) :-
3917 (number(X)
3918 -> eval_formula_in_state(TExpr,PredRes,X,Value)
3919 ; eval_formula_in_state(TExpr,PredRes,ID,Value), ID \= root, X=ID % avoid CLPFD errors on X
3920 ).
3921 :- use_module(kernel_equality,[equality_objects/3]).
3922 eval_formula_in_state(TExpr,PredRes,ID,Value) :-
3923 state_space:visited_expression(ID,State),
3924 state_corresponds_to_fully_setup_b_machine(State,FullState),
3925 add_prob_deferred_set_elements_to_store(FullState,FullState1,visible),
3926 debug_println(9,eval(TExpr,FullState1,Value)),
3927 equality_objects(Value,TExprValue,PredRes), % TO DO: Stronger Checks that types compatible
3928 b_interpreter:b_compute_expression_nowf(TExpr,[],FullState1,TExprValue,'STATE_EVAL',ID).
3929
3930 :- use_module(library(terms),[term_hash/2]).
3931 :- use_module(bmachine,[b_parse_machine_predicate/3]).
3932 :- dynamic parse_pred_cache/3.
3933 parse_pred(PredStr,TPred) :- term_hash(PredStr,Hash), parse_pred(PredStr,Hash,TPred).
3934 parse_pred(PredStr,Hash,TPred) :- parse_pred_cache(Hash,PredStr,TC),!, TPred=TC.
3935 parse_pred(PredStr,Hash,TPred) :-
3936 b_parse_machine_predicate(PredStr,[prob_ids(visible),variables],TC),
3937 assertz(parse_pred_cache(Hash,PredStr,TC)),
3938 TPred=TC.
3939
3940 :- dynamic parse_expr_cache/3.
3941 parse_expr(ExprStr,TExpr) :- term_hash(ExprStr,Hash), parse_expr(ExprStr,Hash,TExpr).
3942 parse_expr(ExprStr,Hash,TExpr) :- parse_expr_cache(Hash,ExprStr,TC),!, TExpr=TC.
3943 parse_expr(ExprStr,Hash,TExpr) :-
3944 atom_codes(ExprStr,Codes), %print(parsing(Expr,Codes)),nl,
3945 bmachine:b_parse_machine_expression_from_codes_with_prob_ids(Codes,TC),
3946 assertz(parse_expr_cache(Hash,ExprStr,TC)),
3947 TExpr=TC.
3948
3949 :- use_module(kernel_strings,[generate_code_sequence/3]).
3950 external_fun_type('HISTORY',[],[seq(integer)]).
3951 expects_spaninfo('HISTORY').
3952 :- public 'HISTORY'/2.
3953 'HISTORY'(Value,Span) :-
3954 get_current_history(H,Span), % does not include current state
3955 generate_code_sequence(H,1,Hist),
3956 kernel_objects:equal_object(Value,Hist).
3957
3958
3959 :- use_module(probsrc(state_space), [visited_state_corresponds_to_initialised_b_machine/1,history/1]).
3960
3961
3962 external_fun_type('EVAL_OVER_HISTORY',[X],[X,integer,seq(X)]).
3963 expects_unevaluated_args('EVAL_OVER_HISTORY').
3964 expects_spaninfo('EVAL_OVER_HISTORY').
3965 is_not_declarative('EVAL_OVER_HISTORY'). % depends on history, not explicitly part of arguments
3966
3967 :- public 'EVAL_OVER_HISTORY'/5.
3968 % related to tcltk_evaluate_expression_over_history
3969 :- block 'EVAL_OVER_HISTORY'(-,?,?,?,?), 'EVAL_OVER_HISTORY'(?,-,?,?,?).
3970 'EVAL_OVER_HISTORY'(CurValue,int(Limit),Res,Infos,Span) :-
3971 eval_over_history(CurValue,Limit,Res,Infos,Span).
3972
3973 :- use_module(probsrc(tools_lists),[include_maplist/3]).
3974 :- block eval_over_history(?,-,?,?,?).
3975 eval_over_history(CurValue,Limit,Res,[AST|_],Span) :-
3976 get_current_history(H,Span), % does not include current state
3977 (H=[ID1|SeqOfStateIds], \+visited_state_corresponds_to_initialised_b_machine(ID1) -> true ; SeqOfStateIds=H),
3978 (Limit<0 -> Seq2=SeqOfStateIds ; limit_history(SeqOfStateIds,Limit,Seq2,_Len)),
3979 include_maplist(eval_formula_in_state(AST,pred_true),Seq2,Values),
3980 append(Values,[CurValue],AllValues),
3981 convert_list_to_seq(AllValues,Res).
3982
3983 limit_history([],_,[],0).
3984 limit_history([H|T],Lim,Res,Len1) :- limit_history(T,Lim,TRes,Len), Len1 is Len+1,
3985 (Len >= Lim -> Res = TRes ; Res = [H|TRes]).
3986
3987
3988 :- use_module(probsrc(bool_pred),[negate/2]).
3989 external_fun_type('CHANGED',[X],[X,boolean]).
3990 expects_unevaluated_args('CHANGED').
3991 expects_spaninfo('CHANGED').
3992 is_not_declarative('CHANGED'). % depends on history, not explicitly part of arguments
3993
3994 :- public 'CHANGED'/4.
3995 % check if an expression has changed wrt the preceding state in the history
3996 :- block 'CHANGED'(-,?,?,?).
3997 'CHANGED'(CurValue,Res,[AST|_],Span) :-
3998 (get_current_history(H,Span),
3999 last(H,PrevID), % get_current_predecessor_state_id does not take current_state_id_for_external_fun into account
4000 visited_state_corresponds_to_initialised_b_machine(PrevID)
4001 -> eval_formula_in_state(AST,pred_true,PrevID,PrevValue),
4002 % TODO: the AST could refer to local variables, e.g., if CHANGED is called in a set comprehension
4003 % currently this will lead to identifier not found error messages
4004 equality_objects(CurValue,PrevValue,EqRes),
4005 negate(EqRes,Res)
4006 ; Res=pred_false
4007 ).
4008 external_fun_type('INCREASING',[X],[X,boolean]).
4009 expects_unevaluated_args('INCREASING').
4010 expects_spaninfo('INCREASING').
4011 is_not_declarative('INCREASING'). % depends on history, not explicitly part of arguments
4012
4013 :- public 'INCREASING'/4.
4014 % check if an expression has increased wrt the preceding state in the history
4015 :- block 'INCREASING'(-,?,?,?).
4016 'INCREASING'(CurValue,Res,[AST|_],Span) :-
4017 (get_current_history(H,Span),
4018 last(H,PrevID), % get_current_predecessor_state_id does not take current_state_id_for_external_fun into account
4019 visited_state_corresponds_to_initialised_b_machine(PrevID)
4020 -> eval_formula_in_state(AST,pred_true,PrevID,PrevValue),
4021 'LESS'(PrevValue,CurValue,Res) % LESS can handle numbers, strings, enumerated sets, ...
4022 ; Res=pred_false
4023 ).
4024
4025
4026 :- use_module(state_space,[is_initial_state_id/1]).
4027
4028 :- public 'INITIAL_STATE'/3.
4029 expects_waitflag('INITIAL_STATE'). % external function with unknown return type
4030 'INITIAL_STATE'(int(InitialState),PredRes,WF) :-
4031 get_wait_flag(2,'INITIAL_STATE',WF,LWF),
4032 is_init2(InitialState,PredRes,LWF).
4033 :- block is_init2(-,-,?), is_init2(-,?,-).
4034 is_init2(InitialState,PredRes,_) :-
4035 PredRes == pred_true,!,
4036 is_initial_state_id(InitialState).
4037 is_init2(InitialState,PredRes,_) :- number(InitialState),!,
4038 (is_initial_state_id(InitialState) -> PredRes=pred_true ; PredRes=pred_false).
4039 is_init2(InitialState,PredRes,_LWF) :-
4040 PredRes == pred_false,!,
4041 when(nonvar(InitialState), \+is_initial_state_id(InitialState)).
4042 is_init2(InitialState,PredRes,LWF) :-
4043 add_internal_error('Uncovered case: ', is_init2(InitialState,PredRes,LWF)),fail.
4044
4045
4046 % provide information about a particular B machine in the project
4047 :- public 'MACHINE_INFO'/4.
4048 expects_waitflag('MACHINE_INFO').
4049 external_fun_type('MACHINE_INFO',[],[string,string,string]).
4050 :- block 'MACHINE_INFO'(?,-,?,?).
4051 'MACHINE_INFO'(M,string(I),Value,WF) :-
4052 get_wait_flag(2,'MACHINE_INFO',WF,LWF), % TO DO: use number of machines
4053 machine_info2(I,M,Value,LWF).
4054
4055 :- use_module(b_machine_hierarchy,[machine_type/2]).
4056 :- block machine_info2(-,?,?,?), machine_info2(?,-,?,-).
4057 machine_info2(INFO,M,Value,_LWF) :-
4058 (ground(M) -> M = string(MachineName) ; true),
4059 machine_info3(INFO,MachineName,Type),
4060 (M,Value) = (string(MachineName),string(Type)).
4061
4062 :- use_module(b_machine_hierarchy,[machine_type/2]).
4063 % :- use_module(extension('probhash/probhash'),[raw_sha_hash/2]). % already imported above
4064 :- use_module(bmachine,[get_full_b_machine/2]).
4065 machine_info3('TYPE',MachineName,Type) :- !, machine_type(MachineName,Type).
4066 % SHA_HASH
4067 machine_info3(INFO,_,_) :- add_error('MACHINE_INFO','Unknown info field (TYPE recognised): ',INFO),fail.
4068
4069
4070 :- use_module(tools_strings,[get_hex_codes/2]).
4071 external_fun_type('INT_TO_HEX_STRING',[],[integer,string]).
4072 :- public 'INT_TO_HEX_STRING'/2.
4073 :- block 'INT_TO_HEX_STRING'(-,?).
4074 'INT_TO_HEX_STRING'(int(Int),Res) :- int_to_hex(Int,Res).
4075
4076 :- block int_to_hex(-,?).
4077 int_to_hex(Int,Res) :-
4078 (Int >= 0 -> Nat=Int ; Nat is -(Int)),
4079 get_hex_codes(Nat,Chars),
4080 (Int >= 0 -> atom_codes(Atom,Chars) ; atom_codes(Atom,[45|Chars])), % "-" = [45]
4081 Res = string(Atom).
4082
4083
4084 :- use_module(tools_strings,[get_hex_bytes/2]).
4085 sha_hash_as_hex_codes(Term,SHAHexCodes) :-
4086 raw_sha_hash(Term,RawListOfBytes),
4087 get_hex_bytes(RawListOfBytes,SHAHexCodes).
4088
4089
4090
4091 %-------------------
4092
4093 % returns list of strings for info string such as files, variables,...
4094 external_fun_type('PROJECT_STATISTICS',[],[string,integer]).
4095 expects_waitflag('PROJECT_STATISTICS').
4096 expects_spaninfo('PROJECT_STATISTICS').
4097 :- public 'PROJECT_STATISTICS'/4.
4098 'PROJECT_STATISTICS'(Str,Res,Span,WF) :-
4099 kernel_waitflags:get_wait_flag(10,'PROJECT_STATISTICS',WF,WF10), % will enumerate possible input strings
4100 project_stats1(Str,Res,WF10,Span).
4101
4102 :- use_module(bmachine,[b_machine_statistics/2]).
4103 :- block project_stats1(-,?,-,?).
4104 project_stats1(string(INFO),Res,_,Span) :-
4105 if(b_machine_statistics(INFO,Nr), Res=int(Nr),
4106 add_error('PROJECT_STATISTICS','Unknown info field: ',INFO,Span)).
4107
4108
4109 % returns list of strings for info string such as files, variables,...
4110 external_fun_type('PROJECT_INFO',[],[string,set(string)]).
4111 expects_waitflag('PROJECT_INFO').
4112 expects_spaninfo('PROJECT_INFO').
4113 :- public 'PROJECT_INFO'/4.
4114 'PROJECT_INFO'(Str,Res,Span,WF) :-
4115 kernel_waitflags:get_wait_flag(10,'PROJECT_INFO',WF,WF10), % will enumerate possible input strings
4116 project_info1(Str,Res,WF10,Span).
4117
4118 :- block project_info1(-,?,-,?).
4119 project_info1(string(INFO),Res,_,_Span) :- INFO==help,!,
4120 L = [files, absolute-files, main-file, main-machine, sha-hash,
4121 variables, constants, sets, operations, assertion_labels, invariant_labels],
4122 maplist(make_string,L,SL),
4123 kernel_objects:equal_object(SL,Res).
4124 project_info1(string(INFO),Res,_,Span) :-
4125 if(list_info(INFO,L),
4126 (maplist(make_string,L,SL),
4127 kernel_objects:equal_object(SL,Res)),
4128 (add_error(external_functions,'Illegal argument for PROJECT_INFO or :list (use help to obtain valid arguments) : ',INFO,Span),
4129 fail)).
4130
4131 :- use_module(bmachine).
4132 :- use_module(bsyntaxtree, [get_texpr_ids/2, get_texpr_label/2]).
4133 :- use_module(tools,[get_tail_filename/2]).
4134 list_info(files,TL) :- (b_get_all_used_filenames(L) -> true ; L=[]), maplist(get_tail_filename,L,TL).
4135 list_info('absolute-files',L) :- (b_get_all_used_filenames(L) -> true ; L=[]).
4136 list_info('main-file',L) :- (b_get_main_filename(F) -> get_tail_filename(F,TF),L=[TF] ; L=[]).
4137 list_info('main-machine',L) :- findall(Name,get_full_b_machine(Name,_),L). % gets only the main machine
4138 list_info('sha-hash',[AtomHash]) :-
4139 get_full_b_machine_sha_hash(Bytes),
4140 get_hex_bytes(Bytes,Hash), atom_codes(AtomHash,Hash).
4141 list_info(variables,L) :- b_get_machine_variables(LT), get_texpr_ids(LT,L).
4142 list_info(constants,L) :- b_get_machine_constants(LT), get_texpr_ids(LT,L).
4143 list_info(sets,L) :- findall(S,b_get_machine_set(S),L).
4144 list_info(operations,L) :- findall(S,b_top_level_operation(S),L).
4145 list_info(assertion_labels,L) :-
4146 findall(ID,(b_get_assertions(all,_,Ass), member(Assertion,Ass),get_texpr_label(Assertion,ID)),L).
4147 list_info(invariant_labels,L) :-
4148 findall(ID,(b_get_invariant_from_machine(C), conjunction_to_list(C,CL),
4149 member(Inv,CL),get_texpr_label(Inv,ID)),L).
4150
4151
4152 make_string(X,Res) :- atom(X),!,Res=string(X).
4153 make_string(X,Res) :- format_to_codes('~w',X,C), atom_codes(Atom,C), Res=string(Atom).
4154
4155 % obtain the source code of an identifier
4156 external_fun_type('SOURCE',[],[string,string]).
4157 :- public 'SOURCE'/2.
4158 'SOURCE'(string(ID),SourceCode) :- source2(ID,SourceCode).
4159 :- block source2(-,?).
4160 source2(ID,SourceCode) :-
4161 source_code_for_identifier(ID,_,_,_OriginStr,_,Source),
4162 translate:translate_bexpression(Source,SC),
4163 SourceCode = string(SC).
4164
4165
4166 % obtain various information about ProB (STRING result)
4167 external_fun_type('PROB_INFO_STR',[],[string,string]).
4168 expects_waitflag('PROB_INFO_STR').
4169 :- assert_must_succeed(external_functions:'PROB_INFO_STR'(string('prob-version'),string(_),_)).
4170 :- public 'PROB_INFO_STR'/3.
4171 % :- block 'PROB_INFO_STR'(-,?). % no block: this way we can via backtracking generate solutions
4172 'PROB_INFO_STR'(Str,Res,WF) :-
4173 kernel_waitflags:get_wait_flag(10,'PROB_INFO_STR',WF,WF10), % will enumerate possible input strings
4174 prob_info1(Str,Res,WF10,WF).
4175
4176 :- use_module(tools,[ajoin_with_sep/3]).
4177 :- block prob_info1(-,?,-,?).
4178 prob_info1(string(INFO),Res,_,WF) :-
4179 if(prob_info2(INFO,Str),true,
4180 (findall(I,prob_info2(I,_),Is),
4181 ajoin_with_sep(['Unknown info field, known fields:'|Is],' ',Msg),
4182 add_error_wf('PROB_INFO_STR',Msg,I,unknown,WF),
4183 Str = 'ERROR'
4184 )),
4185 make_string(Str,Res).
4186
4187 :- use_module(probsrc(tools_strings),[ajoin/2]).
4188 :- use_module(parsercall,[get_parser_version/1, get_java_command_path/1, get_java_fullversion/3]).
4189 :- use_module(version, [version_str/1, revision/1, lastchangeddate/1]).
4190 prob_info2('prob-version',V) :- version_str(V).
4191 prob_info2('parser-version',V) :- get_parser_version(V).
4192 prob_info2('prolog-version',V) :- current_prolog_flag(version,V).
4193 prob_info2('prob-revision',V) :- revision(V).
4194 prob_info2('prob-last-changed-date',V) :- lastchangeddate(V).
4195 prob_info2('java-version',V) :- get_java_fullversion(Maj,Min,Sfx), ajoin([Maj,'.',Min,'.',Sfx],V).
4196 prob_info2('java-command-path',V) :- get_java_command_path(V).
4197 prob_info2('current-time',V) :- get_info2(time,string(V)). % Maybe we can get rid of GET_INFO ?
4198
4199
4200 % obtain various information about ProB (INTEGER result)
4201 external_fun_type('PROB_STATISTICS',[],[string,integer]).
4202 expects_waitflag('PROB_STATISTICS').
4203 expects_spaninfo('PROB_STATISTICS').
4204 external_function_requires_state('PROB_STATISTICS'). % e.g., for current-state-id
4205 :- public 'PROB_STATISTICS'/4.
4206 'PROB_STATISTICS'(Str,Res,Span,WF) :-
4207 kernel_waitflags:get_wait_flag(10,'PROB_STATISTICS',WF,WF10), % will enumerate possible input strings
4208 prob_info_int1(Str,Res,Span,WF10,WF).
4209
4210 % old name of function:
4211 :- public 'PROB_INFO_INT'/4.
4212 'PROB_INFO_INT'(Str,Res,Span,WF) :- 'PROB_STATISTICS'(Str,Res,Span,WF).
4213
4214 :- block prob_info_int1(-,?,?,-,?).
4215 prob_info_int1(string(INFO),Res,Span,_,WF) :-
4216 if(prob_info_int1(INFO,I), Res=int(I),
4217 (add_error_wf('PROB_STATISTICS','Unknown info field: ',INFO,Span,WF),
4218 fail)).
4219
4220 :- use_module(state_space_exploration_modes,[get_current_breadth_first_level/1]).
4221 :- use_module(state_space,[get_state_space_stats/3]).
4222 prob_info_int1('current-state-id',StateIDNr) :- get_current_state_id(ID),convert_id_to_nr(ID,StateIDNr).
4223 prob_info_int1('states',NrNodes) :- get_state_space_stats(NrNodes,_,_).
4224 prob_info_int1('transitions',NrTransitions) :- get_state_space_stats(_,NrTransitions,_).
4225 prob_info_int1('processed-states',ProcessedNodes) :- get_state_space_stats(_,_,ProcessedNodes).
4226 prob_info_int1('bf-level',Level) :- (get_current_breadth_first_level(R) -> Level = R ; Level = -1).
4227 prob_info_int1('now-timestamp',N) :- now(N). % provide UNIX timesstamp
4228 prob_info_int1('prolog-runtime',V) :- statistics(runtime,[V,_]).
4229 prob_info_int1('prolog-walltime',V) :- statistics(walltime,[V,_]).
4230 prob_info_int1('prolog-memory-bytes-used',V) :- statistics(memory_used,V).
4231 prob_info_int1('prolog-memory-bytes-free',V) :- statistics(memory_free,V).
4232 prob_info_int1('prolog-global-stack-bytes-used',V) :- statistics(global_stack_used,V).
4233 prob_info_int1('prolog-local-stack-bytes-used',V) :- statistics(local_stack_used,V).
4234 %prob_info_int1('prolog-global-stack-bytes-free',V) :- statistics(global_stack_free,V).
4235 %prob_info_int1('prolog-local-stack-bytes-free',V) :- statistics(local_stack_free,V).
4236 prob_info_int1('prolog-trail-bytes-used',V) :- statistics(trail_used,V).
4237 prob_info_int1('prolog-choice-bytes-used',V) :- statistics(choice_used,V).
4238 prob_info_int1('prolog-atoms-bytes-used',V) :- statistics(atoms_used,V).
4239 prob_info_int1('prolog-atoms-nb-used',V) :- statistics(atoms_nbused,V).
4240 prob_info_int1('prolog-gc-count',V) :- statistics(gc_count,V).
4241 prob_info_int1('prolog-gc-time',V) :- statistics(gc_time,V).
4242
4243 % --------------------
4244
4245 % coverage/projection functions:
4246
4247 external_fun_type('STATE_VALUES',[T],[string,set(couple(couple(integer,integer),T))]).
4248 expects_unevaluated_args('STATE_VALUES').
4249 :- public 'STATE_VALUES'/3.
4250 :- block 'STATE_VALUES'(-,?,?).
4251 'STATE_VALUES'(_Value,Res,[AST]) :-
4252 state_space_reduction:compute_set_of_covered_values_for_typed_expression(AST,Set),
4253 kernel_objects:equal_object_optimized(Set,Res).
4254
4255 % TODO: other projection/reduction operators: projection as graph, ...
4256 % could be useful to have a minimum/maximum operator on sets which uses Prolog order in avl
4257
4258 % -----------------
4259
4260 % obtain various information about bvisual2 Formulas
4261 external_fun_type('FORMULA_INFOS',[],[string,seq(string)]).
4262 expects_waitflag('FORMULA_INFOS').
4263 :- public 'FORMULA_INFOS'/3.
4264 'FORMULA_INFOS'(Str,Res,WF) :-
4265 kernel_waitflags:get_wait_flag(10,'FORMULA_INFOS',WF,WF10), % will enumerate possible input strings
4266 formula_info(Str,_,Res,_,WF10).
4267 external_fun_type('FORMULA_VALUES',[],[string,seq(string)]).
4268 expects_waitflag('FORMULA_VALUES').
4269 :- public 'FORMULA_VALUES'/3.
4270 'FORMULA_VALUES'(Str,Res,WF) :-
4271 kernel_waitflags:get_wait_flag(10,'FORMULA_VALUES',WF,WF10), % will enumerate possible input strings
4272 formula_info(Str,_,_,Res,WF10).
4273
4274 :- use_module(extrasrc(bvisual2),[bv_get_top_level_formula/4, bv_value_to_atom/2]).
4275
4276 % valid TopLevelCategories are constants, definitions, guards_top_level, inv, sets, variables
4277 :- block formula_info(-,?,?,?,-).
4278 formula_info(string(TopLevelCategory),CatTextRes,LabelRes,ValuesRes,_) :-
4279 bv_get_top_level_formula(TopLevelCategory,CatText,Labels,Values),
4280 CatTextRes = string(CatText),
4281 maplist(make_string,Labels,LS),
4282 convert_list_to_seq(LS,LabelRes),
4283 maplist(make_value,Values,LV),
4284 convert_list_to_seq(LV,ValuesRes).
4285
4286 make_value(V,string(A)) :- bv_value_to_atom(V,A).
4287 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4288
4289
4290 % --------------------------
4291
4292 :- use_module(covsrc(hit_profiler),[add_hit/2, add_hit_if_not_covered/2,
4293 get_profile_statistics/2, profile_functor/1]). %profiler:profile_statistics.
4294
4295 :- public 'GET_PROFILE_STATISTICS'/3.
4296 is_not_declarative('GET_PROFILE_STATISTICS').
4297 :- block 'GET_PROFILE_STATISTICS'(-,?,?).
4298 'GET_PROFILE_STATISTICS'(string(PP),_DummyType,Res) :- % DummyType is just there for typing purposes
4299 if(profile_functor(PP),
4300 (get_profile_statistics(PP,Hits),
4301 maplist(translate_hit_to_b,Hits,List)),
4302 List = []),
4303 equal_object_optimized(List,Res, 'GET_PROFILE_STATISTICS').
4304 %equal_object(List,Res,'GET_PROFILE_STATISTICS'), print(res(Res)),nl.
4305
4306 translate_hit_to_b(hit(Arg,Nr),(Arg,int(Nr))).
4307
4308 :- public 'GET_PROFILE_POINTS'/1.
4309 'GET_PROFILE_POINTS'(Res) :- findall(string(S),profile_functor(S),List),
4310 equal_object_optimized(List,Res,'PROFILE_POINT').
4311
4312 expects_spaninfo('PROFILE').
4313 :- public 'PROFILE'/5.
4314 :- block 'PROFILE'(-,?,?,?,?), 'PROFILE'(?,-,?,?,?). %, 'PROFILE'(?,-,?,?,?).
4315 'PROFILE'(string(PP),Count,Value,ValueRes,SpanInfo) :-
4316 add_profile_exf_hit(Value,PP,SpanInfo,Count),
4317 equal_object(Value,ValueRes,'PROFILE').
4318
4319 :- block add_profile_exf_hit(-,?,?,?), add_profile_exf_hit(?,-,?,?).
4320 add_profile_exf_hit(pred_true,PP,SpanInfo,Count) :- !, add_value_hit(Count,pred_true,PP,SpanInfo).
4321 add_profile_exf_hit(pred_false,PP,SpanInfo,Count) :- !, add_value_hit(Count,pred_false,PP,SpanInfo).
4322 add_profile_exf_hit(int(X),PP,SpanInfo,Count) :- !, add_int_hit(X,PP,SpanInfo,Count).
4323 add_profile_exf_hit(string(X),PP,SpanInfo,Count) :- !, add_string_hit(X,PP,SpanInfo,Count).
4324 add_profile_exf_hit(Value,PP,SpanInfo,Count) :- when(ground(Value), add_complex_hit(Value,PP,SpanInfo,Count)).
4325
4326 add_complex_hit(Value,PP,SpanInfo,Count) :- print(PP), print(' : '), translate:print_bvalue(Value),nl,
4327 add_value_hit(Count,Value,PP,SpanInfo).
4328
4329 :- block add_int_hit(-,?,?,?).
4330 add_int_hit(X,PP,SpanInfo,Count) :- add_value_hit(Count,int(X),PP,SpanInfo).
4331 :- block add_string_hit(-,?,?,?).
4332 add_string_hit(X,PP,SpanInfo,Count) :- add_value_hit(Count,string(X),PP,SpanInfo).
4333
4334 add_value_hit(pred_true,Val,PP,_) :- add_hit(PP,Val).
4335 add_value_hit(pred_false,Val,PP,_) :- add_hit_if_not_covered(PP,Val).
4336
4337 % -------------------
4338
4339 :- use_module(memoization,[get_complete_memoization_expansion/6]).
4340
4341 expects_spaninfo('MEMOIZE_STORED_FUNCTION').
4342 expects_waitflag('MEMOIZE_STORED_FUNCTION').
4343 :- public 'MEMOIZE_STORED_FUNCTION'/4.
4344 :- block 'MEMOIZE_STORED_FUNCTION'(-,?,?,?).
4345 'MEMOIZE_STORED_FUNCTION'(int(MemoID),Res,Span,WF) :- memoize_get_aux(MemoID,Res,Span,WF).
4346
4347 :- block memoize_get_aux(-,?,?,?).
4348 memoize_get_aux(MemoID,Res,Span,WF) :-
4349 if(get_complete_memoization_expansion(MemoID,RV,_Done,Span,'MEMOIZE_STORED_FUNCTION',WF),
4350 kernel_objects:equal_object_wf(Res,RV,WF),
4351 add_error(external_functions,'Function ID not registered:',MemoID,Span)).
4352
4353 % -------------------
4354
4355 :- use_module(eval_let_store,[stored_let_value/3, set_stored_let_value/3,
4356 retract_stored_let_value/3, reset_let_values/0,
4357 extend_state_with_stored_lets/2, get_stored_let_typing_scope/1]).
4358
4359 :- public 'STORE'/4.
4360 external_fun_type('STORE',[X],[X,X]).
4361 expects_waitflag('STORE').
4362 expects_unevaluated_args('STORE').
4363 % stores values just like :let in the REPL does, but can be used within a predicate;
4364 % here name inferred from AST and it is a transparent function for more convenient annotation
4365 % also a way to store global values
4366 :- block 'STORE'(-,?,?,?).
4367 'STORE'(Val,Res,[TVal],WF) :- equal_object_optimized_wf(Val,Res,'STORE',WF),
4368 (translate:try_get_identifier(TVal,ID) -> true % also checks for was_identifier
4369 ; translate:translate_bexpression(TVal,ID),
4370 add_warning('STORE','The expression is not an identifier:',ID,TVal)
4371 ),
4372 'STORE_VALUE'(string(ID),Val,pred_true,[_,TVal],WF).
4373
4374 external_fun_type('STORE_VALUE',[X],[string,X,boolean]).
4375 expects_waitflag('STORE_VALUE').
4376 expects_unevaluated_args('STORE_VALUE').
4377 % stores values just like :let in the REPL does, but can be used within a predicate
4378 :- block 'STORE_VALUE'(-,?,?,?,?).
4379 'STORE_VALUE'(string(ID),Val,PredRes,UnevaluatedArgs,WF) :- PredRes=pred_true,
4380 get_enumeration_finished_wait_flag(WF,EWF),
4381 (UnevaluatedArgs = [_,TVal]
4382 -> get_texpr_type(TVal,Type)
4383 ; add_error('STORE_VALUE','Unexpected AST for arguments:',UnevaluatedArgs),
4384 Type=any),
4385 store_value(ID,Type,Val,EWF).
4386
4387 :- block store_value(-,?,?,?), store_value(?,?,?,-).
4388 store_value(ID,Type,Val,_) :-
4389 adapt_stored_id(ID,FullID),
4390 set_stored_let_value(FullID,Type,Val).
4391
4392 adapt_stored_id(ID,FullID) :-
4393 atom_concat('$USER.',ID,FullID). % avoid name clashes with other variables
4394 % Note: with :let in the REPL you want to re-use the variable; here we probably only access it using RECALL_VALUE
4395
4396 :- use_module(btypechecker, [unify_types_werrors/4]).
4397 :- public 'RECALL_VALUE'/5.
4398 external_fun_type('RECALL_VALUE',[X],[string,X]).
4399 expects_waitflag('RECALL_VALUE').
4400 expects_spaninfo('RECALL_VALUE').
4401 expects_type('RECALL_VALUE').
4402 % typically has to be used within a predicate to type the return value x:INTEGER & x=RECALL_VALUE("name")
4403 :- block 'RECALL_VALUE'(-,?,?,?,?).
4404 'RECALL_VALUE'(string(ID),Res,Type,Span,WF) :-
4405 recall_value(ID,Res,Type,Span,WF).
4406
4407 :- block recall_value(-,?,?,?,?).
4408 recall_value(ID,Res,Type,Span,WF) :-
4409 adapt_stored_id(ID,FullID),
4410 stored_let_value(FullID,StoredType,Val),
4411 !,
4412 (unify_types_werrors(Type,StoredType,Span,'RECALL_VALUE')
4413 -> equal_object_optimized_wf(Val,Res,'RECALL_VALUE',WF)
4414 ; add_error_wf('RECALL_VALUE','Stored value has incompatible type:',ID,Span,WF)
4415 ).
4416 recall_value(ID,_,_,Span,WF) :-
4417 add_error_wf('RECALL_VALUE','No value stored with STORE_VALUE or :let for:',ID,Span,WF),
4418 fail.
4419
4420
4421 :- public 'TRY_RECALL_VALUE'/6.
4422 external_fun_type('TRY_RECALL_VALUE',[X],[string,X,X]).
4423 expects_waitflag('TRY_RECALL_VALUE').
4424 expects_spaninfo('TRY_RECALL_VALUE').
4425 expects_type('TRY_RECALL_VALUE').
4426 % can be used more easily within an expression as type provided by default value
4427 :- block 'TRY_RECALL_VALUE'(-,?,?,?,?,?).
4428 'TRY_RECALL_VALUE'(string(ID),DefaultValue,Res,Type,Span,WF) :-
4429 recall_value_with_default(ID,DefaultValue,Res,Type,Span,WF).
4430
4431 :- block recall_value_with_default(-,?,?,?,?,?).
4432 recall_value_with_default(ID,_Default,Res,Type,Span,WF) :-
4433 adapt_stored_id(ID,FullID),
4434 stored_let_value(FullID,StoredType,Val),
4435 !,
4436 (unify_types_werrors(Type,StoredType,Span,'TRY_RECALL_VALUE')
4437 -> equal_object_optimized_wf(Val,Res,'RECALL_VALUE',WF)
4438 ; add_error_wf('TRY_RECALL_VALUE','Stored value has incompatible type:',ID,Span,WF)
4439 ).
4440 recall_value_with_default(_ID,Default,Res,_,_Span,WF) :-
4441 equal_object_optimized_wf(Default,Res,'TRY_RECALL_VALUE',WF).
4442
4443 :- public 'CAN_RECALL_VALUE'/3.
4444 external_fun_type('CAN_RECALL_VALUE',[],[string,boolean]).
4445 expects_waitflag('CAN_RECALL_VALUE').
4446 :- block 'CAN_RECALL_VALUE'(-,?,?).
4447 'CAN_RECALL_VALUE'(ID,PredRes,WF) :-
4448 (nonvar(ID) -> true
4449 ; kernel_waitflags:get_wait_flag(10,'CAN_RECALL_VALUE',WF,WF10)),
4450 has_stored_value(ID,PredRes,WF10).
4451
4452 :- block has_stored_value(-,?,-).
4453 has_stored_value(string(ID),PredRes,_) :- nonvar(ID),!,
4454 adapt_stored_id(ID,FullID),
4455 if(stored_let_value(FullID,_StoredType,_Val),PredRes=pred_true,PredRes=pred_false).
4456 has_stored_value(string(ID),PredRes,_) :-
4457 if(stored_let_value(FullID,_StoredType,_Val),PredRes=pred_true,PredRes=pred_false),
4458 adapt_stored_id(ID,FullID).
4459
4460 % TODO: do we need a DELETE_STORED_VALUE external function
4461
4462 % -------------------
4463 % a few ugraphs (unweighted graphs) utilities:
4464
4465 % an alternate implementation of closure1, cubic and using Warshall's algorithm from ugraphs
4466 expects_spaninfo('CLOSURE1').
4467 external_fun_type('CLOSURE1',[X],[set(couple(X,X)),set(couple(X,X))]).
4468 :- public 'CLOSURE1'/3.
4469 :- block 'CLOSURE1'(-,?,?).
4470 'CLOSURE1'([],Res,_) :- !, kernel_objects:equal_object(Res,[]).
4471 'CLOSURE1'(avl_set(A),Res,_) :- !, closure1_for_avl_set(A,R), kernel_objects:equal_object_optimized(R,Res).
4472 'CLOSURE1'(A,Res,Span) :- ground_value_check(A,Gr), closure1_gr(A,Gr,Res,Span).
4473
4474 closure1_gr(Set,_,Res,Span) :- convert_to_avl(Set,AVL),!, 'CLOSURE1'(AVL,Res,Span).
4475 closure1_gr(Set,_,_,Span) :-
4476 add_error(external_functions,'Cannot convert CLOSURE1 argument to set: ',Set,Span).
4477
4478 % compute strongly connected components
4479 expects_spaninfo('SCCS').
4480 external_fun_type('SCCS',[X],[set(couple(X,X)),set(set(X))]).
4481 :- public 'SCCS'/3.
4482 :- block 'SCCS'(-,?,?).
4483 'SCCS'([],Res,_) :- !, kernel_objects:equal_object(Res,[]).
4484 'SCCS'(avl_set(A),Res,_) :- !, sccs_for_avl_set(A,R), kernel_objects:equal_object_optimized(R,Res).
4485 'SCCS'(A,Res,Span) :- ground_value_check(A,Gr), sccs_gr(A,Gr,Res,Span).
4486
4487 sccs_gr(Set,_,Res,Span) :- convert_to_avl(Set,AVL),!, 'SCCS'(AVL,Res,Span).
4488 sccs_gr(Set,_,_,Span) :-
4489 add_error(external_functions,'Cannot convert SCCS argument to set: ',Set,Span).
4490
4491 :- use_module(extrasrc(avl_ugraphs),[avl_transitive_closure/2, avl_scc_sets/2]).
4492 closure1_for_avl_set(A,Res) :-
4493 avl_transitive_closure(A,TC),
4494 construct_avl_set(TC,Res).
4495 sccs_for_avl_set(A,Res) :-
4496 avl_scc_sets(A,TC),
4497 construct_avl_set(TC,Res).
4498 construct_avl_set(Avl,Res) :- empty_avl(Avl) -> Res = [] ; Res = avl_set(Avl).
4499 % -------------------
4500
4501 reset_kodkod :-
4502 true. %retractall(kodkod_pred(_,_)).
4503
4504 %:- use_module(probsrc(bsyntaxtree), [b_compute_expression/5]).
4505
4506 % KODKOD(ProblemID, LocalIDsOfPredicate, WaitToBeGroundBeforePosting, PredicateAsBooleanFunction)
4507 % EXTERNAL_PREDICATE_KODKOD(T1,T2) == INTEGER*T1*T2*BOOL;
4508 %:- dynamic kodkod_pred/2. % now stored as attribute in WF store
4509 do_not_evaluate_args('KODKOD').
4510 expects_unevaluated_args('KODKOD').
4511 expects_waitflag('KODKOD').
4512 expects_spaninfo('KODKOD').
4513 expects_state('KODKOD').
4514
4515 :- use_module(bsyntaxtree,[create_negation/2]).
4516 :- use_module(b_compiler,[b_optimize/6]).
4517 :- use_module(b_interpreter,[b_compute_expression/5]).
4518 :- public 'KODKOD'/6.
4519 :- block 'KODKOD'(-,?,?,?,?,?).
4520 'KODKOD'(PredRes,LocalState,State,UnevaluatedArgs,Span,WF) :-
4521 UnevaluatedArgs = [TID,IDEXPR,WAITIDEXPR,UEA],
4522 get_integer(TID,ID),
4523 construct_predicate(UEA,KPredicate),
4524 (PredRes == pred_false -> create_negation(KPredicate,Predicate) ; Predicate=KPredicate),
4525 must_get_identifiers('KODKOD',IDEXPR,TIdentifiers),
4526 get_texpr_ids(TIdentifiers,Ids),
4527 b_compute_expression(WAITIDEXPR,LocalState,State,WaitVal,WF),
4528 when(ground(WaitVal),
4529 ( b_optimize(Predicate,Ids,LocalState,State,CPredicate,WF),
4530 (debug:debug_mode(off) -> true
4531 ; add_message(kodkod,'STORING FOR KODKOD : ',ID:PredRes,Span), translate:print_bexpr(CPredicate),nl),
4532 kernel_waitflags:my_add_predicate_to_kodkod(WF,ID,CPredicate),
4533 %assertz(kodkod_pred(ID,CPredicate)), % TO DO: attach to WF Store !; assertz will break Prolog variable links !
4534 % TO DO: retract upon backtracking + store negation if PredRes = pred_false
4535 PredRes=pred_true
4536 )).
4537
4538
4539 :- use_module(probsrc(bsyntaxtree), [safe_create_texpr/3]).
4540 construct_predicate(b(convert_bool(P),_,_),Res) :- !, Res=P.
4541 construct_predicate(BoolExpr,Res) :-
4542 safe_create_texpr(equal(BoolExpr,b(boolean_true,boolean,[])),pred,Res).
4543
4544 :- use_module(kodkodsrc(kodkod), [replace_by_kodkod/3]).
4545 % EXTERNAL_PREDICATE_KODKOD_SOLVE(T1,T2) == INTEGER*T1*T2;
4546 expects_unevaluated_args('KODKOD_SOLVE').
4547 expects_waitflag('KODKOD_SOLVE').
4548 expects_state('KODKOD_SOLVE').
4549 :- public 'KODKOD_SOLVE'/8.
4550 :- block 'KODKOD_SOLVE'(-,?,?,?,?,?,?,?).
4551 'KODKOD_SOLVE'(int(ID),Ids,WaitIds,PredRes,LocalState,State,UEA,WF) :-
4552 when(ground(WaitIds),
4553 kodkod_solve_aux(ID,Ids,WaitIds,PredRes,LocalState,State,UEA,WF)).
4554
4555 :- use_module(library(ordsets),[ord_subtract/3]).
4556 kodkod_solve_aux(ID,Ids,_WaitIds,PredRes,LocalState,State,UEA,WF) :-
4557 %print(trigger_SOLVE(_WaitIds)),nl,
4558 get_wait_flag(2,'KODKOD_SOLVE',WF,LWF), % give other co-routines chance to fire
4559 kodkod_solve_aux2(ID,Ids,PredRes,LocalState,State,UEA,WF,LWF).
4560
4561 :- block kodkod_solve_aux2(?,?,?,?,?,?,?,-).
4562 kodkod_solve_aux2(ID,_,PredRes,LocalState,State,[_,IDEXPR,WAITIDEXPR],WF,_) :-
4563 %print(ls(LocalState,State)),nl,
4564 %findall(P,kodkod_pred(ID,P),Ps), % TO DO: obtain from WF Store
4565 kernel_waitflags:my_get_kodkod_predicates(WF,ID,Ps),
4566 length(Ps,Len),
4567 reverse(Ps,RPs), % we reverse Ps to put predicates in same order they were added by KODKOD / seems to influence analysis time
4568 conjunct_predicates(RPs,Predicate),
4569 %translate:print_bexpr(Predicate),nl,
4570 must_get_identifiers('KODKOD_SOLVE',IDEXPR,TIdentifiers),
4571 get_texpr_ids(TIdentifiers,Ids),
4572 ((get_identifiers(WAITIDEXPR,TWaitIds,[]), get_texpr_ids(TWaitIds,WaitIds),
4573 sort(WaitIds,SWIds),
4574 formatsilent('KODKOD_SOLVE Problem ~w (~w conjuncts), Identifiers: ~w, Waiting for ~w~n',[ID,Len,Ids,SWIds]),
4575 sort(Ids,SIds),
4576 ord_subtract(SIds,SWIds,IdsToSolve))
4577 -> b_optimize(Predicate,IdsToSolve,LocalState,State,CPredicate,WF), % inline known values
4578 (silent_mode(on) -> true ; print('compiled: '),translate:print_bexpr(CPredicate),nl,nl)
4579 ; CPredicate=Predicate
4580 ),
4581 (replace_by_kodkod(TIdentifiers,CPredicate,NewPredicate)
4582 -> (silent_mode(on) -> true ; print('AFTER KODKOD: '),translate:print_bexpr(NewPredicate),nl),
4583 b_interpreter:b_test_boolean_expression(NewPredicate,LocalState,State,WF)
4584 ; print('KODKOD cannot be applied'),nl,
4585 b_interpreter:b_test_boolean_expression(CPredicate,LocalState,State,WF)
4586 ),
4587 PredRes=pred_true.
4588
4589 must_get_identifiers(PP,TExpr,Res) :-
4590 (get_identifiers(TExpr,Ids,[]) -> Res=Ids
4591 ; add_error(PP,'Could not get identifiers: ',TExpr),fail).
4592
4593 get_identifiers(b(couple(A1,A2),_,_)) --> !, get_identifiers(A1), get_identifiers(A2).
4594 get_identifiers(b(identifier(ID),T,I)) --> [b(identifier(ID),T,I)].
4595 get_identifiers(b(integer(_),_,_)) --> []. % to do: accept other ground values; in case they are compiled
4596 get_identifiers(b(value(_),_,_)) --> []. % identifier has already been compiled
4597 get_identifiers(b(string(_),_,_)) --> [].
4598
4599
4600 % -------------------
4601 do_not_evaluate_args('SATSOLVER').
4602 expects_unevaluated_args('SATSOLVER').
4603 expects_waitflag('SATSOLVER').
4604 expects_spaninfo('SATSOLVER').
4605 expects_state('SATSOLVER').
4606
4607 :- use_module(kernel_tools,[value_variables/2]).
4608 :- public 'SATSOLVER'/6.
4609 :- block 'SATSOLVER'(-,?,?,?,?,?).
4610 'SATSOLVER'(PredRes,LocalState,State,UnevaluatedArgs,Span,WF) :-
4611 UnevaluatedArgs = [TID,IDEXPR,WAITIDEXPR,UEA],
4612 get_integer(TID,ID),
4613 construct_predicate(UEA,KPredicate),
4614 (PredRes == pred_false -> create_negation(KPredicate,Predicate) ; Predicate=KPredicate),
4615 must_get_identifiers('SATSOLVER',IDEXPR,TIdentifiers),
4616 get_texpr_ids(TIdentifiers,Ids),
4617 % Note: the Ids are not really necessary here; they are just used for b_optimize; see SATSOLVER_SOLVE below
4618 b_interpreter:b_compute_expression(WAITIDEXPR,LocalState,State,WaitVal,WF),
4619 value_variables(WaitVal,WVars),
4620 when(ground(WVars),
4621 ( %print(compile_for(ID,Ids)),nl,
4622 %nl,add_message(satsolver,'Optimzing for SATSOLVER_SOLVE: ',Predicate,Span), debug:nl_time,
4623 %translate:nested_print_bexpr(Predicate),nl,
4624 b_optimize(Predicate,Ids,LocalState,State,CPredicate,WF), % Ids are left in the closure
4625 (debug:debug_mode(off) -> true
4626 ; add_message(satsolver,'Storing for SATSOLVER_SOLVE: ',CPredicate,Span)
4627 ),
4628 kernel_waitflags:my_add_predicate_to_satsolver(WF,ID,CPredicate),
4629 % TO DO: retract upon backtracking + store negation if PredRes = pred_false
4630 PredRes=pred_true
4631 )).
4632
4633 expects_unevaluated_args('SATSOLVER_SOLVE').
4634 expects_waitflag('SATSOLVER_SOLVE').
4635 expects_state('SATSOLVER_SOLVE').
4636 :- public 'SATSOLVER_SOLVE'/8.
4637 :- block 'SATSOLVER_SOLVE'(-,?,?,?,?,?,?,?).
4638 'SATSOLVER_SOLVE'(int(ID),Ids,WaitIds,PredRes,LocalState,State,UEA,WF) :-
4639 value_variables(WaitIds,WVars),
4640 get_wait_flag1('SATSOLVER_SOLVE',WF,WF1),
4641 when(ground((WF1,WVars)),
4642 satsolver_solve_aux(ID,Ids,WaitIds,PredRes,LocalState,State,UEA,WF)).
4643 % Note: the Ids are not really necessary here; they are just used for b_optimize
4644 % The b_to_cnf conversion will look up all identifiers anyway, identifier or value(_) node makes no difference!
4645 % TODO: probably remove them
4646
4647 :- use_module(library(ordsets),[ord_subtract/3]).
4648 satsolver_solve_aux(ID,Ids,_WaitIds,PredRes,LocalState,State,UEA,WF) :-
4649 %print(trigger_SOLVE(_WaitIds)),nl,
4650 get_idle_wait_flag('SATSOLVER_SOLVE',WF,LWF), % give other co-routines chance to fire
4651 satsolver_solve_aux2(ID,Ids,PredRes,LocalState,State,UEA,WF,LWF).
4652
4653 :- use_module(extension('satsolver/b2sat'), [solve_predicate_with_satsolver/2]).
4654
4655 :- block satsolver_solve_aux2(?,?,?,?,?,?,?,-).
4656 satsolver_solve_aux2(ID,_,PredRes,LocalState,State,[_,IDEXPR,WAITIDEXPR],WF,_) :-
4657 print('SATSOLVER_SOLVE:'),nl,
4658 kernel_waitflags:my_get_satsolver_predicates(WF,ID,Ps),
4659 length(Ps,Len), format('Got ~w SATSOLVER predicates for ID: ~w~n',[Len,ID]),
4660 reverse(Ps,RPs), % we reverse Ps to put predicates in same order they were added, necessary??
4661 conjunct_predicates(RPs,Predicate),
4662 %translate:print_bexpr(Predicate),nl,
4663 must_get_identifiers('SATSOLVER_SOLVE',IDEXPR,TIdentifiers),
4664 get_texpr_ids(TIdentifiers,Ids),
4665 ((get_identifiers(WAITIDEXPR,TWaitIds,[]), get_texpr_ids(TWaitIds,WaitIds),
4666 sort(WaitIds,SWIds),
4667 formatsilent('Sat Solver identifiers: ~w ; waiting for ~w~n',[Ids,SWIds]),
4668 sort(Ids,SIds),
4669 ord_subtract(SIds,SWIds,IdsToSolve))
4670 -> b_optimize(Predicate,IdsToSolve,LocalState,State,CPredicate,WF), % inline known values
4671 (debug_mode(off) -> true
4672 ; print('compiled: '),translate:print_bexpr(CPredicate),nl,nl)
4673 ; CPredicate=Predicate
4674 ),
4675 (solve_predicate_with_satsolver(CPredicate,State)
4676 % if(b_interpreter:b_test_boolean_expression(CPredicate,[],State,WF),print(ok),
4677 % add_error_wf('SATSOLVER_SOLVE','SAT result not confirmed by ProB:',ID,CPredicate,WF))
4678 % TODO: catch errors if b_sat fails!
4679 %-> true
4680 % ; print('Calling SAT solver failed'),nl,
4681 % b_interpreter:b_test_boolean_expression(CPredicate,LocalState,State,WF)
4682 ),
4683 PredRes=pred_true.
4684 % -------------------
4685
4686
4687 expects_waitflag('UNSAT_CORE'). % WF not used at the moment
4688 expects_spaninfo('UNSAT_CORE').
4689 :- public 'UNSAT_CORE'/5.
4690 % EXTERNAL_FUNCTION_UNSAT_CORE(T) == (POW(T)-->BOOL)*POW(T) --> POW(T);
4691 % UNSAT_CORE(Fun,Set) == Set
4692 % example: UNSAT_CORE(f,0..200) = {2} with f = %x.(x:POW(INTEGER)|bool(x /\ 1..2={}))
4693 'UNSAT_CORE'(FunToBool,Set,ValueRes,SpanInfo,WF) :-
4694 'UNSAT_CORE_ACC'(FunToBool,Set,[],ValueRes,SpanInfo,WF).
4695
4696
4697 expects_waitflag('UNSAT_CORE_ACC'). % WF not used at the moment
4698 expects_spaninfo('UNSAT_CORE_ACC').
4699 % EXTERNAL_FUNCTION_UNSAT_CORE_ACC(T) == (POW(T)-->BOOL)*POW(T)*POW(T) --> POW(T);
4700 % UNSAT_CORE_ACC(Fun,Set,Acc) == Set\/Acc;
4701 % example: UNSAT_CORE_ACC(f,0..200,{}) = {2} & f = %x.(x:POW(INTEGER)|bool(x /\ 1..2={}))
4702 % provides a way to initialise the accumulator of the unsat core computation
4703 'UNSAT_CORE_ACC'(FunToBool,Set,Acc,ValueRes,SpanInfo,WF) :-
4704 expand_custom_set_to_list_wf(Set,ESet,_,compute_apply_true,WF),
4705 expand_custom_set_to_list_wf(Acc,EAcc,_,compute_apply_true,WF),
4706 debug_println(9,computing_unsat_core(ESet,EAcc)),
4707 when(ground((FunToBool,ESet)), compute_unsat_core(ESet,FunToBool,no_time_out,EAcc,ValueRes,SpanInfo,WF)).
4708
4709 % EXTERNAL_FUNCTION_UNSAT_CORE_ACC_TIMEOUT(T) == (POW(T)-->BOOL)*POW(T)*POW(T)*INTEGER --> POW(T);
4710 % UNSAT_CORE_ACC_TIMEOUT(Fun,Set,Acc,TO) == Set\/Acc;
4711 % example: UNSAT_CORE_ACC_TIMEOUT(f,0..200,{},100) = {2} & f = %x.(x:POW(INTEGER)|bool(x /\ 1..2={}))
4712 expects_waitflag('UNSAT_CORE_ACC_TIMEOUT'). % WF not used at the moment
4713 expects_spaninfo('UNSAT_CORE_ACC_TIMEOUT').
4714 :- public 'UNSAT_CORE_ACC_TIMEOUT'/7.
4715 'UNSAT_CORE_ACC_TIMEOUT'(FunToBool,Set,Acc,int(TimeOut),ValueRes,SpanInfo,WF) :-
4716 expand_custom_set_to_list_wf(Set,ESet,_,compute_apply_true,WF),
4717 expand_custom_set_to_list_wf(Acc,EAcc,_,compute_apply_true,WF),
4718 debug_println(9,computing_unsat_core(ESet,EAcc)),
4719 when(ground((FunToBool,ESet,TimeOut)), compute_unsat_core(ESet,FunToBool,TimeOut,EAcc,ValueRes,SpanInfo,WF)).
4720
4721 compute_unsat_core([],_FunToBool,_TimeOut,Core,Result,_SpanInfo,WF) :- equal_object_wf(Result,Core,WF).
4722 compute_unsat_core([H|T],FunToBool,TimeOut,Core,Result,SpanInfo,WF) :-
4723 debug_println(9,trying_to_remove(H,core(Core))),
4724 append(Core,T,CoreT),
4725 if(compute_apply_true_timeout(TimeOut,FunToBool,CoreT,SpanInfo),
4726 compute_unsat_core(T,FunToBool,TimeOut,[H|Core],Result,SpanInfo,WF), % we found a solution, H is needed in core
4727 compute_unsat_core(T,FunToBool,TimeOut, Core, Result,SpanInfo,WF) % contradiction also exists without H
4728 ).
4729
4730 :- use_module(library(timeout)).
4731 compute_apply_true_timeout(no_time_out,FunToBool,CoreT,SpanInfo) :- !,
4732 compute_apply_true(FunToBool,CoreT,SpanInfo).
4733 compute_apply_true_timeout(TO,FunToBool,CoreT,SpanInfo) :-
4734 time_out(compute_apply_true(FunToBool,CoreT,SpanInfo), TO, TORes),
4735 (TORes == success -> true ,format(user_output,'~nSUCCESS~n~n',[])
4736 ; format(user_output,'~nTIME-OUT: ~w~n~n',[TORes]),fail). % treat time-out like failure
4737
4738 compute_apply_true(FunToBool,CoreT,SpanInfo) :-
4739 init_wait_flags_with_call_stack(WF1,[prob_command_context(compute_apply_true,unknown)]),
4740 bsets_clp:apply_to(FunToBool,CoreT,pred_true,SpanInfo,WF1), % TO DO: also pass function type
4741 ground_wait_flags(WF1).
4742
4743 expects_waitflag('MAX_SAT').
4744 expects_spaninfo('MAX_SAT').
4745 :- public 'MAX_SAT'/5.
4746 % EXTERNAL_FUNCTION_MAX_SAT(T) == (POW(T)-->BOOL)*POW(T) --> POW(T);
4747 % MAX_SAT(Fun,Set) == Set;
4748 % example: MAX_SAT(f,0..3) = {0,3} & f = %x.(x:POW(INTEGER)|bool(x /\ 1..2={}))
4749
4750 'MAX_SAT'(FunToBool,Set,ValueRes,SpanInfo,WF) :-
4751 expand_custom_set_to_list_wf(Set,ESet,_,compute_apply_true,WF),
4752 debug_println(9,computing_unsat_core(ESet)),
4753 when(ground((FunToBool,ESet)), compute_maxsat_ground(ESet,FunToBool,ValueRes,SpanInfo,WF)).
4754
4755 compute_maxsat_ground(ESet,FunToBool,ValueRes,SpanInfo,WF) :-
4756 debug_println(9,computing_maxsat(ESet)), %nl,reset_walltime,
4757 get_wait_flag(1,'MAX_SAT',WF,LWF), % avoid computing straightaway in case pending co-routines fail; not really sure it is needed
4758 when(nonvar(LWF),compute_maxsat(ESet,FunToBool,[],ValueRes,SpanInfo,WF)).
4759 compute_maxsat([],_FunToBool,Core,Result,_SpanInfo,_WF) :- equal_object(Result,Core).
4760 compute_maxsat([H|T],FunToBool,Core,Result,SpanInfo,WF) :-
4761 debug_println(9,trying_to_add(H,core(Core))),
4762 %nl,nl,nl,print(maxsat(H,Core)),nl, print_walltime(user_output),nl,
4763 if(compute_apply_true(FunToBool,[H|Core],SpanInfo),
4764 compute_maxsat(T,FunToBool,[H|Core],Result,SpanInfo,WF),
4765 compute_maxsat(T,FunToBool, Core, Result,SpanInfo,WF) % contradiction also exists without H
4766 ).
4767
4768 % can be used to maximize a bounded integer expression
4769 % more limited than optimizing_solver (only optimizing integers), but using inlined branch and bound enumeration
4770 % example usage: xx:1..10 & res=10*xx-xx*xx & MAXIMIZE_EXPR(res)
4771 :- use_module(clpfd_interface,[clpfd_domain/3, clpfd_inrange/3, clpfd_size/2, clpfd_eq/2]).
4772 expects_waitflag('MAXIMIZE_EXPR').
4773 expects_spaninfo('MAXIMIZE_EXPR').
4774 :- public 'MAXIMIZE_EXPR'/4.
4775 'MAXIMIZE_EXPR'(int(X),PredRes,Span,WF) :-
4776 %get_wait_flag1('MAXIMIZE_EXPR',WF,LWF),
4777 get_wait_flag(2,'MAXIMIZE_EXPR',WF,LWF),
4778 PredRes=pred_true,
4779 maximize_expr_wf(LWF,X,Span,WF).
4780 :- block maximize_expr_wf(-,?,?,?).
4781 maximize_expr_wf(_LWF,X,Span,WF) :-
4782 clpfd_size(X,Size), Size \= sup,
4783 clpfd_domain(X,Min,Max),
4784 Mid is round((Min + Max)/2),
4785 !,
4786 maximize_expr_6(Min,Mid,Max,X,Span,WF).
4787 maximize_expr_wf(_,_,Span,_) :-
4788 add_error(external_functions,'MAXIMIZE_EXPR/MINIMIZE_EXPR called on unbounded expression',Span),
4789 fail.
4790 maximize_expr_6(M,M,M,X,Span,WF) :- !, X=M,
4791 add_message(external_functions,'Checking optimisation target for MAXIMIZE_EXPR/MINIMIZE_EXPR: ',X,Span),
4792 ground_wait_flags(WF). % NOTE: without fully grounding WF: we do not know if a solution has really been found !
4793 maximize_expr_6(Min,Mid,Max,X,Span,WF) :- % tools_printing:print_term_summary(maximize_expr_6(Min,Mid,Max,X)),nl,
4794 %add_message(external_functions,'Optimisation target for MAXIMIZE_EXPR/MINIMIZE_EXPR: ',Min:Max,Span),
4795 if( (clpfd_inrange(X,Mid,Max),
4796 NMid is round((Mid+Max)/2),
4797 maximize_expr_6(Mid,NMid,Max,X,Span,WF)),
4798 true, % we found a solution in the upper half
4799 (Mid>Min, M1 is Mid-1,
4800 clpfd_inrange(X,Min,M1),
4801 NMid is round((Min+M1)/2),
4802 maximize_expr_6(Min,NMid,M1,X,Span,WF)
4803 ) ).
4804
4805 expects_waitflag('MINIMIZE_EXPR').
4806 expects_spaninfo('MINIMIZE_EXPR').
4807 :- public 'MINIMIZE_EXPR'/4.
4808 'MINIMIZE_EXPR'(int(X),PredRes,Span,WF) :-
4809 clpfd_eq(-X,MaxVar),
4810 'MAXIMIZE_EXPR'(int(MaxVar),PredRes,Span,WF).
4811
4812
4813 :- use_module(kernel_tools,[bexpr_variables/2]).
4814 % maximize is actually quite similar to CHOOSE; but it will choose maximum and use special algorithm for closures
4815 expects_waitflag('MAXIMIZE').
4816 expects_spaninfo('MAXIMIZE').
4817 :- public 'MAXIMIZE'/4.
4818 :- block 'MAXIMIZE'(-,?,?,?).
4819 'MAXIMIZE'([],_,Span,WF) :- !,
4820 add_wd_error_span('MAXIMIZE applied to empty set: ',[],Span,WF).
4821 'MAXIMIZE'(avl_set(A),H,_,_) :- !, avl_max(A,Max),kernel_objects:equal_object(H,Max).
4822 'MAXIMIZE'(closure(P,T,Body),FunValue,SpanInfo,WF) :- !,
4823 bexpr_variables(Body,ClosureWaitVars),
4824 debug_println(19,wait_maximize(P,ClosureWaitVars)),
4825 when(ground(ClosureWaitVars),maximize_closure(P,T,Body,FunValue,SpanInfo,WF)).
4826 'MAXIMIZE'([H|T],C,Span,WF) :- !,
4827 when(ground([H|T]),
4828 (convert_to_avl([H|T],AVL) -> 'MAXIMIZE'(AVL,C,Span,WF)
4829 ; add_wd_error_span('Cannot determine maximum element for MAXIMIZE: ',[H|T],Span,WF),
4830 kernel_objects:equal_object_wf(C,H,WF))
4831 ).
4832 'MAXIMIZE'(_,_,SpanInfo,_WF) :-
4833 add_error(external_functions,'MAXIMIZE requires set of values',SpanInfo),
4834 fail.
4835
4836 % move to optimizing solver
4837 % difference here is that entire constraint is re-set up every time; allowing Kodkod to be used
4838 maximize_closure(Parameters,ParameterTypes,ClosureBody,FunValue,_SpanInfo,WF) :-
4839 debug_println(maximizing(Parameters)),
4840 length(Parameters,Len), length(ParValues,Len),
4841 test_closure(Parameters,ParameterTypes,ClosureBody,ParValues),
4842 debug_println(19,found_initial_solution(ParValues)),
4843 !,
4844 maximize_closure2(Parameters,ParameterTypes,ClosureBody,ParValues,FunValue,WF).
4845 maximize_closure(_Parameters,_ParameterTypes,_ClosureBody,_FunValue,SpanInfo,_WF) :-
4846 add_error(external_functions,'MAXIMIZE: could not find solution for set comprehension',SpanInfo),
4847 fail.
4848
4849 maximize_closure2(Parameters,ParameterTypes,ClosureBody,PrevSol,FunValue,WF) :-
4850 Parameters=[PMax|_], ParameterTypes=[T1|_],
4851 PrevSol = [ PrevVal | _],
4852 debug_println(19,trying_to_improve_upon(PrevVal,PMax)),
4853 better_sol_pred(PMax,T1,PrevVal,Better),
4854 %translate:print_bexpr(Better),nl,
4855 bsyntaxtree:conjunct_predicates([Better,ClosureBody],NewBody),
4856 length(Parameters,Len), length(NewParValues,Len),
4857 test_closure(Parameters,ParameterTypes,NewBody,NewParValues),
4858 debug_println(19,found_better_solution(NewParValues)),
4859 !,
4860 maximize_closure2(Parameters,ParameterTypes,ClosureBody,NewParValues,FunValue,WF).
4861 maximize_closure2(_Parameters,_ParameterTypes,_ClosureBody,PrevSol,FunValue,WF) :-
4862 debug_println(19,cannot_improve),
4863 tools:convert_list_into_pairs(PrevSol,ParTuple),
4864 kernel_objects:equal_object_wf(ParTuple,FunValue,WF).
4865
4866 :- use_module(probsrc(solver_interface),[apply_kodkod_or_other_optimisations/4]).
4867 test_closure(Parameters,ParameterTypes,Body,ParValues) :-
4868 apply_kodkod_or_other_optimisations(Parameters,ParameterTypes,Body,Body2),
4869 custom_explicit_sets:b_test_closure(Parameters,ParameterTypes,Body2,ParValues,positive,no_wf_available). % positive instead of all_solutions
4870
4871 % generate predicate for better solution; % TO DO: support MINIMIZE by inverting args
4872 % TO DO: support more types: couples, booleans, ...
4873 better_sol_pred(PMax,integer,PrevVal,Better) :- !,
4874 Better = b(less(b(value(PrevVal),integer,[]),b(identifier(PMax),integer,[])),pred,[]).
4875 better_sol_pred(PMax,set(T1),PrevVal,Better) :- !,
4876 % WARNING: for sets we will only find one maximum, not all due to the cuts in maximize_closure(2) above
4877 Better = b(subset_strict(b(value(PrevVal),set(T1),[]),b(identifier(PMax),set(T1),[])),pred,[]).
4878 better_sol_pred(PMax,Type,_Val,_) :-
4879 add_error(external_functions,'MAXIMIZE requires first argument of set comprehension to be integer or set; cannot optimize: ',PMax:Type),fail.
4880
4881 % ----------------------------------
4882
4883 % EXTERNAL_FUNCTION_READ_XML == STRING --> seq(XML_ELement_Type);
4884 % with XML_ELement_Type == struct( recId: NATURAL1, pId:NATURAL, element:STRING, attributes: STRING +-> STRING, meta: STRING +-> STRING );
4885
4886 % XML_ELement_Type from LibraryXML.def:
4887 xml_element_type(record([ field(recId,integer), field(pId, integer), field(element,string),
4888 field(attributes, set(couple(string,string))),
4889 field(meta, set(couple(string,string))) ]) ).
4890
4891 performs_io('READ_XML').
4892 expects_spaninfo('READ_XML').
4893 :- public 'READ_XML'/3.
4894 :- block 'READ_XML'(-,?,?).
4895 'READ_XML'(string(File),Res,Span) :-
4896 read_xml(File,auto,Res,Span).
4897
4898 %expects_spaninfo('READ_XML'). both versions expect span info
4899 external_fun_type('READ_XML',[],[string,string,seq(XT)]) :- xml_element_type(XT).
4900 :- public 'READ_XML'/4.
4901 :- block 'READ_XML'(-,?,?,?),'READ_XML'(?,-,?,?).
4902 'READ_XML'(string(File),string(Encoding),Res,Span) :-
4903 read_xml(File,Encoding,Res,Span).
4904
4905
4906 :- use_module(tools, [read_string_from_file/3, detect_xml_encoding/3]).
4907 :- use_module(extrasrc(xml2b), [convert_xml_to_b/4]).
4908 :- use_module(preferences, [is_of_type/2]).
4909 :- block read_xml(-,?,?,?), read_xml(?,-,?,?).
4910 read_xml(File,EncodingPref,Res,Span) :-
4911 b_absolute_file_name(File,AFile,Span),
4912 (EncodingPref = 'auto',
4913 detect_xml_encoding(AFile,_Version,HeaderEncoding)
4914 -> (is_of_type(HeaderEncoding,text_encoding)
4915 -> Encoding=HeaderEncoding
4916 ; add_warning(read_xml,'Illegal encoding in XML header (must be "UTF-8", "UTF-16", "ISO-8859-1",...): ',HeaderEncoding),
4917 Encoding=auto
4918 )
4919 ; is_of_type(EncodingPref,text_encoding) -> Encoding = EncodingPref
4920 ; add_error(read_xml,'Illegal encoding preference (must be "auto", "UTF-8", "UTF-16", "ISO-8859-1",...): ',EncodingPref),
4921 Encoding=auto
4922 ),
4923 statistics(walltime,_),
4924 safe_call(read_string_from_file(AFile,Encoding,Codes),Span),
4925 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to read in ~w~n',[W1,AFile]),
4926 convert_xml_to_b(Codes,BDataSequence,File,Span),
4927 statistics(walltime,[_,W2]),
4928 formatsilent('% Walltime ~w ms to parse and convert XML in ~w~n',[W2,AFile]),
4929 kernel_objects:equal_object_optimized(Res,BDataSequence).
4930
4931
4932 external_fun_type('READ_XML_FROM_STRING',[],[string,seq(XT)]) :- xml_element_type(XT).
4933 expects_spaninfo('READ_XML_FROM_STRING').
4934 :- public 'READ_XML_FROM_STRING'/3.
4935 :- block 'READ_XML_FROM_STRING'(-,?,?).
4936 'READ_XML_FROM_STRING'(string(Contents),Res,Span) :-
4937 atom_codes(Contents,Codes),
4938 statistics(walltime,[W1,_]),
4939 convert_xml_to_b(Codes,BDataSequence,'string',Span),
4940 statistics(walltime,[W2,_]), W is W2-W1,
4941 formatsilent('% Walltime ~w ms to parse and convert XML~n',[W]),
4942 kernel_objects:equal_object_optimized(Res,BDataSequence).
4943
4944 :- use_module(extrasrc(json_parser),[json_parse_file/3,json_parse/3]).
4945 :- use_module(extrasrc(json_freetype),[json_parser_to_json_freetype/2]).
4946 performs_io('READ_JSON').
4947 external_fun_type('READ_JSON',[],[string,freetype('JsonValue')]).
4948 expects_spaninfo('READ_JSON').
4949 :- public 'READ_JSON'/3.
4950 :- block 'READ_JSON'(-,?,?).
4951 'READ_JSON'(string(File),Res,Span) :-
4952 read_json(File,Res,Span).
4953 :- block read_json(-,?,?).
4954 read_json(File,Res,Span) :-
4955 b_absolute_file_name(File,AFile,Span),
4956 statistics(walltime,_),
4957 safe_call(json_parse_file(AFile,Json,[]),Span),
4958 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to read and parse ~w~n',[W1,AFile]),
4959 json_parser_to_json_freetype(Json,JsonFreetype),
4960 statistics(walltime,[_,W2]),
4961 formatsilent('% Walltime ~w ms to convert JSON from ~w~n',[W2,AFile]),
4962 kernel_objects:equal_object_optimized(Res,JsonFreetype).
4963
4964 :- use_module(extrasrc(xml2b), [convert_json_to_b/3]).
4965 % reads in JSON file producing the same format as READ_XML
4966 performs_io('READ_JSON_AS_XML').
4967 external_fun_type('READ_JSON_AS_XML',[],[string,seq(XT)]) :- xml_element_type(XT).
4968 expects_spaninfo('READ_JSON_AS_XML').
4969 :- public 'READ_JSON_AS_XML'/3.
4970 :- block 'READ_JSON_AS_XML'(-,?,?).
4971 'READ_JSON_AS_XML'(string(File),Res,Span) :-
4972 read_json_as_xml(File,Res,Span).
4973 :- block read_json_as_xml(-,?,?).
4974 read_json_as_xml(File,Res,Span) :-
4975 statistics(walltime,_),
4976 b_absolute_file_name(File,AFile,Span),
4977 safe_call(json_parse_file(AFile,JSONList,[position_infos(true)]),Span),
4978 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to read and parse ~w~n',[W1,AFile]),
4979 convert_json_to_b(JSONList,BDataSequence,Span),
4980 statistics(walltime,[_,W2]),
4981 formatsilent('% Walltime ~w ms to convert JSON from ~w~n',[W2,AFile]),
4982 kernel_objects:equal_object_optimized(Res,BDataSequence).
4983
4984 external_fun_type('READ_JSON_FROM_STRING',[],[string,freetype('JsonValue')]).
4985 expects_spaninfo('READ_JSON_FROM_STRING').
4986 :- public 'READ_JSON_FROM_STRING'/3.
4987 :- block 'READ_JSON_FROM_STRING'(-,?,?).
4988 'READ_JSON_FROM_STRING'(string(Contents),Res,Span) :-
4989 read_json_from_string(Contents,Res,Span).
4990 :- block read_json_from_string(-,?,?).
4991 read_json_from_string(Contents,Res,Span) :-
4992 statistics(walltime,_),
4993 atom_codes(Contents,Codes),
4994 safe_call(json_parse(Codes,Json,[]),Span),
4995 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to parse string~n',[W1]),
4996 json_parser_to_json_freetype(Json,JsonFreetype),
4997 statistics(walltime,[_,W2]),
4998 formatsilent('% Walltime ~w ms to convert JSON~n',[W2]),
4999 kernel_objects:equal_object_optimized(Res,JsonFreetype).
5000
5001 external_fun_type('READ_JSON_FROM_STRING_AS_XML',[],[string,seq(XT)]) :- xml_element_type(XT).
5002 expects_spaninfo('READ_JSON_FROM_STRING_AS_XML').
5003 :- public 'READ_JSON_FROM_STRING_AS_XML'/3.
5004 :- block 'READ_JSON_FROM_STRING_AS_XML'(-,?,?).
5005 'READ_JSON_FROM_STRING_AS_XML'(string(Contents),Res,Span) :-
5006 read_json_from_string_as_xml(Contents,Res,Span).
5007 :- block read_json_from_string_as_xml(-,?,?).
5008 read_json_from_string_as_xml(Contents,Res,Span) :-
5009 atom_codes(Contents,Codes),
5010 statistics(walltime,_),
5011 safe_call(json_parse(Codes,JSONList,[position_infos(true)]),Span),
5012 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to parse string~n',[W1]),
5013 convert_json_to_b(JSONList,BDataSequence,Span),
5014 statistics(walltime,[_,W2]),
5015 formatsilent('% Walltime ~w ms to convert JSON~n',[W2]),
5016 kernel_objects:equal_object_optimized(Res,BDataSequence).
5017
5018 expects_spaninfo('WRITE_XML').
5019 external_fun_type('WRITE_XML',[],[seq(XT),string]) :- xml_element_type(XT).
5020 :- public 'WRITE_XML'/4.
5021 :- block 'WRITE_XML'(-,?,?,?),'WRITE_XML'(?,-,?,?).
5022 'WRITE_XML'(Records,string(File),Res,Span) :- write_xml2(Records,File,Res,Span).
5023 :- block write_xml2(?,-,?,?).
5024 write_xml2(Records,File,Res,Span) :-
5025 b_absolute_file_name(File,AFile,Span),
5026 statistics(walltime,_),
5027 'WRITE_XML_TO_STRING'(Records,String,Span),
5028 String = string(S),
5029 when(nonvar(S),
5030 (statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to convert XML for ~w~n',[W1,AFile]),
5031 open(AFile,write,Stream,[encoding(utf8)]),
5032 write(Stream,S),nl(Stream),
5033 close(Stream),
5034 statistics(walltime,[_,W2]), formatsilent('% Walltime ~w ms to write XML to file ~w~n',[W2,AFile]),
5035 Res = pred_true
5036 )).
5037
5038
5039 %sequence of records of type:
5040 % rec(attributes:{("version"|->"03.04")},
5041 % element:"Data",
5042 % meta:{("xmlLineNumber"|->"2")},
5043 % pId:0,
5044 % recId:1),
5045 :- use_module(probsrc(xml_prob),[xml_parse/4, xml_pp/1]).
5046 expects_spaninfo('WRITE_XML_TO_STRING').
5047 :- public 'WRITE_XML_TO_STRING'/3.
5048 :- block 'WRITE_XML_TO_STRING'(-,?,?).
5049 'WRITE_XML_TO_STRING'(Records,Res,Span) :-
5050 custom_explicit_sets:expand_custom_set_to_list(Records,ESet,Done,'WRITE_XML_TO_STRING'),
5051 ground_value_check(ESet,Gr),
5052 when((nonvar(Done),nonvar(Gr)),
5053 ( % print(expanded(ESet)),nl,
5054 gen_prolog_xml_term(ESet,Prolog,Span),
5055 %print(prolog(Prolog)),nl,
5056 xml_parse(Codes,Prolog,[],Span),
5057 (debug:debug_mode(on) -> xml_pp(Prolog) ; true),
5058 atom_codes(S,Codes),
5059 Res = string(S))).
5060
5061 :- use_module(extrasrc(json_parser),[json_write/3,json_write_file/3]).
5062 :- use_module(extrasrc(json_freetype),[json_freetype_to_json_parser/2]).
5063 expects_spaninfo('WRITE_JSON').
5064 external_fun_type('WRITE_JSON',[],[freetype('JsonValue'),string]).
5065 :- public 'WRITE_JSON'/4.
5066 :- block 'WRITE_JSON'(-,?,?,?),'WRITE_JSON'(?,-,?,?).
5067 'WRITE_JSON'(JsonFreetype,string(File),Res,Span) :-
5068 ground_value_check(JsonFreetype,GrJ),
5069 write_json(GrJ,JsonFreetype,File,Res,Span).
5070 :- block write_json(-,?,?,?,?),write_json(?,?,-,?,?).
5071 write_json(_,JsonFreetype,File,Res,Span) :-
5072 statistics(walltime,_),
5073 json_freetype_to_json_parser(JsonFreetype,Json),
5074 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to convert JSON to parser representation for ~w~n',[W1,AFile]),
5075 b_absolute_file_name(File,AFile,Span),
5076 safe_call(json_write_file(AFile,Json,[pretty(true)]),Span),
5077 statistics(walltime,[_,W2]), formatsilent('% Walltime ~w ms to write JSON for ~w~n',[W2,AFile]),
5078 Res = pred_true.
5079
5080 expects_spaninfo('WRITE_JSON_TO_STRING').
5081 external_fun_type('WRITE_JSON_TO_STRING',[],[freetype('JsonValue'),string]).
5082 :- public 'WRITE_JSON_TO_STRING'/3.
5083 'WRITE_JSON_TO_STRING'(JsonFreetype,Res,Span) :-
5084 ground_value_check(JsonFreetype,GrJ),
5085 write_json_to_string(GrJ,JsonFreetype,Res,Span).
5086 :- block write_json_to_string(-,?,?,?).
5087 write_json_to_string(_,JsonFreetype,Res,Span) :-
5088 statistics(walltime,_),
5089 json_freetype_to_json_parser(JsonFreetype,Json),
5090 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to convert JSON to parser representation~n',[W1]),
5091 safe_call(json_write(Json,Codes,[pretty(true)]),Span),
5092 atom_codes(S,Codes),
5093 statistics(walltime,[_,W2]), formatsilent('% Walltime ~w ms to write JSON to string~n',[W2]),
5094 Res = string(S).
5095
5096 gen_prolog_xml_term(List,xml( [version="1.0", encoding="ASCII"], ContentList),Span) :-
5097 InitialLineNr = 2, % first line is xml-header !?
5098 gen_prolog_xml_dcg(InitialLineNr,_,0,[],ContentList,Span,List,[]).
5099
5100 gen_prolog_xml_dcg(LastLineNr,FinalLineNr,CurLevel, Parents, ResContentList,Span) -->
5101 [(int(Index),rec(Fields))],
5102 { %print(treat(Index,Fields)),nl,
5103 get_parentId(Fields,CurLevel,Span)}, % The element should be added to the current content list
5104 !,
5105 {get_element(Fields,Element,Span),
5106 get_attributes(Fields,Attributes,Span),
5107 get_line(Fields,LineNr,Span),
5108 gen_element(LastLineNr,LineNr,Element, Attributes, InnerContentList, ResContentList, TailContentList)
5109 },
5110 gen_prolog_xml_dcg(LineNr,LineNr2,Index,[CurLevel|Parents],InnerContentList,Span),
5111 gen_prolog_xml_dcg(LineNr2,FinalLineNr,CurLevel, Parents, TailContentList,Span).
5112 gen_prolog_xml_dcg(L,L,_,_,[],_Span) --> [].
5113
5114 gen_element(LastLineNr,NewLineNr,'CText',['='(text,Codes)],[], [PCDATA|Tail],Tail) :-
5115 insert_newlines(LastLineNr,NewLineNr,Codes,NLCodes),
5116 !,
5117 PCDATA=pcdata(NLCodes).
5118 gen_element(LastLineNr,NewLineNr,Element, Attributes, InnerContentList, [pcdata(NL),XELEMENT|Tail],Tail) :-
5119 LastLineNr < NewLineNr,
5120 insert_newlines(LastLineNr,NewLineNr,[],NL),
5121 !,
5122 XELEMENT = element( Element, Attributes, InnerContentList).
5123 gen_element(_,_,Element, Attributes, InnerContentList, [XELEMENT|Tail],Tail) :-
5124 XELEMENT = element( Element, Attributes, InnerContentList).
5125
5126 insert_newlines(LastLineNr,NewLineNr,C,R) :- NewLineNr =< LastLineNr,!,R=C.
5127 % TO DO: maybe we have to use 13 on Windows ??
5128 insert_newlines(LastLineNr,NewLineNr,C,[10|Res]) :- L1 is LastLineNr+1, insert_newlines(L1,NewLineNr,C,Res).
5129
5130 get_parentId(Fields,Nr,Span) :-
5131 (member(field(pId,int(ParentID)),Fields) -> Nr=ParentID
5132 ; add_error('WRITE_XML_TO_STRING','The record has no pId field: ',Fields,Span),
5133 Nr = 0).
5134 get_element(Fields,Atom,Span) :-
5135 (member(field(element,string(Atom)),Fields) -> true
5136 ; add_error('WRITE_XML_TO_STRING','The record has no element field: ',Fields,Span),
5137 Atom = '??').
5138
5139 get_attributes(Fields,Attrs,Span) :-
5140 (member(field(attributes,Set),Fields)
5141 -> custom_explicit_sets:expand_custom_set_to_list(Set,ESet,_Done,'get_attributes'),
5142 (maplist(get_xml_attr,ESet,Attrs) -> true
5143 ; add_error('WRITE_XML_TO_STRING','Illegal attributes field: ',ESet,Span),
5144 Attrs = []
5145 )
5146 ; add_error('WRITE_XML_TO_STRING','The record has no attributes field: ',Fields,Span),
5147 Attrs = []).
5148 get_line(Fields,LineNr,Span) :-
5149 (member(field(meta,Set),Fields)
5150 -> custom_explicit_sets:expand_custom_set_to_list(Set,ESet,_Done,'get_line'),
5151 (member((string(xmlLineNumber),string(LineNrS)),ESet)
5152 -> atom_codes(LineNrS,CC), number_codes(LineNr,CC)
5153 ; add_error('WRITE_XML_TO_STRING','The meta field has no xmlLineNumber entry: ',ESet,Span),
5154 LineNr = -1
5155 )
5156 ; add_error('WRITE_XML_TO_STRING','The record has no meta field: ',Fields,Span),
5157 LineNr = -1).
5158
5159 get_xml_attr((string(Attr),string(Val)),'='(Attr,ValCodes)) :- atom_codes(Val,ValCodes).
5160
5161
5162 % ----------------------------------
5163 % A flexible CVS Reader that always uses the same type
5164 % rec([field(attributes,BAttributes),field(lineNr,LineNr)])
5165
5166 % EXTERNAL_FUNCTION_READ_CSV_STRINGS == STRING --> seq(CSV_ELement_Type);
5167 % with CSV_ELement_Type == STRING +-> STRING ;
5168
5169 performs_io('READ_CSV_STRINGS').
5170 expects_spaninfo('READ_CSV_STRINGS').
5171 external_fun_type('READ_CSV_STRINGS',[],[string,seq(set(couple(string,string)))]).
5172 :- public 'READ_CSV_STRINGS'/3.
5173 :- block 'READ_CSV_STRINGS'(-,?,?).
5174 'READ_CSV_STRINGS'(string(File),Res,Span) :- read_csv_strings(File,Res,Span).
5175
5176 read_csv_strings(File,ResAVL,Span) :-
5177 b_absolute_file_name(File,AFile,Span),
5178 open_utf8_file_for_reading(AFile,Stream,Span),
5179 statistics(walltime,_),
5180 read_line(Stream,Line1),
5181 (Line1 = end_of_file -> ResAVL = []
5182 ; split_csv_line(1,Stream,[],HeadersCodes,Span,Line1,[]),
5183 maplist(process_header,HeadersCodes,Headers),
5184 formatsilent('CSV Line Headers = ~w for ~w~n',[Headers,AFile]),
5185 safe_call(read_csv_strings_lines(Stream,1,Span,Headers,Res),Span),
5186 statistics(walltime,[_,W1]), formatsilent('% Walltime ~w ms to read in ~w~n',[W1,AFile]),
5187 kernel_objects:equal_object_optimized(Res,ResAVL),
5188 statistics(walltime,[_,W2]), formatsilent('% Walltime ~w ms to normalise in ~w~n',[W2,AFile])
5189 ),
5190 close(Stream). % TO DO: call_cleanup
5191
5192 process_header(HeaderC,HeaderAtom) :- safe_atom_codes(HeaderAtom,HeaderC).
5193
5194 read_csv_strings_lines(Stream,PrevLineNr,Span,Headers,Res) :-
5195 read_line(Stream,Line),
5196 (Line = end_of_file -> Res = []
5197 ; LineNr is PrevLineNr+1,
5198 debug_format(9,'~nCSV line ~w: ~s~n',[LineNr,Line]),
5199 split_csv_line(LineNr,Stream,[],AtomsC,Span,Line,[]),
5200 Res = [(int(PrevLineNr),Attrs)|ResT],
5201 construct_attributes(AtomsC,Headers,Attrs,Span,LineNr,1),
5202 read_csv_strings_lines(Stream,LineNr,Span,Headers,ResT)
5203 ).
5204
5205 construct_attributes([],_,[],_,_,_).
5206 construct_attributes([ [] | T],[ _|HT],Res,Span,LineNr,ColNr) :- !, % empty column
5207 C1 is ColNr+1,
5208 construct_attributes(T,HT,Res,Span,LineNr,C1).
5209 construct_attributes([ AtomC | T], [], Res,Span,LineNr,ColNr) :- !,
5210 safe_atom_codes(A,AtomC),
5211 length(AtomC,NrChars),
5212 ajoin(['Additional field with ',NrChars,' chars on line ',LineNr,' and column ',ColNr,': '],Msg),
5213 add_warning('READ_CSV_STRINGS',Msg,A,Span),
5214 Res=[(string('ExtraField'),string(A))|TR],
5215 C1 is ColNr+1,
5216 construct_attributes(T, [], TR,Span,LineNr,C1).
5217 construct_attributes([ AtomC | T], [ Header | HT],
5218 [ (string(Header),string(A)) | ResT],Span,LineNr,ColNr) :-
5219 safe_atom_codes(A,AtomC),
5220 %format('Col ~w: ~w~n',[ColNr,A]),flush_output,
5221 C1 is ColNr+1,
5222 construct_attributes(T,HT,ResT,Span,LineNr,C1).
5223
5224 % ----------------------------------
5225 % A CSV Reader that uses the B types to adapt how it reads in values
5226
5227 performs_io('READ_CSV').
5228 expects_spaninfo('READ_CSV').
5229 expects_type('READ_CSV').
5230
5231 :- public 'READ_CSV'/6.
5232 :- block 'READ_CSV'(-,?,?,?,?,?).
5233 'READ_CSV'(string(File),BoolSkipLine1,AllowExtraValues,Res,Type,Span) :-
5234 read_csv(File,BoolSkipLine1,AllowExtraValues,pred_false,Res,Type,Span).
5235
5236 external_fun_type('READ_CSV',[T],[string,T]).
5237 :- public 'READ_CSV'/4.
5238 :- block 'READ_CSV'(-,?,?,?).
5239 'READ_CSV'(string(File),Res,Type,Span) :-
5240 read_csv(File,pred_false,pred_false,pred_false,Res,Type,Span).
5241
5242 performs_io('READ_CSV_SEQUENCE').
5243 expects_spaninfo('READ_CSV_SEQUENCE').
5244 expects_type('READ_CSV_SEQUENCE').
5245 :- public 'READ_CSV_SEQUENCE'/6.
5246 :- block 'READ_CSV_SEQUENCE'(-,?,?,?,?,?).
5247 'READ_CSV_SEQUENCE'(string(File),BoolSkipLine1,AllowExtraValues,Res,Type,Span) :-
5248 read_csv(File,BoolSkipLine1,AllowExtraValues,pred_true,Res,Type,Span).
5249
5250 :- use_module(bsyntaxtree,[get_set_type/2]).
5251 :- block read_csv(-,?,?,?,?,?,?).
5252 read_csv(File,BoolSkipLine1,AllowExtraValues,CreateSequence,Res,InType,Span) :-
5253 (CreateSequence=pred_true
5254 -> (get_set_type(InType,couple(integer,T)) -> Type=set(T), SeqIndex=1
5255 ; add_error('READ_CSV_SEQUENCE','Expecting sequence as return type:',InType),
5256 Type=InType, SeqIndex=none
5257 )
5258 ; SeqIndex=none,Type=InType),
5259 get_column_types(Type,Types,Skel,Vars,Span),
5260 b_absolute_file_name(File,AFile,Span),
5261 open_utf8_file_for_reading(AFile,Stream,Span),
5262 (debug:debug_mode(off) -> true
5263 ; formatsilent('~nReading CSV file ~w with Types = ~w and Skel = ~w for Vars = ~w~n~n',[AFile,Types,Skel,Vars])),
5264 (read_csv_lines(1,SeqIndex,BoolSkipLine1,AllowExtraValues,Stream,Types,Skel,Vars,Res,Span) -> true
5265 ; add_error('READ_CSV','Reading CSV File failed: ',AFile)),
5266 close(Stream). % TO DO: call_cleanup
5267
5268 read_csv_lines(Nr,SeqIndex,BoolSkipLine1,AllowExtraValues,Stream,Types,Skel,Vars,Res,Span) :- %print(line(Nr,Types)),nl,
5269 read_line(Stream,Line),
5270 debug:debug_println(9,read_line(Nr,Line)),
5271 (Line = end_of_file -> Res = []
5272 ; split_csv_line(Nr,Stream,[],AtomsC,Span,Line,[]),
5273 %print(atoms(Nr,Atoms)),nl,
5274 %maplist(convert_atom_codes(Span),Types,Atoms,Tuple), % TO DO: check same length
5275 (Nr=1,BoolSkipLine1=pred_true
5276 -> maplist(codes_to_atom,AtomsC,Atoms), format('Skipping line 1: ~w~n',[Atoms]),
5277 Res=ResT
5278 ; Line=[] -> format('Skipping empty line ~w~n',[Nr]), Res=ResT
5279 ; l_convert_atom_codes(Types,AtomsC,Tuple,Span,Nr,AllowExtraValues),
5280 copy_term((Vars,Skel),(Tuple,BValue)),
5281 (number(SeqIndex) -> S1 is SeqIndex+1, Res = [(int(SeqIndex),BValue)|ResT]
5282 ; S1 = SeqIndex, Res = [BValue|ResT]
5283 )
5284 ),
5285 N1 is Nr+1,
5286 read_csv_lines(N1,S1,BoolSkipLine1,AllowExtraValues,Stream,Types,Skel,Vars,ResT,Span)).
5287
5288 codes_to_atom(C,A) :- atom_codes(A,C).
5289
5290 l_convert_atom_codes([],[],Vals,_Span,_LineNr,_) :- !, Vals=[].
5291 l_convert_atom_codes([Type|TT],[AtomC|TC],[Val|VT],Span,LineNr,AllowExtraValues) :- !,
5292 convert_atom_codes(Span,LineNr,Type,AtomC,Val),
5293 l_convert_atom_codes(TT,TC,VT,Span,LineNr,AllowExtraValues).
5294 l_convert_atom_codes([Type|TT],[],_,Span,LineNr,_) :- !,
5295 ajoin(['Missing value(s) on CSV line ',LineNr,' for types: '],Msg),
5296 add_error('READ_CSV',Msg,[Type|TT],Span),fail.
5297 l_convert_atom_codes([],[AtomC|AT],Vals,Span,LineNr,AllowExtraValues) :- !,
5298 (AllowExtraValues=pred_true -> true
5299 ; safe_atom_codes(Atom,AtomC),
5300 ajoin(['Extra value(s) on CSV line ',LineNr,' : ',Atom,' Rest = '],Msg),
5301 add_error('READ_CSV',Msg,AT,Span)
5302 ), Vals=[].
5303
5304 convert_atom_codes(Span,LineNr,T,AtomC,Val) :-
5305 (convert_atom2(T,AtomC,Val,Span,LineNr) -> true ;
5306 atom_codes(Atom,AtomC),
5307 ajoin(['Could not convert value to type ',T,' on CSV line ',LineNr,': '],Msg),
5308 add_error('READ_CSV',Msg,Atom,Span),
5309 Val = term('READ_CSV_ERROR')).
5310 :- use_module(tools,[safe_number_codes/2, safe_atom_codes/2]).
5311 convert_atom2(string,C,string(A),_,_) :- safe_atom_codes(A,C).
5312 convert_atom2(integer,C,int(Nr),_Span,LineNr) :-
5313 (C=[] -> (debug:debug_mode(off) -> true ; format('Translating empty string to -1 on line ~w~n',[LineNr])),
5314 % add_warning('READ_CSV','Translating empty string to -1 on line: ',LineNr,Span),
5315 Nr is -1
5316 ; safe_number_codes(Nr,C)).
5317 convert_atom2(global(G),C,FD,Span,LineNr) :- safe_atom_codes(A,C),convert_to_enum(G,A,FD,Span,LineNr).
5318 convert_atom2(boolean,C,Bool,Span,LineNr) :- safe_atom_codes(A,C),
5319 (convert_to_bool(A,Bool) -> true
5320 ; ajoin(['Could not convert value to BOOL on line ',LineNr,'; assuming FALSE: '],Msg),
5321 add_warning('READ_CSV',Msg,A,Span),
5322 Bool=pred_false).
5323 % TO DO: support set(_), seq(_)
5324
5325 convert_to_bool('0',pred_false).
5326 convert_to_bool('1',pred_true).
5327 convert_to_bool('FALSE',pred_false).
5328 convert_to_bool('TRUE',pred_true).
5329 convert_to_bool('false',pred_false).
5330 convert_to_bool('true',pred_true).
5331
5332 convert_to_enum(G,A,FD,Span,LineNr) :- string_to_enum2(A,FD,_,Span),
5333 (FD=fd(_,G) -> true ; add_error('READ_CSV','Enumerated element of incorrect type: ',A:expected(G):line(LineNr),Span)).
5334
5335 % split a CSV line into individual AtomCode lists
5336 split_csv_line(LineNr,Stream,[],T,Span) --> " ", !, split_csv_line(LineNr,Stream,[],T,Span).
5337 split_csv_line(LineNr,Stream,Acc,[AtomC|T],Span) --> sep, !,
5338 {reverse(Acc,AtomC)}, split_csv_line(LineNr,Stream,[],T,Span).
5339 split_csv_line(LineNr,Stream,[],ResultList,Span,[34|InLine],OutLine) :- % "
5340 nonmember(34,InLine), % string is not terminated,
5341 !, % CSV files do not encode newlines within strings
5342 debug_println(19,csv_string_not_terminated_on_line(LineNr)),
5343 extend_line_until_eos(Stream,NewLines),
5344 append([InLine|NewLines],ExtendedLine),
5345 split_csv_line_inside_string(LineNr,Stream,ResultList,Span,ExtendedLine,OutLine).
5346 split_csv_line(LineNr,Stream,[],ResultList,Span) --> [34], !, % "
5347 split_csv_line_inside_string(LineNr,Stream,ResultList,Span).
5348 split_csv_line(LineNr,Stream,Acc,Atoms,Span) --> [X], !, split_csv_line(LineNr,Stream,[X|Acc],Atoms,Span).
5349 split_csv_line(_,_,Acc,[AtomC],_Span) --> !, % end of line
5350 {reverse(Acc,AtomC)}.
5351
5352 split_csv_line_inside_string(LineNr,Stream,[String|T],Span) -->
5353 scan_to_end_of_string(LineNr,[],String,Span),
5354 (sep -> split_csv_line(LineNr,Stream,[],T,Span)
5355 ; [XX] -> {atom_codes(AS,String),
5356 atom_codes(XS,[XX]), ajoin(['String on line ',LineNr,' not followed by separator but by ',XS,':'],Msg),
5357 add_error('READ_CSV',Msg,string(AS),Span)},
5358 split_csv_line(LineNr,Stream,[XX],T,Span)
5359 ; {T=[]}).
5360
5361
5362 extend_line_until_eos(Stream,[[10],Line|T]) :- % insert newline symbol; maybe use 13 on Windows ??
5363 read_line(Stream,Line), % note: we do not update line number; thus error msg refer to logical CSV lines
5364 Line \= end_of_file,!,
5365 (member(34,Line) -> T=[] % end of string found
5366 ; extend_line_until_eos(Stream,T)).
5367 extend_line_until_eos(_,[]). % string not terminated in entire CSV file; error will be generated below
5368
5369 sep --> " ",!, sep.
5370 sep --> ("," ; ";" ; " ,").
5371
5372 scan_to_end_of_string(_,Acc,AtomC,_) --> [34],!, % we found end of string "
5373 {reverse(Acc,AtomC)}.
5374 scan_to_end_of_string(LineNr,Acc,String,Span) --> [X],!, scan_to_end_of_string(LineNr,[X|Acc],String,Span).
5375 scan_to_end_of_string(LineNr,Acc,AtomC,Span) -->
5376 {reverse(Acc,AtomC),atom_codes(String,AtomC),
5377 ajoin(['String not terminated on CSV line ',LineNr,':'],Msg),
5378 add_error('READ_CSV',Msg,String,Span)}.
5379
5380 % get the list of column types along with Value skeleton with variables in the places where CSV values should be inserted
5381 get_column_types(set(X),Types,Skel,Vars,_) :- !,flatten_pairs(X,Types,[]), %print(types(Types)),nl,
5382 flatten_pairs_value_skeleton(X,Skel,Vars,[]). % print(skel(Skel,Vars)),nl.
5383 get_column_types(seq(X),Types,Skel,Vars,Span) :- !,
5384 get_column_types(set(couple(integer,X)),Types,Skel,Vars,Span).
5385 get_column_types(Type,_,_,_,Span) :- add_error('READ_CSV','Invalid return type (must be relation): ',Type,Span),fail.
5386
5387 % flatten couple pairs and generate skeleton term
5388 flatten_pairs(couple(A,B)) --> !,flatten_pairs(A), flatten_pairs(B).
5389 flatten_pairs(record(Fields)) --> !, flatten_fields(Fields).
5390 flatten_pairs(X) --> [X].
5391
5392 /* note: currently record fields have to be alphabetically in the same order as in CSV file: the fields are sorted by ProB's kernel ! : TO DO: try and recover the original order of the fields */
5393 flatten_fields([]) --> [].
5394 flatten_fields([field(_Name,Type)|T]) --> [Type], % no nesting allowed; this has to be a basic type for CSV reading to work
5395 flatten_fields(T).
5396
5397 % generate a value skeleton
5398 flatten_pairs_value_skeleton(couple(A,B),(CA,CB)) --> !,
5399 flatten_pairs_value_skeleton(A,CA), flatten_pairs_value_skeleton(B,CB).
5400 flatten_pairs_value_skeleton(record(Fields),rec(SF)) --> !, flatten_field_skel(Fields,SF).
5401 flatten_pairs_value_skeleton(_X,Var) --> [Var].
5402
5403 flatten_field_skel([],[]) --> [].
5404 flatten_field_skel([field(Name,_Type)|T],[field(Name,Var)|ST]) --> [Var],
5405 flatten_field_skel(T,ST).
5406
5407
5408 % ----------------------------------
5409 % Writing a matrix to a .pgm graphics file
5410 % The header of such a file looks like:
5411 % P5
5412 % 752 864 (width height)
5413 % 255 (maximal pixel value)
5414 % after that we have bytes of grayscale values
5415 % https://en.wikipedia.org/wiki/Netpbm#File_formats
5416
5417 % TODO: try and support colors (.ppm files)
5418 % improve performance; possibly avoiding to expand avl_sets
5419
5420 :- use_module(probsrc(tools_io),[read_byte_line/2, read_byte_word/2, put_bytes/2]).
5421
5422 :- public 'READ_PGM_IMAGE_FILE'/4.
5423 external_fun_type('READ_PGM_IMAGE_FILE',[],[string,seq(seq(integer))]).
5424 expects_waitflag('READ_PGM_IMAGE_FILE').
5425 expects_spaninfo('READ_PGM_IMAGE_FILE').
5426 :- block 'READ_PGM_IMAGE_FILE'(-,?,?,?).
5427 'READ_PGM_IMAGE_FILE'(string(FileName),Matrix,Span,WF) :-
5428 when(nonvar(FileName),
5429 (statistics(walltime,[_,_]),
5430 b_absolute_file_name(FileName,AFile,Span),
5431 open(AFile,read,Stream,[type(binary)]),
5432 call_cleanup(read_pgm_file(Stream,MatrixList,Span,WF), close(Stream)),
5433 statistics(walltime,[_,W2]),
5434 formatsilent('% Walltime ~w ms to read matrix from PGM file ~w~n',[W2,AFile]),
5435 kernel_objects:equal_object_optimized(Matrix,MatrixList)
5436 )).
5437
5438 read_pgm_file(Stream,Matrix,Span,_WF) :-
5439 read_byte_line(Stream,FileType),
5440 (FileType = "P5"
5441 -> read_byte_number(Stream,Width,Span),
5442 read_byte_number(Stream,Height,Span),
5443 read_byte_number(Stream,MaxPix,Span),
5444 formatsilent('% Detected PGM file width=~w, height=~w, max=~w~n',[Width,Height,MaxPix]),
5445 read_pgm_matrix(1,Height,Width,MaxPix,Stream,Matrix,Span)
5446 ; atom_codes(FT,FileType),
5447 add_error('READ_PGM_IMAGE_FILE','Can only support P5 grayscale type:',FT,Span),fail
5448 ).
5449
5450 % read pgm bytes and covert to B sequence of sequence of numbers
5451 read_pgm_matrix(Nr,Height,_,_,Stream,Res,Span) :- Nr > Height, !,
5452 get_byte(Stream,Code),
5453 (Code = -1 -> true
5454 ; add_warning('READ_PGM_IMAGE_FILE','Bytes ignored after reading rows=',Height,Span)),
5455 Res=[].
5456 read_pgm_matrix(RowNr,Height,Width,MaxPix,Stream,[(int(RowNr),Row1)|ResT],Span) :-
5457 read_pgm_row(1,Width,MaxPix,Stream,Row1,Span),
5458 N1 is RowNr+1,
5459 read_pgm_matrix(N1,Height,Width,MaxPix,Stream,ResT,Span).
5460
5461 read_pgm_row(Nr,Width,_,_Stream,Res,_Span) :- Nr>Width, !, Res=[].
5462 read_pgm_row(ColNr,Width,MaxPix,Stream,[(int(ColNr),int(Code))|ResT],Span) :-
5463 (get_byte(Stream,Code), Code >= 0
5464 -> (Code =< MaxPix -> true
5465 ; add_warning('READ_PGM_IMAGE_FILE','Grayscale pixel value exceeds maximum: ',Code,Span)
5466 )
5467 ; add_error('READ_PGM_IMAGE_FILE','Unexpected EOF at column:',ColNr),
5468 fail
5469 ),
5470 N1 is ColNr+1,
5471 read_pgm_row(N1,Width,MaxPix,Stream,ResT,Span).
5472
5473
5474 % read a word (until ws or eof) and convert it to a number
5475 read_byte_number(Stream,Nr,Span) :- read_byte_word(Stream,Codes),
5476 (safe_number_codes(Nr,Codes) -> true
5477 ; add_error('READ_PGM_IMAGE_FILE','Expected number:',Codes,Span)
5478 ).
5479
5480 :- public 'WRITE_PGM_IMAGE_FILE'/5.
5481 external_fun_type('WRITE_PGM_IMAGE_FILE',[],[string,seq(seq(integer),boolean)]).
5482 expects_waitflag('WRITE_PGM_IMAGE_FILE').
5483 expects_spaninfo('WRITE_PGM_IMAGE_FILE').
5484 :- block 'WRITE_PGM_IMAGE_FILE'(-,?,?,?,?), 'WRITE_PGM_IMAGE_FILE'(?,-,?,?,?).
5485 'WRITE_PGM_IMAGE_FILE'(string(FileName),Matrix,Res,Span,WF) :-
5486 custom_explicit_sets:expand_custom_set_to_list(Matrix,ESet,Done,'WRITE_PGM_IMAGE_FILE'),
5487 ground_value_check(ESet,Gr),
5488 when((nonvar(FileName),nonvar(Done),nonvar(Gr)),
5489 (statistics(walltime,[_,_]),
5490 b_absolute_file_name(FileName,AFile,Span),
5491 open(AFile,write,Stream,[type(binary)]),
5492 call_cleanup(put_pgm_file(Stream,ESet,Width,Height,WF),
5493 close(Stream)),
5494 statistics(walltime,[_,W2]),
5495 formatsilent('% Walltime ~w ms to write matrix to PGM file (width=~w, height=~w) ~w~n',[W2,Width,Height,AFile]),
5496 Res = pred_true
5497 )).
5498
5499 put_pgm_file(Stream,ESet,Width,Height,WF) :-
5500 ESet = [(int(_),Row)|_],
5501 bsets_clp:size_of_sequence(Row,int(Width),WF),
5502 put_bytes(Stream,"P5\n"),
5503 number_codes(Width,WC), put_bytes(Stream,WC),
5504 put_bytes(Stream," "),
5505 bsets_clp:size_of_sequence(ESet,int(Height),WF),
5506 number_codes(Height,HC), put_bytes(Stream,HC),
5507 put_bytes(Stream,"\n"),
5508 put_bytes(Stream,"255\n"),
5509 sort(ESet,SESet),
5510 put_pgm_matrix(Stream,Width,SESet).
5511
5512 % put a pgm grayscale matrix as bytes into a stream
5513 put_pgm_matrix(_,_,[]).
5514 put_pgm_matrix(Stream,Width,[(int(_),RowVector)|T]) :-
5515 custom_explicit_sets:expand_custom_set_to_list(RowVector,ESet,_,'WRITE_PGM_IMAGE_FILE'),
5516 sort(ESet,SESet),
5517 put_pgm_row(Stream,Width,SESet),
5518 put_pgm_matrix(Stream,Width,T).
5519
5520 put_zeros(_,X) :- X<1, !.
5521 put_zeros(Stream,X) :- put_byte(Stream,0), X1 is X-1, put_zeros(Stream,X1).
5522
5523 put_pgm_row(Stream,W,[]) :-
5524 (W=0 -> true
5525 ; add_error('WRITE_PGM_IMAGE_FILE','Illegal PGM width in row: ',W),
5526 put_zeros(Stream,W)
5527 ).
5528 put_pgm_row(Stream,W,[(_,int(Pixel))|T]) :-
5529 W1 is W-1,
5530 ( W<1 -> add_error('WRITE_PGM_IMAGE_FILE','Additional PGM pixel in row: ',Pixel)
5531 ; Pixel >=0, Pixel =< 255
5532 -> put_byte(Stream,Pixel),
5533 put_pgm_row(Stream,W1,T)
5534 ; add_error('WRITE_PGM_IMAGE_FILE','Illegal PGM pixel (must be 0..255): ',Pixel),
5535 put_byte(Stream,0),
5536 put_pgm_row(Stream,W1,T)
5537 ).
5538
5539 % -----------------
5540
5541 :- use_module(extrasrc(mcts_game_play), [mcts_auto_play/4, mcts_auto_play_available/0]).
5542 external_subst_enabling_condition('MCTS_AUTO_PLAY',_,Truth) :- create_texpr(truth,pred,[],Truth).
5543 external_function_requires_state('MCTS_AUTO_PLAY').
5544 :- public 'MCTS_AUTO_PLAY'/3.
5545 :- block 'MCTS_AUTO_PLAY'(-,?,?).
5546 'MCTS_AUTO_PLAY'(_,_Env,OutEnvModifications) :- % TO DO: pass simulation runs and time_out as parameter
5547 mcts_auto_play_available,!,
5548 get_current_state_id(CurID),
5549 mcts_auto_play(CurID,_ActionAsTerm,_TransID,State2),
5550 state_space:get_variables_state_for_id(State2,OutEnvModifications).
5551 'MCTS_AUTO_PLAY'(_,_,[]).
5552
5553 % EXTERNAL_SUBSTITUTION_MCTS_AUTO_PLAY == BOOL; MCTS_AUTO_PLAY(x) == skip;
5554
5555 % -----------------
5556
5557 :- use_module(extension('zmq_rpc/zmq_rpc'),
5558 [zmq_rpc_init/2, stream_socket_rpc_init/2,
5559 zmq_rpc_destroy/1, zmq_rpc_send/4,
5560 stream_socket_rpc_accept_request/3, stream_socket_rpc_send_answer/3]).
5561
5562 % connect to a JSON-RPC ZMQ socket
5563 performs_io('ZMQ_RPC_INIT').
5564 external_fun_type('ZMQ_RPC_INIT',[],[string,integer]).
5565 :- public 'ZMQ_RPC_INIT'/2.
5566 :- block 'ZMQ_RPC_INIT'(-,?).
5567 'ZMQ_RPC_INIT'(string(Endpoint), Res) :-
5568 when(nonvar(Endpoint), zmq_rpc_init(Endpoint, Res)).
5569
5570 % connect to a JSON-RPC regular socket using ndjson single-line messages
5571 performs_io('SOCKET_RPC_INIT').
5572 external_fun_type('SOCKET_RPC_INIT',[],[integer,integer]).
5573 :- public 'SOCKET_RPC_INIT'/2.
5574 :- block 'SOCKET_RPC_INIT'(-,?).
5575 'SOCKET_RPC_INIT'(int(Port), Res) :-
5576 when(nonvar(Port), stream_socket_rpc_init(Port, Res)).
5577
5578 performs_io('ZMQ_RPC_DESTROY').
5579 external_fun_type('ZMQ_RPC_DESTROY',[],[integer]).
5580 :- public 'ZMQ_RPC_DESTROY'/3.
5581 :- block 'ZMQ_RPC_DESTROY'(-,?,?).
5582 'ZMQ_RPC_DESTROY'(int(Socket), _EnvIn, EnvOut) :-
5583 when(nonvar(Socket),zmq_rpc_destroy(Socket)),
5584 EnvOut = [].
5585
5586 performs_io('ZMQ_RPC_SEND').
5587 expects_waitflag('ZMQ_RPC_SEND').
5588 external_fun_type('ZMQ_RPC_SEND',[],[integer,string,set(couple(string,freetype('JsonValue'))),freetype('RpcResult')]).
5589 :- public 'ZMQ_RPC_SEND'/5.
5590 :- block 'ZMQ_RPC_SEND'(-,?,?,?,?), 'ZMQ_RPC_SEND'(?,-,?,?,?), 'ZMQ_RPC_SEND'(?,?,-,?,?).
5591 'ZMQ_RPC_SEND'(int(Socket), string(Name), Args, Res,WF) :-
5592 expand_custom_set_to_list_wf(Args, ExpArgs, _Done, 'ZMQ_RPC_SEND',WF),
5593 ground_value_check(ExpArgs,Ground),
5594 block_zmq_rpc_send(Socket, Name, Ground, ExpArgs, Res).
5595
5596 :- block block_zmq_rpc_send(-,?,?,?,?), block_zmq_rpc_send(?,-,?,?,?),
5597 block_zmq_rpc_send(?,?,-,?,?).
5598 block_zmq_rpc_send(Socket, Name, _, ExpArgs, Res) :-
5599 zmq_rpc_send(Socket, Name, ExpArgs, Res).
5600
5601 performs_io('SOCKET_RPC_ACCEPT').
5602 external_fun_type('SOCKET_RPC_ACCEPT',[],[integer,freetype('JsonValue')]).
5603 :- public 'SOCKET_RPC_ACCEPT'/2.
5604 :- block 'SOCKET_RPC_ACCEPT'(-,?).
5605 'SOCKET_RPC_ACCEPT'(int(Port), Request) :-
5606 when(nonvar(Port),
5607 (stream_socket_rpc_accept_request(Port,_Id,FreeVal), % the Id is stored in zmq_rpc
5608 kernel_objects:equal_object_optimized(Request,FreeVal))).
5609
5610
5611 performs_io('SOCKET_RPC_REPLY').
5612 external_fun_type('SOCKET_RPC_REPLY',[],[integer,freetype('JsonValue')]).
5613 :- public 'SOCKET_RPC_REPLY'/3.
5614 :- block 'SOCKET_RPC_REPLY'(-,?,?),'SOCKET_RPC_REPLY'(?,-,?).
5615 'SOCKET_RPC_REPLY'(int(Port), FreeVal,Res) :-
5616 ground_value_check(FreeVal,Gr),
5617 when((nonvar(Port),nonvar(Gr)),
5618 (stream_socket_rpc_send_answer(Port,_Id,FreeVal), Res=pred_true)).