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