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