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