1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5
6 :- module(tools, [exact_member/2,
7 exact_member_lookup/4, exact_member_replace/5,
8 remove/3, remove_all/3, insert/3,
9 remove_variables/3,
10 list_intersection/3, list_difference/3,
11 disjoint_list_union/3, lists_are_disjoint/2,
12 string_concatenate/3, is_upper_case_name/1,
13 %write_to_file/2, write_to_utf8_file/2, put_codes/2, % now in tools_files
14 %print_error/1,
15 print_message/1, print_message_with_max_depth/2,
16 print_short_msg/1,
17 print_bt_message/1, print_bt_trace_message/1, bt_trace/1,
18 format_bt/2,
19 print_wtime/1,
20 print_mb/1, print_gb/1,
21 prints/1,
22 is_absolute_path/1,
23 split_common_path/4,
24 gen_relative_path/3, gen_relative_path_to_cur_dir/2,
25 get_parent_directory/2, get_parent_directory_name/2,
26 get_parent_directory_of_directory/2,
27 get_tail_filename/2, get_modulename_filename/2,
28 get_filename_extension/2,
29 get_option_from_list/4, get_options_from_list/2,
30 get_options/4,get_options/5,
31 arg_is_number/2, arg_is_number_or_wildcard/2,
32 check_filename_arg/2,
33 arg_is_integer/2,
34 split_filename/3,
35 safe_absolute_file_name/2, safe_absolute_file_name/3,
36 host_file_name_case_insensitive/0,
37 same_file_name/2,
38
39 filter/4,
40 flatten/2,
41 % count_occurences/2, % now in tools_lists
42 split_last/4,
43 split_atom/3, split_chars/3, split_complex_sep/3,
44 split_atom_at_separator/4,
45 latex_escape_atom/2,
46 b_escape_string_atom/2, b_string_escape_codes/2,
47 string_escape/2, print_escaped/1, % can also be used for dot
48 simple_dot_string_escape/2, % for dot, just quoting "
49 xml_escape/2, xml_escape_codes/2,
50 html_escape/2, html_escape_codes/2,
51 xml_attribute_escape/2,
52 read_term_from_file/2,
53 safe_read_term_from_atom/2, safe_read_term_from_codes/2,
54 read_string_from_file/2, read_string_from_file/3,
55 safe_read_string_from_file/3,
56 read_atom_from_file/3,
57 % write_lines_to_file/2, % now in tools_files
58 open_temp_file/3,
59 open_temp_file/4,
60 detect_xml_encoding/3,
61
62 ajoin/2,
63 ajoin_with_limit/3,
64 ajoin_with_sep/3,
65 substitute/4,
66 % call_residue/2, % now in tools_meta
67
68 catch_call/1,
69 observe_user_interrupt_signal/3,
70 %safe_on_exception/3, safe_on_exception_silent/3, % now in tools_meta
71 %reraise_important_exception/1, % now in tools_meta
72 % catch_matching/3, % now in tools_meta
73
74 convert_list_into_pairs/2, convert_pairs_into_list/3,
75
76 safe_univ/2, safe_univ_no_cutoff/2,
77 safe_sort/3,
78 safe_set_sort/3,
79 safe_functor/4,
80
81 safe_atom_codes/2, safe_atom_chars/3,
82 atom_codes_with_limit/2, atom_codes_with_limit/3,
83 truncate_atom/3, wrap_and_truncate_atom/4,
84 safe_number_codes/2,
85 atom_or_number_codes/2,
86 ensure_atom/2,
87 number_suffix/3,
88
89 print_size_of_table/1,
90 print_runtime/0, start_ms_timer/1, stop_ms_timer/2, stop_ms_timer/1,
91 stop_ms_timer_with_msg/2,
92 stop_ms_timer_with_silent_msg/2,
93 stop_ms_timer_with_debug_msg/2,
94 stop_ms_walltimer_with_msg/2,
95 bt_start_ms_timer/1, bt_stop_ms_timer/1,
96 get_elapsed_walltime/2,
97 get_elapsed_timer/2, combiner_timer/3,
98 get_elapsed_runtime/2,
99 cputime/1, walltime/1,
100 convert_ms_time_to_string/2,
101
102 retract_with_statistics/2,
103 statistics_memory_used/1,
104 get_memory_used/1, print_memory_used_difference/2, print_memory_used/1,
105 print_memory_used_wo_gc/0, print_memory_used_wo_gc/1,
106
107 split_list/4,
108 split_list_idx/5, re_split_list_idx/4,
109
110 minimize_lasso/4,
111
112 map_split_list/4,
113 foldl/4,foldl/5,foldl/6,
114 maplist5/5,
115 average/2,
116
117 map_optlist/2,
118 optlist_to_list/2,
119
120 (space_call)/1,
121 assert_once/1,
122
123 % safe_time_out/3, % now in tools_meta
124 % time_out_call/2, time_out_call/1, time_out_with_factor_call/3, % now in tools_timeout
125
126 unique_id/2,
127
128 get_PROBPATH/1,
129 atom_to_number/2,
130 get_set_optional_prolog_flag/3,
131
132 bb_safe_get/2,
133 bb_inc/1, bb_inc_by/2,
134
135 top_sort/3
136 ]).
137
138 :- meta_predicate foldl(3,?,?,?).
139 :- meta_predicate foldl2(?,3,?,?).
140 :- meta_predicate foldl(4,?,?,?,?).
141 :- meta_predicate foldl2(?,4,?,?,?).
142 :- meta_predicate foldl(5,?,?,?,?,?).
143 :- meta_predicate foldl2(?,5,?,?,?,?).
144 :- meta_predicate maplist5(4,-,-,-,-).
145 :- meta_predicate catch_call(0).
146 :- meta_predicate assert_once(0).
147 :- meta_predicate split_list_idx(1,?,?,?,?).
148 :- meta_predicate split_list_idx2(?,1,?,?,?).
149 :- meta_predicate map_split_list(2,?,?,?).
150 :- meta_predicate map_split_list2(?,2,?,?).
151 :- meta_predicate split_list(1,?,?,?).
152 :- meta_predicate split_list2(?,1,?,?).
153 :- meta_predicate observe_user_interrupt_signal(-,-,0).
154 :- meta_predicate filter(1,*,*,*).
155 :- meta_predicate get_options(+,4,-,-).
156 :- meta_predicate get_options(+,4,-,-,0).
157 :- meta_predicate retract_all_count(0,-,-).
158 :- meta_predicate space_call(0).
159 :- meta_predicate map_optlist(1,-).
160 :- meta_predicate map_optlist_aux(-,1).
161 :- meta_predicate call_optional(1,-).
162 :- meta_predicate call_optional_aux(-,1,-).
163
164 :- meta_predicate get_calls_for_table(:,-).
165 :- meta_predicate print_size_of_table(:).
166
167 :- meta_predicate string_escape(2,-,-).
168
169 :- meta_predicate bb_safe_get(0,-).
170 :- meta_predicate bb_inc(0).
171 :- meta_predicate bb_inc_by(0,-).
172
173 :- use_module(module_information).
174
175 :- module_info(group,infrastructure).
176 :- module_info(description,'This module contains many general helper predicates.').
177
178 :- use_module(pathes,[runtime_application_path/1]). % we just import it to set-up pathes, we don't need any predicates
179
180 :- use_module(library(lists)).
181 :- use_module(library(system)).
182 %%:- use_module(library(file_systems)). %% not required ?
183 %% :- use_module(library(codesio)).
184
185
186 :- use_module(tools_meta,[reraise_important_exception/1, safe_on_exception/3]).
187
188 :- set_prolog_flag(double_quotes, codes).
189
190
191 catch_call(Call) :-
192 catch(call(Call), Exception, (
193 add_error(catch_call,'Call raised an exception: ',(Call:Exception)),
194 /* read(_), */
195 reraise_important_exception(Exception),
196 fail
197 )).
198
199 :- use_module(error_manager,[add_warning/4]).
200 % catch CTRL-C and print a message if it happens and re-throw the interrupt
201 observe_user_interrupt_signal(Context,Span,Call) :-
202 catch(Call, user_interrupt_signal, (
203 add_warning(user_interrupt_signal,'CTRL-C occurred in context: ',Context,Span),
204 %(pending_abort_error(WF,Msg,_ErrTerm,Span)
205 % % Unfortunately any abort errors induced by Call itself are already removed by the exception
206 % -> add_message(user,'Pending WD-Error could cause long runtimes: ',Msg,Span) ; true),
207 throw(user_interrupt_signal)
208 )).
209
210
211
212 :- use_module(self_check). % put after search paths have been set
213
214 % These predicates from tools_platform are tested here to avoid module load order issues.
215
216 :- use_module(tools_platform, [map_host_platform/2, map_host_processor/2, host_platform/1]).
217 :- assert_must_succeed(map_host_platform("x86-win32-nt-4",windows)).
218 :- assert_must_succeed(map_host_platform("x86_64-win32-nt-4",windows)).
219 :- assert_must_succeed(map_host_platform("x86_64-darwin-10.6.0",darwin)).
220 :- assert_must_succeed(map_host_platform("x86_64-darwin-18.7.0",darwin)).
221 :- assert_must_succeed(map_host_platform("arm64-darwin-20.1.0",darwin)).
222 :- assert_must_succeed(map_host_platform("x86-linux-glibc2.7",linux)).
223 :- assert_must_succeed(map_host_platform("x86_64-linux-glibc2.17",linux)).
224 :- assert_must_succeed(map_host_platform("aarch64-linux-glibc2.28",linux)).
225 :- assert_must_succeed(map_host_platform("nonsense-potatos-4.2",unknown)).
226 % On SWI, the arch/host_type flag doesn't include an OS version number.
227 :- assert_must_succeed(map_host_platform("i386-win32",windows)).
228 :- assert_must_succeed(map_host_platform("x64-win64",windows)).
229 :- assert_must_succeed(map_host_platform("x86_64-darwin",darwin)).
230 :- assert_must_succeed(map_host_platform("arm64-darwin",darwin)).
231 :- assert_must_succeed(map_host_platform("aarch64-linux",linux)).
232 :- assert_must_succeed(map_host_platform("nonsense-potatos",unknown)).
233
234 :- assert_must_succeed((host_platform(Platform), Platform \= unknown)).
235
236
237 :- assert_must_succeed(map_host_processor("x86-win32-nt-4",x86)).
238 :- assert_must_succeed(map_host_processor("x86_64-win32-nt-4",x86_64)).
239 :- assert_must_succeed(map_host_processor("x86_64-darwin-10.6.0",x86_64)).
240 :- assert_must_succeed(map_host_processor("x86_64-darwin-18.7.0",x86_64)).
241 :- assert_must_succeed(map_host_processor("arm64-darwin-20.1.0",aarch64)).
242 :- assert_must_succeed(map_host_processor("x86-linux-glibc2.7",x86)).
243 :- assert_must_succeed(map_host_processor("x86_64-linux-glibc2.17",x86_64)).
244 :- assert_must_succeed(map_host_processor("aarch64-linux-glibc2.28",aarch64)).
245 :- assert_must_succeed(map_host_processor("nonsense-potatos-4.2",unknown)).
246 % On SWI, the arch/host_type flag doesn't include an OS version number.
247 :- assert_must_succeed(map_host_processor("i386-win32",x86)).
248 :- assert_must_succeed(map_host_processor("x64-win64",x86_64)).
249 :- assert_must_succeed(map_host_processor("x86_64-darwin",x86_64)).
250 :- assert_must_succeed(map_host_processor("arm64-darwin",aarch64)).
251 :- assert_must_succeed(map_host_processor("aarch64-linux",aarch64)).
252 :- assert_must_succeed(map_host_processor("nonsense-potatos",unknown)).
253
254 % --------------------------------------
255
256 cputime(T) :-
257 statistics(runtime,[T,_]).
258
259 walltime(WT) :-
260 statistics(walltime,[WT,_]).
261 % --------------------------------------
262
263
264 :- use_module(error_manager,[add_error/3, add_internal_error/2]).
265 print_message(Msg) :- print_message_with_max_depth(Msg,20).
266 print_message_with_max_depth(Msg,MaxDepth) :-
267 safe_on_exception(E,print_message2(Msg,MaxDepth),
268 add_error(tools,'Exception in print_message: ',E)). % added because sometimes in Windows/Vista we get an exception here
269 print_message2(Msg,MaxDepth) :-
270 (var(Msg) -> print_message(informational,'_')
271 ; write(user_output,'% '),write_term(user_output,Msg,[max_depth(MaxDepth)]),nl(user_output) ).
272 print_short_msg(Msg) :-
273 write(user_output,Msg).
274
275 format_bt(Msg,P) :- format(Msg,P).
276 format_bt(Msg,P) :- print(' * BACKTRACK: '),format(Msg,P),
277 fail.
278
279 print_bt_message(Msg) :- print_message(Msg).
280 print_bt_message(Msg) :- print_message(backtrack(Msg)),
281 %(Msg = found_enumeration_of_constants(_,_) -> trace ; true),
282 fail.
283
284 % like print_bt_message but trace upon backtrack
285 print_bt_trace_message(Msg) :- print_message(Msg).
286 print_bt_trace_message(Msg) :- trace,
287 print_message(backtrack(Msg)),
288 fail.
289
290 % trace upon backtrack:
291 bt_trace(_) :- true.
292 bt_trace(PP) :- print(' * BACKTRACK: '), print(PP),nl, trace,fail.
293
294 print_wtime(PP) :- statistics(walltime,[WT,_]),
295 format('~w : ~w ms ~n', [PP,WT]).
296
297 % a print that will automatically stop after 25 prints and give the user the option to inspect the printed messages
298 :- dynamic prints_count/1.
299 prints_count(25).
300 prints(L) :- print_bt_message(L),
301 (retract(prints_count(X)) -> true ; X=25),
302 (X<1
303 -> print('*** Stopped printing >'),
304 read(RT),
305 (number(RT) -> X1=RT ; X1=25)
306 ; X1 is X-1
307 ), assertz(prints_count(X1)).
308
309 :- assert_pre(tools:exact_member(_Var,Vs),
310 (list_skeleton(Vs))).
311 :- assert_post(tools:exact_member(_Var,_Vs), true).
312 :- assert_must_succeed(tools:exact_member(V,[V])).
313 :- assert_must_succeed(tools:exact_member(V,[_X,_Z,V])).
314 :- assert_must_fail(tools:exact_member(_W,[_X,_Z,_V])).
315 :- assert_must_fail(tools:exact_member(_W,[])).
316
317 exact_member(X,[Y|T]) :-
318 (X==Y -> true ; exact_member(X,T)).
319
320
321 :- assert_pre(tools:exact_member_lookup(_Var,_ValRes,Vs,Vals),
322 (list_skeleton(Vs),list_skeleton(Vals))).
323 :- assert_post(tools:exact_member_lookup(_Var,_ValRes,_Vs,_Vals), true).
324 :- assert_must_succeed(tools:exact_member_lookup(V,2,[V],[2])).
325 :- assert_must_succeed(tools:exact_member_lookup(V,2,[_X,_Z,V],[1,3,2])).
326 :- assert_must_fail(tools:exact_member_lookup(V,3,[_X,_Z,V],[1,3,2])).
327 :- assert_must_fail(tools:exact_member_lookup(_W,3,[_X,_Z,_V],[1,3,2])).
328 :- assert_must_fail(tools:exact_member_lookup(_W,3,[],[1,3,2])).
329
330 exact_member_lookup(Var,ValRes,[V|TV],[Val|TVal]) :-
331 (Var==V -> ValRes=Val ; exact_member_lookup(Var,ValRes,TV,TVal)).
332
333
334 :- assert_pre(tools:exact_member_replace(_Var,_ValRes,Vs,Vals,_),
335 (list_skeleton(Vs),list_skeleton(Vals))).
336 :- assert_post(tools:exact_member_replace(_Var,_ValRes,_Vs,_Vals,NewVals),
337 list_skeleton(NewVals)).
338 :- assert_must_succeed(tools:exact_member_replace(V,44,[_X,_Z,V],[1,3,2],[1,3,44])).
339 :- assert_must_fail(tools:exact_member_replace(_V,44,[_X,_Z,_VV],[1,3,2],[1,3,44])).
340
341 exact_member_replace(Var,NewVal,[V|TV],[Val|TVal],[NV|TN]) :-
342 ((Var==V) -> (NV=NewVal,TN=TVal)
343 ; (NV=Val,exact_member_replace(Var,NewVal,TV,TVal,TN))).
344
345
346
347 remove([X|T],X,T).
348 ?remove([Y|T],X,[Y|DT]) :- \+(X=Y), remove(T,X,DT).
349
350 :- assert_must_succeed(tools:flatten([],[])).
351 :- assert_must_succeed(tools:flatten([[1,2,3]],[1,2,3])).
352 :- assert_must_succeed(tools:flatten([[1],[[99]],[2,3],[4,5]],[1,99,2,3,4,5])).
353 :- assert_must_succeed(tools:flatten([[]],[])).
354
355 flatten(List,FlatList) :- flatten1(List,[],FlatList).
356 flatten1([],L,L) :- !.
357 flatten1([H|T],Tail,List) :- !, flatten1(H,FlatList,List), flatten1(T,Tail,FlatList).
358 flatten1(NonList,Tail,[NonList|Tail]).
359
360
361 :- use_module(tools_lists,[count_occurences/2]).
362 :- assert_must_succeed((tools_lists:count_occurences([a,b,a,a,b],R),R == [a-3,b-2])).
363 :- assert_must_succeed((tools_lists:count_occurences([a],R),R == [a-1])).
364 :- assert_must_succeed((tools_lists:count_occurences([],R),R == [])).
365 :- assert_must_succeed((tools_lists:count_occurences([a,b],R),R == [a-1,b-1])).
366
367
368
369 :- assert_must_succeed((tools:filter(var,[1,2,X,3,Y],R,Out),R == [X,Y],Out == [1,2,3])).
370 :- assert_must_succeed((tools:filter(nonvar,[1,2,X,3,Y],R,Out),R == [1,2,3],Out == [X,Y])).
371
372 filter(_Pred,[],[],[]).
373 filter(Pred,[H|T],True,False) :-
374 ? (call(Pred,H) -> True = [H|TT], filter(Pred,T,TT,False)
375 ? ; False = [H|FF], filter(Pred,T,True,FF)).
376
377 :- public is_a_comment/3. % used for testing filter
378 :- assert_must_succeed((tools: filter(tools:is_a_comment('/*','*/'),['This comment ','/* comment */','will be ignored!'],R,Out),
379 R==['/* comment */'],Out==['This comment ','will be ignored!'])).
380 % checking whether an atom is a comment /* ... */
381 is_a_comment(Begin,End,Comment) :-
382 maplist(atom_codes,[Begin,End,Comment],[BL,EL,CL]),
383 ? prefix(CL,BL),suffix(CL,EL).
384
385 :- assert_must_succeed((tools:remove_variables([X,Y,Z],[Y],R),R==[X,Z])).
386 remove_variables(List,Vars,Remaining) :-
387 exclude(exact_member_rev(Vars),List,Remaining).
388 % a version of exact member with reversed parameters - usefull with
389 % higher-order functions
390 exact_member_rev(List,Member) :- exact_member(Member,List).
391
392 :- assert_must_succeed(tools:insert([],a,[a])).
393 :- assert_must_succeed(tools:insert([a,b,c,d],a,[a,b,c,d])).
394 :- assert_must_succeed(tools:insert([a,b,c,d],b,[a,b,c,d])).
395 :- assert_must_succeed(tools:insert([a,b,c,d],d,[a,b,c,d])).
396 :- assert_must_succeed(tools:insert([a,b,c,d],x,[a,b,c,d,x])).
397 insert([],X,[X]).
398 insert([H|T],X,R) :- (H=X -> R=[H|T] ; R=[H|R2],insert(T,X,R2)).
399
400
401 :- assert_must_succeed(tools:list_intersection([a,b,c,d],[d,f,b],[b,d])).
402
403 list_intersection([],_L,[]).
404 list_intersection([H|T],L,Res) :-
405 ? (remove(L,H,NL) -> (Res=[H|RR]) ; (Res=RR,NL=L)),
406 list_intersection(T,NL,RR).
407
408 insert_new([],X,[X]).
409 insert_new([H|T],X,R) :- (H=X -> fail ; R=[H|R2],insert_new(T,X,R2)).
410
411 :- assert_must_succeed(tools:disjoint_list_union([a,b,c,d],[e,f,g],[e,f,g,a,b,c,d])).
412 :- assert_must_fail(tools:disjoint_list_union([a,b,c,d],[d,f,b],_)).
413 :- assert_must_fail(tools:disjoint_list_union([a,b,c,d],[d,f,b],[d,f,b,a,c])).
414 disjoint_list_union([],L,L).
415 disjoint_list_union([H|T],L,Res) :- insert_new(L,H,L2), disjoint_list_union(T,L2,Res).
416
417 :- assert_must_succeed(tools:lists_are_disjoint([a,b,c,d],[e,f,g])).
418 :- assert_must_succeed(tools:lists_are_disjoint([a,b,c,d],[])).
419 :- assert_must_succeed(tools:lists_are_disjoint([],[e,f,g])).
420 :- assert_must_fail(tools:lists_are_disjoint([a,b,c,d],[e,f,g,d])).
421 lists_are_disjoint([],_).
422 lists_are_disjoint([H|T],List2) :- \+ member(H,List2), lists_are_disjoint(T,List2).
423
424 :- assert_must_succeed(tools:list_difference([a,b,c,d],[b,f,d],[a,c])).
425
426 list_difference([],_L,[]).
427 list_difference([H|T],L,Res) :-
428 ? (remove(L,H,NL) -> (Res=RR) ; (Res=[H|RR],NL=L)),
429 list_difference(T,NL,RR).
430
431 :- use_module(tools_strings,[string_concatenate/3]).
432 :- assert_must_succeed(( tools_strings:string_concatenate('5','.10',R), R=='5.10' )).
433
434
435
436
437 :- assert_must_succeed(tools:is_upper_case_name('GOODS')).
438 :- assert_must_succeed(tools:is_upper_case_name('ZZAA')).
439 :- assert_must_fail(tools:is_upper_case_name('capacity')).
440 :- assert_must_fail(tools:is_upper_case_name('PARAs')).
441
442 :- use_module(tools_strings,[safe_name/2]).
443 is_upper_case_name(Name) :-
444 safe_name(Name,AsciiList),
445 upper_case_list(AsciiList).
446
447 upper_case_list([]).
448 upper_case_list([H|T]) :- 0'A =< H, H =< 0'Z, upper_case_list(T).
449
450
451 :- assert_must_succeed(tools:split_common_path('/aaaa/bbb/cc/d.app','/aaaa/bbb/cc/','/aaaa/bbb/cc','d.app')).
452 :- assert_must_succeed(tools:split_common_path('/aaaa/bbb/cc/d.app','/aaaa/bbb/cc/e','/aaaa/bbb/cc','d.app')).
453 :- assert_must_succeed(tools:split_common_path('/aaaa/bbb/cc/d.app','/aaaa/bbb/ce/e','/aaaa/bbb','cc/d.app')).
454 :- assert_must_succeed(tools:split_common_path('/aaaa/bbb/cc/d.app','/aaaa/e','/aaaa','bbb/cc/d.app')).
455 split_common_path(Path1,Path2,CommonPrefix,Suffix1) :-
456 split_atom_with_empty(Path1,['/','\\'],PC1),
457 split_atom_with_empty(Path2,['/','\\'],PC2),
458 split_com_aux(PC1,PC2,Com,Suff),
459 ajoin_with_sep(Com,'/',CommonPrefix),
460 ajoin_with_sep(Suff,'/',Suffix1).
461
462 split_com_aux([],_,[],Suffix) :- !, Suffix=[].
463 split_com_aux([H|T1],[H|T2],[H|CT],Suffix) :- !,
464 split_com_aux(T1,T2,CT,Suffix).
465 split_com_aux(P1,_,[],P1).
466
467
468 :- assert_must_succeed(tools:gen_relative_path('/aaaa/bbb/cc/d.app','/aaaa/e.app','bbb/cc/d.app')).
469 :- assert_must_succeed(tools:gen_relative_path('/aaaa/bbb/cc/d.app','/aaaa/bbb/e.app','cc/d.app')).
470 :- assert_must_succeed(tools:gen_relative_path('/aaaa/bbb/cc/d.app','/aaaa/bbb/cc/e.app','d.app')).
471 :- assert_must_succeed(tools:gen_relative_path('/aaaa/bbb/cc/d.app','/aaaa/xx/e.app','../bbb/cc/d.app')).
472 :- assert_must_succeed(tools:gen_relative_path('/aaaa/bbb/cc/d.app','/aaaa/xx/yy/e.app','../../bbb/cc/d.app')).
473 :- assert_must_succeed(tools:gen_relative_path('/aaaa/bbb/cc/d.app','/aaaa/xx/yy/','../../bbb/cc/d.app')).
474 :- assert_must_succeed(tools:gen_relative_path('d.app','/aaaa/xx/yy/','d.app')).
475 :- assert_must_succeed(tools:gen_relative_path('d/e.app','/aaaa/xx/yy/','d/e.app')).
476 % can be used for already expanded full paths;
477 % the relative_to option absolute_file_name does not seem to work on already expanded full paths
478 gen_relative_path(Path,ReferencePath,RelPath) :-
479 split_atom_with_empty(Path,['/','\\'],PC1),
480 (PC1 = [File|_], File \= ''
481 -> % this is a relative path, not an absolute one; this is not the intended use of this predicate
482 RelPath = Path % but can happen, e.g., in error_manager
483 ; split_atom_with_empty(ReferencePath,['/','\\'],PC2),
484 split_com_aux(PC1,PC2,_,Suff1),
485 split_com_aux(PC2,PC1,_,Suff2),
486 (Suff2=[_|D2] -> true ; D2=Suff2), % remove last entry
487 maplist(replace_by_dotdot,D2,DotDot), % replace directory names by ..
488 append(DotDot,Suff1,Rel1),
489 ajoin_with_sep(Rel1,'/',RelPath)
490 ).
491
492 replace_by_dotdot(_,'..').
493
494 :- use_module(library(file_systems),[current_directory/1]).
495 gen_relative_path_to_cur_dir(Path,RelPath) :-
496 current_directory(CurDir),
497 gen_relative_path(Path,CurDir,RelPath).
498
499
500 :- assert_must_succeed(tools:is_absolute_path('/aaaa/bbb/cc/d.app')).
501 :- assert_must_fail(tools:is_absolute_path('cc/d.app')).
502 :- assert_must_fail(tools:is_absolute_path('./cc/')).
503 is_absolute_path(Path) :-
504 atom_chars(Path,PathAscii),
505 PathAscii = ['/'|_]. % TO DO: add other rules for windows C: ...
506
507 :- assert_must_succeed(tools:get_parent_directory('/aaaa/bbb/cc/d.app','/aaaa/bbb/cc/')).
508 :- assert_must_succeed(tools:get_parent_directory('/aaaa/bbb/cc/','/aaaa/bbb/cc/')).
509 :- assert_must_succeed(tools:get_parent_directory('d.app','')).
510 :- assert_must_succeed(tools:get_parent_directory('/a/b/cc/(machine from Jupyter cell).mch','/a/b/cc/')).
511 :- assert_must_succeed(tools:get_parent_directory('D:\\Users\\OneDrive - hhu\\[Master] PA\\models\\r\\RF.mch',
512 'D:\\Users\\OneDrive - hhu\\[Master] PA\\models\\r\\')).
513
514 get_parent_directory(Path,NewPath) :-
515 atom_chars(Path,PathAscii),
516 strip_last(PathAscii,[],[],New),
517 atom_chars(NewPath,New).
518
519 :- assert_must_succeed(tools:get_parent_directory_of_directory('/aaaa/bbb/cc/d.app','/aaaa/bbb/cc/')).
520 :- assert_must_succeed(tools:get_parent_directory_of_directory('/aaaa/bbb/cc/','/aaaa/bbb/')).
521 :- assert_must_succeed(tools:get_parent_directory_of_directory('\\aaaa\\bb b\\cc\\','\\aaaa\\bb b\\')).
522 % just like get_parent_directory, except when last character is a slash
523 get_parent_directory_of_directory(Path,NewPath) :-
524 atom_chars(Path,PathAscii0),
525 (append(PathAscii,[Last],PathAscii0), is_path_slash(Last)
526 -> true ; PathAscii=PathAscii0),
527 strip_last(PathAscii,[],[],New),
528 atom_chars(NewPath,New).
529
530 is_path_slash('/').
531 is_path_slash('\\'). % Windows
532
533 :- assert_must_succeed(tools:get_parent_directory_name('/aaaa/bbb/cc/d.app','cc')).
534 :- assert_must_succeed(tools:get_parent_directory_name('/aaaa/bbb/cc/','cc')).
535 :- assert_must_succeed(tools:get_parent_directory_name('\\aaaa\\bbb\\cc\\','cc')).
536 :- assert_must_succeed(tools:get_parent_directory_name('\\aaaa\\bbb b\\cc c\\','cc c')).
537 :- assert_must_fail(tools:get_parent_directory_name('d.app',_)).
538 :- assert_must_succeed(tools:get_parent_directory_name('/a/b/cd/(machine from Jupyter cell).mch','cd')).
539
540 get_parent_directory_name(Path,DirName) :-
541 atom_chars(Path,P1),
542 split_last2_lst(P1, ['/','\\'], [],[], P2, _),
543 split_last2_lst(P2, ['/','\\'], [],[], _, DChars),
544 atom_chars(DirName,DChars).
545
546 :- use_module(library(lists)).
547
548 % strip part after last path slash
549 strip_last([],ResSoFar,_,Res) :- reverse(ResSoFar,Res).
550 strip_last([Slash|Tail],ResSoFar,StripSoFar,Res) :- is_path_slash(Slash), !,
551 append([Slash|StripSoFar],ResSoFar,NewRes),
552 strip_last(Tail,NewRes,[],Res).
553 strip_last([A|Tail],ResSoFar,StripSoFar,Res) :-
554 strip_last(Tail,ResSoFar,[A|StripSoFar],Res).
555
556 :- assert_must_succeed((tools:split_atom_at_separator('ef,g',',',L,R), L==ef,R==g)).
557 % a simple split into two parts using a single separator atom of length 1
558 split_atom_at_separator(Atom,Sep,Left,Right) :-
559 ? sub_atom(Atom, Before, 1, After, Sep),
560 sub_atom(Atom, 0, Before, _, Left),
561 sub_atom(Atom, _, After, 0, Right).
562
563 :- assert_must_succeed((tools:split_atom('ef,g',[','],R), R==[ef,g])).
564 :- assert_must_succeed((tools:split_atom('ef, g',[',',' '],R), R==[ef,g])).
565 :- assert_must_succeed((tools:split_atom('ab,cd,ef,g',[','],R), R==['ab','cd',ef,g])).
566 :- assert_must_succeed((tools:split_atom('ab,cd,ef;g',[',',';'],R), R==['ab','cd',ef,g])).
567 :- assert_must_succeed((tools:split_atom('/ef/g/',['/'],R), R==[ef,g])).
568
569 split_atom(Atom,SepList,SplitList) :-
570 atom_chars(Atom,ListAscii),
571 split2(ListAscii,SepList,SplitList).
572
573 split2([],_,R) :- !,R=[].
574 split2(List,Sep,Res) :- get_next_word(List,Sep,Word,Tail),!,
575 (Word=[]
576 -> split2(Tail,Sep,Res) % skip empty atom
577 ; Res=[Atom|TA], atom_chars(Atom,Word),
578 split2(Tail,Sep,TA)).
579
580 get_next_word([],_Sep,[],[]).
581 get_next_word([H|T],Sep,Word,Tail) :-
582 ? member(H,Sep) -> Word=[],Tail=T
583 ; Word=[H|TR], get_next_word(T,Sep,TR,Tail).
584
585
586 :- assert_must_succeed((tools:split_atom_with_empty('/ef/g/',['/'],R), R==['',ef,g,''])).
587 :- assert_must_succeed((tools:split_atom_with_empty('/ef/g',['/'],R), R==['',ef,g])).
588 :- assert_must_succeed((tools:split_atom_with_empty('ef/g',['/'],R), R==[ef,g])).
589 :- assert_must_succeed((tools:split_atom_with_empty('efg',['/'],R), R==[efg])).
590
591 % a version of split atom that also returns empty sub atoms
592 split_atom_with_empty(Atom,SepList,SplitList) :-
593 atom_chars(Atom,ListAscii),
594 split_wempty2(ListAscii,SepList,SplitList).
595
596 split_wempty2(List,Sep,Res) :-
597 get_next_match(List,Sep,Word,Tail),!,
598 Res=[Atom|TA], atom_chars(Atom,Word),
599 split_wempty2(Tail,Sep,TA).
600 split_wempty2(List,_,[Atom]) :- atom_chars(Atom,List).
601
602 get_next_match([H|T],Sep,Word,Tail) :-
603 ? member(H,Sep) -> Word=[],Tail=T
604 ; Word=[H|TR], get_next_match(T,Sep,TR,Tail).
605
606
607 :- assert_must_succeed((tools:split_complex_sep("ef,,g,h",",,",R), R==["ef","g,h"])).
608 % a version of split that allows longer seperators, % TO DO: make more efficient
609 split_complex_sep(L,Sep,[First|Rest]) :- append(Sep,LRest,SepR),
610 append(First,SepR,L),
611 !,
612 split_complex_sep(LRest,Sep,Rest).
613 split_complex_sep(H,_,[H]).
614
615
616 :- assert_must_succeed((tools:split_chars("ef,g",",",R), R==["ef","g"])).
617 :- assert_must_succeed((tools:split_chars("10",".",R), R==["10"])).
618 :- assert_must_succeed((tools:split_chars("",".",R), R==[""])).
619 :- assert_must_succeed((tools:split_chars("1.0",".",R), R==["1","0"])).
620 :- assert_must_succeed((tools:split_chars("1.",".",R), R==["1",""])).
621 :- assert_must_succeed((tools:split_chars(".1",".",R), R==["","1"])).
622
623 split_chars(List,Sep,Res) :- get_next_word_until_sep(List,Sep,Word,Tail),!,
624 Res=[Word|TA],
625 split_chars(Tail,Sep,TA).
626 split_chars(List,_,[List]).
627
628 get_next_word_until_sep([H|T],Sep,Word,Tail) :-
629 member(H,Sep) -> Word=[],Tail=T
630 ; Word=[H|TR], get_next_word_until_sep(T,Sep,TR,Tail).
631
632 :- assert_must_succeed(tools:split_last('/aaaa/bbb/cc/d.app','/','/aaaa/bbb/cc','d.app')).
633 :- assert_must_succeed(tools:split_last('/aaaa/bbb/cc/d.app','.','/aaaa/bbb/cc/d','app')).
634 split_last(Atom, Sep, Head, Tail) :- \+ atom(Sep),!,
635 add_internal_error('Separator not an atom: ', split_last(Atom, Sep, Head, Tail)),fail.
636 split_last(Atom, Sep, Head, Tail) :- atom_chars(Sep,SepACodes),
637 split_last_lst(Atom,SepACodes,Head,Tail).
638
639
640 :- assert_must_succeed(tools:split_last_lst('/aaaa/bbb;cc/d.app',['/',';'],'/aaaa/bbb;cc','d.app')).
641 :- assert_must_succeed(tools:split_last_lst('/aaaa/bbb/cc/d.app',['.'],'/aaaa/bbb/cc/d','app')).
642 % a list version of split_last: obtains a list of sperator chars
643 split_last_lst(Atom, Seps, Head, Tail) :- \+ atom(Atom),!,
644 add_internal_error('First arg not an atom: ', split_last_lst(Atom, Seps, Head, Tail)),fail.
645 split_last_lst(Atom, Seps, Head, Tail) :-
646 atom_chars(Atom,ListAscii),
647 split_last2_lst(ListAscii,Seps,[],[],HeadA, TailA),
648 atom_chars(Head,HeadA), atom_chars(Tail,TailA).
649
650 split_last2_lst([],_,CurSplit,[_|Head],ResH,ResT) :-
651 reverse(CurSplit,ResT),
652 reverse(Head,ResH).
653 ?split_last2_lst([Sep|Tail],Seps,CurSplit,Head,ResH,ResT) :- member(Sep,Seps), % TO DO: use ord_member ?
654 !,
655 append([Sep|CurSplit],Head,NewHead),
656 split_last2_lst(Tail,Seps,[],NewHead,ResH,ResT).
657 split_last2_lst([H|Tail],Seps,CurSplit,Head,ResH,ResT) :-
658 split_last2_lst(Tail,Seps,[H|CurSplit],Head,ResH,ResT).
659
660
661
662 :- assert_must_succeed(tools:split_filename('/aaaa/bbb/cc/d.app','/aaaa/bbb/cc/d','app')).
663 :- assert_must_succeed((Z='/aaaa/bbb/cc/d',tools:split_filename(Z,R,X),X=='',R==Z)).
664
665 split_filename(Filename,Base,Ext) :-
666 (split_last(Filename,'.',Base,Ext) -> true ; Base=Filename,Ext='').
667
668
669 :- assert_must_succeed(tools:get_tail_filename('/aaaa/bbb/cc/d.app','d.app')).
670 :- assert_must_succeed(tools:get_tail_filename('\\aaaa\\bbb\\c\\d.app','d.app')).
671 :- assert_must_succeed(tools:get_tail_filename('d.app','d.app')).
672 :- assert_must_succeed(tools:get_tail_filename('/aaaa/bbb/cc/','')).
673 get_tail_filename(Path,Tail) :- compound(Path),!,
674 add_internal_error('Not a filename: ',get_tail_filename(Path,Tail)),
675 Tail=Path.
676 get_tail_filename(Path,Tail) :- (split_last_lst(Path, ['/','\\'], _, T) -> Tail=T ; Tail=Path).
677
678 :- assert_must_succeed(tools:get_modulename_filename('/aaaa/bbb/cc/d.app','d')).
679 :- assert_must_succeed(tools:get_modulename_filename('d.app','d')).
680 get_modulename_filename(Path,Module) :-
681 get_tail_filename(Path,Tail),
682 (split_last(Tail, '.', M, _) -> Module=M ; Module=Tail).
683
684
685 :- assert_must_succeed(get_filename_extension('/aaaa/bbb/cc/d.app','app')).
686 get_filename_extension(Path,Ext) :- split_filename(Path,_,Ext).
687
688 % also works if numbers passed (can happen by accident in test_runner ...)
689 % absolute_file_name('$a',X) generates a permission error
690 safe_absolute_file_name(F,AF,Options) :-
691 ensure_atom(F,A),
692 catch(
693 absolute_file_name(A,AF,Options),
694 error(permission_error(_,_,_),ERR),
695 (format('*** Permission Error for absolute_file_name: ~w~n',[ERR]),AF=F)).
696
697 safe_absolute_file_name(F,AF) :- safe_absolute_file_name(F,AF,[]).
698
699 % host_platform specific check if file names match
700 same_file_name(F,F) :- !.
701 same_file_name(File1,File2) :- host_file_name_case_insensitive,
702 atom_codes(File1,FC1),
703 atom_codes(File2,FC2),
704 maplist(case_insensitive_match,FC1,FC2).
705
706 case_insensitive_match(Code,Code) :- !.
707 case_insensitive_match(C1,C2) :-
708 simple_lowcase(C1,L1),
709 simple_lowcase(C2,L1).
710
711 % TODO: are there other changes to be made in Windows filenames?
712 simple_lowcase(H,R) :- H >="A", H=<"Z", !, R is H+"a"-"A".
713 simple_lowcase(92,R) :- !, R=47. % convert Windows path divider \ to Unix one /
714 simple_lowcase(Code,Code).
715
716 host_file_name_case_insensitive :-
717 host_platform(Platform),
718 host_file_name_case_insensitive(Platform).
719 host_file_name_case_insensitive(windows).
720 host_file_name_case_insensitive(darwin). % by default case insensitive, but up/lower case stored
721 % TODO: can we check if main filesystem is case sensitive??
722
723 %*******************************************************************************
724 % remove_all(A,B,Result): Result is the list of elements of A which do not occur in B
725 remove_all([],_,[]).
726 remove_all([H|T],Remove,Result) :-
727 ? (member(H,Remove) -> !,Result = Rest ; Result = [H|Rest]),
728 remove_all(T,Remove,Rest).
729
730
731
732 %*******************************************************************************
733 % get options from Prolog list passed as parameter
734
735
736 :- assert_must_succeed((get_option_from_list(b,2,[a/false,b/true],B),B==true)).
737 get_option_from_list(Option,Default, OptionList,Value) :-
738 (memberchk(Option/V,OptionList) -> Value=V ; Value=Default).
739
740
741 :- assert_must_succeed(get_options_from_list([option(a,true,false)],[a/false,b/true])).
742 :- assert_must_succeed((get_options_from_list([option(a,true,A)],[a/false,b/true]),A==false)).
743 :- assert_must_succeed((get_options_from_list([option(c,3,C),option(b,1,B),option(a,2,A)],[a/false,b/true]),
744 A==false,B==true,C==3)).
745
746 :- use_module(library(lists), [select/3]).
747
748 get_options_from_list([],_OptionList). % TO DO: provide optional check that no other options left
749 get_options_from_list([option(OptionName,Default,Value)|T],OptionList) :-
750 ? (select(OptionName/V,OptionList,Rest) -> Value=V
751 ; Value=Default, Rest=OptionList),
752 get_options_from_list(T,Rest).
753
754
755 %*******************************************************************************
756 % get_options/4 for parsing command line arguments
757
758
759 get_options(List,Pred,Options,Rest) :-
760 get_options(List,Pred,Options,Rest,halt).
761 get_options([],_,[],[],_).
762 get_options([X|T],Recognised,Options,Args,HALTCMD) :-
763 ? ( call(Recognised,X,Opt,Values,Action)
764 ->
765 ( append(Values, Rest, T) -> true
766 ;
767 length(Values,Len),
768 length(T,TLen),
769 (TLen < Len
770 -> format('Command ~w expects ~w argument(s); ~w provided.~n',[X,Len,TLen])
771 ; format('~nInvalid argument(s) for option: ~w.~n',[X]) % will never happen ??
772 ),
773 HALTCMD),
774 ( call(Action) -> true
775 ;
776 format('~nInvalid argument(s) for option ~w : ~w.~n',[X,Values]),
777 HALTCMD),
778 RT = Rest,
779 Options = [Opt|OT], Args = AT
780 ; % option not recognised, keep in Args list (for probcli these are assumed to be files)
781 Options = OT, Args = [X|AT],
782 RT = T
783 ),
784 get_options(RT,Recognised,OT,AT,HALTCMD).
785
786 arg_is_number(Arg,Nr) :- number(Arg),!,Nr=Arg.
787 arg_is_number(Arg,Nr) :- atom(Arg),atom_codes(Arg,Str),safe_number_codes(Nr,Str),number(Nr).
788 arg_is_integer(Arg,Nr) :-
789 ( atom_concat("-",SPos,Arg) -> % negative number
790 arg_is_number(SPos,Pos),
791 Nr is -Pos
792 ;
793 arg_is_number(Arg,Nr)).
794
795 % utilities for command-line arguments
796 % allow Number, _, >Number, <Number
797 arg_is_number_or_wildcard('_',R) :- !, R=_.
798 arg_is_number_or_wildcard('*',R) :- !, R=_. % * on command-line is expanded to files unless quoted
799 arg_is_number_or_wildcard(Arg,R) :- arg_is_number(Arg,N),!,R=N.
800 arg_is_number_or_wildcard(Comparator,R) :- atom(Comparator), atom_codes(Comparator,AC),
801 comparator(AC,CompOp,NC), safe_number_codes(Nr,NC), R=comparison_operator(CompOp,Nr).
802 comparator([0'>|T],>,T). % Ascii code 62
803 comparator([0'<|T],<,T).
804 comparator([0'>,0'=|T],'>=',T).
805 comparator([0'=,0'<|T],'=<',T).
806
807
808 % TO DO: add comparator
809
810 :- use_module(error_manager,[add_warning/3]).
811 check_filename_arg(File,Command) :- tools:arg_is_number(File,_),!,
812 ajoin(['File argument to -',Command,' is a number: '],Msg),
813 add_warning(Command,Msg,File).
814 check_filename_arg(File,Command) :- atom(File),
815 sub_atom(File,0,1,_,'-'), % atom_concat('-',_,File),
816 !,
817 ajoin(['File argument to -',Command,' starts with a hypen: '],Msg),
818 add_warning(Command,Msg,File).
819 check_filename_arg(_,_).
820
821
822 :- assert_must_succeed( tools:convert_list_into_pairs([a],a)).
823 :- assert_must_succeed( (tools:convert_list_into_pairs([a,b,c],R), R = ((a,b),c) )).
824
825 convert_list_into_pairs([X|T],Res) :- !,conv2(T,X,Res).
826 convert_list_into_pairs([],Res) :- !, Res=[].
827 convert_list_into_pairs(X,R) :- add_internal_error('Not a list: ',convert_list_into_pairs(X,R)),R=X.
828 conv2([],X,X).
829 conv2([X|T],Acc,Res) :- conv2(T,(Acc,X),Res).
830
831 :- assert_must_succeed(( tools:convert_pairs_into_list([x],a,R), R==[a] )).
832 %:- assert_must_succeed(( b_interpreter:convert_pairs_into_list([x,y,z],((a,b),c),R), R == [a,b,c] )).
833 :- assert_must_succeed(( tools:convert_pairs_into_list([x,y,z],((a,b),c),R), R == [a,b,c] )).
834 :- assert_must_succeed(( tools:convert_pairs_into_list([x,y,z],A,B),nonvar(A),nonvar(B),A=((_,_),_),B=[_,_,_] )).
835
836 % the first argument just indicates the identifiers, the second is a constructed pair and the third the list of values
837 convert_pairs_into_list([_],X,R) :- !,R=[X].
838 convert_pairs_into_list([_|Guide],Pair,R) :- !, R = [A|TValList],
839 conv4(Guide,A,Pair,TValList).
840 convert_pairs_into_list(List,Pairs,Result) :-
841 add_internal_error('Illegal arguments:',convert_pairs_into_list(List,Pairs,Result)),
842 fail.
843
844 conv4([],X,X,[]).
845 conv4([_|T],Acc,Res,[X|TValList]) :- conv4(T,(Acc,X),Res,TValList).
846
847
848 /* ex: substitute(1, [1,2,3,4], 5, X). */
849 :- assert_must_succeed(( tools:substitute(1, [1,2,3,4], 5, X), X==[5,2,3,4])).
850 substitute(X,L,Y,Res) :- sub(L,X,Y,Res).
851 sub([],_,_,[]).
852 sub([H|T],X,Y,[SH|ST]) :-
853 (H=X -> SH=Y ; SH=H),
854 sub(T,X,Y,ST).
855
856
857
858 :- use_module(tools_strings,[ajoin/2, ajoin_with_sep/3, ajoin_with_limit/3]).
859 % tests are stored here to avoid cyclic module dependencies
860 :- assert_must_succeed((tools_strings: ajoin_with_sep([link,a,xa],'.',Text), Text == 'link.a.xa')).
861 :- assert_must_succeed((tools_strings: ajoin_with_sep([link],'.',Text), Text == 'link')).
862 :- assert_must_succeed((tools_strings: ajoin_with_sep(['',a,''],'.',Text), Text == '.a.')).
863
864 :- assert_must_succeed((tools_strings: ajoin_with_limit(['A','B','C','D'],100,Text), Text == 'ABCD')).
865 :- assert_must_succeed((tools_strings: ajoin_with_limit(['A','B','C','D'],2,Text), Text == 'AB...')).
866
867
868 :- use_module(error_manager,[add_error_and_fail/3]).
869 safe_univ(Term,List) :- nonvar(Term),!,Term=..List.
870 safe_univ(Term,List) :- var(List), !,add_error_and_fail(tools,'Arguments to safe_univ (=..) both var:', safe_univ(Term,List)).
871 safe_univ(Term,List) :- %Term is a variable
872 current_prolog_flag(max_arity,MA),
873 (MA = unbounded -> CL = List ; cut_off_list(List,MA,CL)),
874 !, % avoid pending choice points
875 Term =.. CL.
876
877 cut_off_list([],_,[]).
878 cut_off_list([H|T],MA,R) :- (MA<2 -> R=['...'] ; R=[H|TR],MA1 is MA-1, cut_off_list(T,MA1,TR)).
879
880
881 % a version of safe_univ which does not remove args; just puts the extra arguments into the last arg
882
883 safe_univ_no_cutoff(Term,List) :- nonvar(Term),!,Term=..List.
884 safe_univ_no_cutoff(Term,List) :- var(List), !,
885 add_error_and_fail(tools,'Arguments to safe_univ (=..) both var:', safe_univ_no_cutoff(Term,List)).
886 safe_univ_no_cutoff(Term,List) :- %Term is a variable
887 current_prolog_flag(max_arity,MA),
888 (MA = unbounded -> CL = List ; squash_list(List,MA,CL)),
889 !, % avoid pending choice points
890 Term =.. CL.
891 squash_list([],_,[]).
892 squash_list([H|T],MA,R) :- (MA<3,T\=[] -> R=[H,T] ; R=[H|TR],MA1 is MA-1, squash_list(T,MA1,TR)).
893
894 safe_atom_chars(A,B,Loc) :-
895 catch(atom_chars(A,B), error(E1,E2), (
896 add_internal_error('atom_chars error: ',Loc:E1),
897 throw(error(E1,E2))
898 )).
899
900 :- use_module(tools_strings,[atom_codes_with_limit/2, atom_codes_with_limit/3]).
901
902 safe_atom_codes(V,C) :- var(V),var(C),!,
903 add_internal_error('Variables in call: ',safe_atom_codes(V,C)), C='$VARIABLE$'.
904 safe_atom_codes(A,C) :-
905 catch(atom_codes(A,C), error(representation_error(max_atom_length),_), (
906 print(exception(max_atom_length)),nl,
907 atom_codes_with_limit(A,1000,C)
908 )).
909
910 safe_number_codes(V,C) :- var(V),var(C),!,
911 add_internal_error('Variables in call: ',safe_number_codes(V,C)), C='$VARIABLE$'.
912 safe_number_codes(A,C) :-
913 catch(number_codes(A,C), error(syntax_error(_N),_), (
914 %print(9,syntax_error_in_number_codes(_N)),nl,
915 % in this case safe_number_codes fails ; we cannot convert the codes into a number
916 fail
917 )).
918
919 % for an identifier "x" and a number N, create a new identifier "x$N"
920 number_suffix(Id,N,FullId) :-
921 safe_atom_chars(Id,IdChars,number_suffix1),number_chars(N,NChars),
922 append(IdChars,['$'|NChars],FullIdChars),
923 safe_atom_chars(FullId,FullIdChars,number_suffix2).
924
925
926 :- assert_must_succeed(ensure_atom(19,'19')).
927 % ensure that numbers get converted to atoms:
928 ensure_atom(Var,A) :- var(Var),!, A='_'.
929 ensure_atom(N,Res) :- number(N),!,number_codes(N,C), atom_codes(A,C), Res=A.
930 ensure_atom(A,A).
931
932
933 :- assert_must_succeed(atom_or_number_codes(19,"19")).
934 :- assert_must_succeed(atom_or_number_codes(aa,"aa")).
935 atom_or_number_codes(N,Res) :- number(N),!,number_codes(N,Res).
936 atom_or_number_codes(A,Res) :- atom(A),!,atom_codes(A,Res).
937 atom_or_number_codes(Other,Res) :-
938 add_internal_error('Not atom or number: ',atom_or_number_codes(Other,Res)),
939 Res = [].
940
941
942 :- use_module(tools_strings,[truncate_atom/3]).
943 :- assert_must_succeed((tools_strings:truncate_atom(abcd,100,Text), Text == 'abcd')).
944 :- assert_must_succeed((tools_strings:truncate_atom(abcd,2,Text), Text == 'ab...')).
945 :- assert_must_succeed((tools_strings:truncate_atom(abcd,0,Text), Text == '...')).
946
947
948 wrap_and_truncate_atom(Atom,LineLength,Limit,NewAtom) :- \+ atom(Atom),!,
949 add_internal_error('Argument to wrap_and_truncate_atom not atom: ',wrap_and_truncate_atom(Atom,LineLength,Limit,NewAtom)),
950 NewAtom=Atom.
951 wrap_and_truncate_atom(Atom,LineLength,Limit,NewAtom) :-
952 atom_codes(Atom,Codes),
953 wrap_and_truncate_codes(Codes,LineLength,LineLength,Limit,NewCodes,Chng),
954 (Chng=true -> atom_codes(NewAtom,NewCodes) ; NewAtom=Atom).
955
956 wrap_and_truncate_codes([],_,_,_,[],false).
957 wrap_and_truncate_codes([H|T],CharsOnLineCount,MaxLineLength,TotCount,Res,Chng) :-
958 (TotCount<1 -> Res = [46,46,46],Chng=true /* '...' */
959 ; (CharsOnLineCount<1 -> Res=[92,110,H|TT], /* add newline \n */
960 TR=T, L1 is MaxLineLength, Chng=true
961 ; H=92,T=[H2|T2] -> Res = [H,H2|TT], /* do not split escaped char */
962 TR=T2, L1 is CharsOnLineCount-1, Chng2=Chng
963 ; Res = [H|TT], TR=T, L1 is CharsOnLineCount-1, Chng2=Chng),
964 TC1 is TotCount-1, wrap_and_truncate_codes(TR,L1,MaxLineLength,TC1,TT,Chng2)
965 ).
966
967
968 % print_size_of_table counts the number of succeeded calls of the
969 % given predicate
970 get_calls_for_table(Module:P/N,Call) :- !,
971 functor(Call,P,N),
972 call(Module:Call).
973 get_calls_for_table(P/N,Call) :-
974 functor(Call,P,N),
975 call(Call).
976
977 :- volatile count/1.
978 :- dynamic count/1.
979 print_size_of_table(Pred) :- retractall(count(_)),
980 assertz(count(0)),
981 get_calls_for_table(Pred,_),inc_size_of_table,fail.
982 print_size_of_table(Pred) :-
983 print('% size of table for '), print(Pred), print(': '), count(X), print(X),nl.
984 inc_size_of_table :- retract(count(X)),X1 is X+1, assertz(count(X1)).
985
986
987 % ----------------- Sorting ---------------
988
989 safe_sort(Orig,A,B) :- var(A),!, add_internal_error('Illegal call: ',safe_sort(Orig,A,B)),A=B.
990 safe_sort(_,A,B) :- sort(A,B).
991
992 :- use_module(library(samsort)).
993 % a sorting function which checks that there were no multiples in the original list
994 safe_set_sort(Orig,S,Res) :- var(S),!, add_internal_error('Illegal call: ',safe_set_sort(Orig,S,Res)),S=Res.
995 %safe_set_sort(Orig,S,Res) :- !,sort(S,Res).
996 safe_set_sort(Orig,S,Res) :- samsort(S,SS),
997 (SS=[H|T] -> (check_for_multiples(T,H,Orig) -> Res=SS ; sort(SS,Res)) ; Res=SS).
998 check_for_multiples([],_,_).
999 check_for_multiples([H|T],Prev,Origin) :-
1000 (H=Prev
1001 -> add_error(Origin,'Multiple occurrences in set list of: ',H),fail
1002 ; check_for_multiples(T,H,Origin)).
1003
1004 % ----------------------
1005
1006 safe_functor(Src,F,A,Term) :- var(F),var(A),var(Term),!,
1007 add_internal_error('Illegal functor call: ',safe_functor(Src,F,A,Term)),
1008 fail.
1009 safe_functor(_,F,A,T) :- functor(F,A,T).
1010
1011
1012 print_runtime :- statistics(runtime,[Tot,SinceLast]), print(' Total runtime: '), print(Tot),
1013 print(' ms, since last: '), print(SinceLast), print(' ms'),nl.
1014
1015 :- use_module(debug,[debug_mode/1, silent_mode/1]).
1016 start_ms_timer(timer(R,T,W)) :- statistics(runtime,[R,_]),
1017 statistics(total_runtime,[T,_]),
1018 statistics(walltime,[W,_]).
1019 stop_ms_timer(T) :- stop_ms_timer(T,[runtime/RT,total_runtime/RTT,walltime/WT]),
1020 format('% Runtime: ~w ms (with gc: ~w ms, walltime: ~w ms)~n',[RT,RTT,WT]).
1021 stop_ms_timer_with_debug_msg(T,Msg) :-
1022 (debug_mode(on) -> stop_ms_timer_with_msg(T,Msg) ; true).
1023 stop_ms_timer_with_silent_msg(T,Msg) :-
1024 (silent_mode(on) -> true ; stop_ms_timer_with_msg(T,Msg)).
1025 stop_ms_timer_with_msg(T,Msg) :- stop_ms_timer(T,[runtime/RT,total_runtime/RTT,walltime/WT]),
1026 statistics(walltime,[WE,_]),
1027 convert_ms_time_to_string(WE,WEStr),
1028 format('% Runtime for ~w: ~w ms (with gc: ~w ms, walltime: ~w ms); since start: ~w~n',[Msg,RT,RTT,WT,WEStr]).
1029 stop_ms_walltimer_with_msg(T,Msg) :- stop_ms_timer(T,[runtime/_RT,total_runtime/_RTT,walltime/WT]),
1030 format('% Walltime for ~w: ~w ms~n',[Msg,WT]).
1031 stop_ms_timer(timer(R,T,W),[runtime/RT,total_runtime/RTT,walltime/WT]) :-!,
1032 statistics(runtime,[RE,_]),
1033 % These refer to CPU time used while executing, excluding time spent in memory management tasks or or in system calls.
1034 statistics(total_runtime,[TE,_]),
1035 % These refer to total CPU time used while executing, including memory management tasks such as garbage collection but excluding system calls.
1036 statistics(walltime,[WE,_]),
1037 % These refer to absolute time elapsed.
1038 RT is RE-R, RTT is TE-T, WT is WE-W.
1039 stop_ms_timer(X,Y) :-
1040 add_internal_error('Illegal call: ', stop_ms_timer(X,Y)),
1041 Y = [].
1042 get_elapsed_walltime(timer(_R,_T,W),WTot) :-
1043 statistics(walltime,[W2,_]), WTot is W2-W.
1044
1045 % convert ms time to a user readable time string
1046 convert_ms_time_to_string(TimeMS,Str) :-
1047 convert_ms_time_to_hms(TimeMS,H,M,S,MS),
1048 (H > 0 -> ajoin([H,' h ', M, ' min ', S, ' sec ', MS, ' ms'],Str)
1049 ; M > 0 -> ajoin([M, ' min ', S, ' sec ', MS, ' ms'],Str)
1050 ; ajoin([S, ' sec ', MS, ' ms'],Str)).
1051
1052 convert_ms_time_to_hms(TimeMS,Hours,MinsMod,SecsMod,MilSecs) :-
1053 MilSecs is TimeMS mod 1000,
1054 Secs is TimeMS // 1000, SecsMod is Secs mod 60,
1055 Mins is Secs // 60, MinsMod is Mins mod 60,
1056 Hours is Mins // 60.
1057
1058 % get delta timer between old timer1 and current time
1059 get_elapsed_timer(timer(R1,T1,W1),timer(R,T,W)) :-
1060 statistics(runtime,[R2,_]),
1061 statistics(total_runtime,[T2,_]),
1062 statistics(walltime,[W2,_]),
1063 R is R2-R1, T is T2-T1, W is W2-W1.
1064 get_elapsed_runtime(timer(R1,_,_),Delta) :-
1065 statistics(runtime,[R2,_]),
1066 Delta is R2-R1.
1067
1068 % combine (add) two timers
1069 combiner_timer(0,T2,R) :- !, R=T2.
1070 combiner_timer(timer(R1,T1,W1),timer(R2,T2,W2),timer(R,T,W)) :-
1071 R is R1+R2, T is T1+T2, W is W1+W2.
1072
1073 % a timer that measures backtracking times
1074 :- dynamic last_bt_timer/2.
1075 bt_start_ms_timer(Msg) :- retractall(last_bt_timer(Msg,_)),
1076 start_ms_timer(T), assertz(last_bt_timer(Msg,T)).
1077 bt_start_ms_timer(Msg) :- retract(last_bt_timer(Msg,Timer)),
1078 stop_ms_timer(Timer,[runtime/RT,total_runtime/_RTT,walltime/WT]),
1079 format('% Runtime to FINALISE ~w: ~w ms (walltime: ~w ms)~n',[Msg,RT,WT]),
1080 fail.
1081
1082
1083 bt_stop_ms_timer(Msg) :-
1084 retract(last_bt_timer(Msg,Last)),
1085 stop_ms_timer(Last,[runtime/RT,total_runtime/_RTT,walltime/WT]),
1086 format('% Runtime for SOLUTION for ~w: ~w ms (walltime: ~w ms)~n',[Msg,RT,WT]).
1087 bt_stop_ms_timer(Msg) :- start_ms_timer(BT_Timer),
1088 assertz(last_bt_timer(Msg,BT_Timer)),
1089 fail.
1090 % ---------------------------
1091
1092
1093 retract_with_statistics(Module,ListOfFacts) :-
1094 nl,print('Retracting Facts'),nl,
1095 get_memory_used(M),
1096 print(' Memory usage: '),print_memory_used(M),nl,
1097 retract_with_statistics(Module,ListOfFacts,M).
1098
1099
1100 retract_with_statistics(_Module,[],_) :- nl.
1101 retract_with_statistics(Module,[Fact|T],Mem) :-
1102 format('~w : ',[Fact]),
1103 %retractall(Module:Fact),
1104 retract_all_count(Module:Fact,0,Nr), format(' ~w facts : ',[Nr]),
1105 get_memory_used(NewMem),
1106 print_memory_used(NewMem),
1107 print_memory_used_difference(Mem,NewMem),
1108 retract_with_statistics(Module,T,NewMem).
1109
1110 retract_all_count(Fact,Acc,Res) :- \+ (\+ (retract(Fact))),!, A1 is Acc+1, retract_all_count(Fact,A1,Res).
1111 retract_all_count(_,R,R).
1112
1113 :- if(current_prolog_flag(dialect, swi)).
1114 % this could possibly be moved to SWI compatibility code
1115 statistics_memory_used(M) :-
1116 statistics(stack,GL), statistics(trail,T), statistics(heapused,H), M is GL+T+H.
1117 % not sure this computes all of memory used; other keys: globalused, localused, codes
1118 :- else.
1119 statistics_memory_used(M) :- statistics(memory_used,M).
1120 :- endif.
1121
1122 get_memory_used([M,PU]) :- garbage_collect,garbage_collect_atoms, get_memory_used_wo_gc([M,PU]).
1123 get_memory_used_wo_gc([M,PU]) :- statistics(program,[PU,_]),statistics_memory_used(M).
1124 print_memory_used_wo_gc :- print_memory_used_wo_gc(user_output).
1125 print_memory_used_wo_gc(Stream) :- get_memory_used_wo_gc(M), print_memory_used(Stream,M).
1126
1127 print_memory_used(M) :- print_memory_used(user_output,M).
1128 print_memory_used(Stream,[M,PU]) :- print_mb(Stream,M),
1129 write(Stream,' ('), print_mb(Stream,PU), write(Stream,' program) ').
1130
1131 print_memory_used_difference([M1,_PU1],[NewM2,_PU2]) :- Diff is (M1)-(NewM2),
1132 (Diff >= 0 -> print(' freed: '), print_bytes(Diff)
1133 ; print(' allocated: '), D2 is -(Diff), print_bytes(D2)),nl.
1134 %print(' / '),Diff2 is (PU1)-(PU2), print_mb(Diff2).
1135 print_bytes(X) :- (X<50000 -> print_kb(X) ; print_mb(X)).
1136 print_gb(X) :- XGB is X / 1000000000, % used instead of deprecated 1048576
1137 format(' ~3f GB',[XGB]).
1138 print_mb(X) :- print_mb(user_output,X).
1139 print_mb(Stream,X) :- XMB is X / 1000000, % used instead of deprecated 1048576
1140 format(Stream,' ~3f MB',[XMB]).
1141 print_kb(X) :- XKB is X / 1000, % used instead of deprecated 1024
1142 format(' ~3f KB',[XKB]).
1143
1144 space_call(Call) :- get_memory_used(M1),
1145 call(Call),
1146 get_memory_used(M2),
1147 print_memory_used(M2),
1148 print_memory_used_difference(M1,M2).
1149
1150 % ---------------------------
1151
1152 :- use_module(library(fastrw),[fast_read/2]).
1153
1154 read_term_from_file(Filename,Term) :-
1155 absolute_file_name(Filename,AbsFilename,[]),
1156 open(AbsFilename,read,Stream),
1157 peek_code(Stream,Code),
1158 read_term_from_file2(Code,Stream,AbsFilename,Term).
1159
1160 read_term_from_file2(Code,Stream,File,Term) :-
1161 fastrw_start_code(Code), !,
1162 close(Stream),
1163 open(File,read,NewStream,[type(binary)]),
1164 fast_read(NewStream,Term),
1165 close(NewStream).
1166 read_term_from_file2(_,Stream,_,Term) :-
1167 read_term(Stream,Term,[]),
1168 close(Stream).
1169
1170 fastrw_start_code(0'D). % like for .prob in parsercall
1171
1172 :- use_module(library(codesio), [read_from_codes/2]).
1173 safe_read_term_from_atom(Atom,Term) :-
1174 safe_atom_codes(Atom,Codes),
1175 safe_read_term_from_codes(Codes,Term).
1176 safe_read_term_from_codes(Codes,Term) :-
1177 (append(_,[46],Codes) % add dot: 46 = '.' if required
1178 -> Codes1 = Codes
1179 ; append(Codes,[46],Codes1)
1180 ),
1181 catch(read_from_codes(Codes1,Term),
1182 error(syntax_error(StxMsg),_),
1183 (atom_codes(AT,Codes),
1184 ajoin(['Prolog syntax error: ',StxMsg,' in'],Msg),
1185 add_error(read_term_from_codes,Msg,AT), fail)
1186 ).
1187
1188
1189 read_string_from_file(Filename,String) :-
1190 absolute_file_name(Filename,AbsFilename,[]),
1191 open(AbsFilename,read,S), % utf
1192 read_string(S,String),
1193 close(S).
1194
1195 % Encoding can be any value of text_encoding preference category: auto, 'ISO-8859-1', 'UTF-8', ...
1196 read_string_from_file(Filename,auto,String) :- !, read_string_from_file(Filename,String).
1197 read_string_from_file(Filename,Encoding,String) :-
1198 absolute_file_name(Filename,AbsFilename,[]),
1199 open(AbsFilename,read,S,[encoding(Encoding)]),
1200 read_string(S,String),
1201 close(S).
1202
1203 read_string(S,String) :-
1204 get_code(S,C),!,
1205 (C= -1
1206 -> String = []
1207 ; String = [C|Rest], read_string(S,Rest)).
1208
1209 read_atom_from_file(Filename,Encoding,Atom) :-
1210 read_string_from_file(Filename,Encoding,String),
1211 atom_codes(Atom,String).
1212
1213 % version which catches exceptions
1214 safe_read_string_from_file(Filename,Encoding,String) :-
1215 catch(read_string_from_file(Filename,Encoding,String), E, (
1216 ajoin(['Could not read string from file ',Filename,':'],Msg),
1217 add_error(read_string_from_file,Msg,E),
1218 fail
1219 )).
1220
1221 :- use_module(debug,[debug_format/3]).
1222 % open a file using auto and try and read XML header
1223 % <?xml version="1.0" encoding="UTF-8"?>
1224 % useful to first open file and detect encoding and then re-open file using the found encoding
1225 detect_xml_encoding(Filename,Version,Encoding) :-
1226 absolute_file_name(Filename,AbsFilename,[]),
1227 open(AbsFilename,read,Stream),
1228 call_cleanup(
1229 (
1230 match(" <?xml_version = \"",Stream),
1231 read_quoted_xml_string_contents(Stream,Version),
1232 debug_format(19,'XML version ~s detected~n',[Version]),
1233 (match(" encoding = \"",Stream)
1234 -> read_quoted_xml_string_contents(Stream,EncodingCodes),
1235 debug_format(19,'XML encoding ~s detected~n',[EncodingCodes]),
1236 (EncodingCodes = "windows 1252" -> UEnc=Encoding % only encoding using lower case
1237 ; maplist(simple_upcase,EncodingCodes,UEnc) % convert utf-8 to UTF-8;
1238 ),
1239 atom_codes(Encoding,UEnc)
1240 ; debug_format(19,'No XML encoding detected in header, using auto ~w~n',[Filename]),
1241 Encoding = auto
1242 )
1243 ),
1244 close(Stream)).
1245
1246
1247 simple_upcase(H,R) :- H >="a", H=<"z", !, R is H+"A"-"a".
1248 simple_upcase(H,H).
1249
1250 % simple read contents of a string until end quote; no escaping detected (yet)
1251 read_quoted_xml_string_contents(Stream,String) :-
1252 get_code(Stream,C),!,
1253 (C= -1
1254 -> String = []
1255 ; C = 34 -> String = [] % string finished
1256 ; String=[C|Rest],read_quoted_xml_string_contents(Stream,Rest)).
1257
1258 match([],_).
1259 match([H|T],Stream) :- !, get_code(Stream,C),
1260 match2(H,T,C,Stream).
1261
1262 match2(32,T,C,Stream) :- !, % treat a space character as optional whitespace
1263 (is_ws(C) -> match([32|T],Stream)
1264 ; T = [H1|T1],
1265 match2(H1,T1,C,Stream)
1266 ).
1267 match2(95,T,C,Stream) :- !, % treat underscore as mandatory whitespace
1268 (is_ws(C) -> match([32|T],Stream)
1269 ; debug_format(19,'Not a valid xml header ("~s" instead of whitespace)~n',[[C]]),fail
1270 ).
1271 match2(H,T,C,Stream) :-
1272 (C=H -> match(T,Stream)
1273 ; format('Not a valid xml header ("~s" instead of "~s")~n',[[C],[H]]),fail
1274 ).
1275
1276 is_ws(32).
1277 is_ws(9). % tab
1278 is_ws(10).
1279 is_ws(13).
1280
1281 %! open_temp_file(+BaseName, -Path, -Stream, +Options) is det.
1282 %
1283 % Compatible way to create and open a temporary file.
1284 %
1285 % ReqName will be used as the file name if possible,
1286 % but the actual file name may be different
1287 % (e. g. it may have a unique suffix added).
1288 % Path is the temporary file's full path,
1289 % which is automatically opened for writing as Stream.
1290 % Supported Options are type(binary) and encoding(Encoding).
1291 % see also tmpdir preference, default /tmp/ on Unix
1292
1293 :- if(predicate_property(tmp_file_stream(_,_,_), _)). % SWI
1294
1295 :- use_module(library(lists), [select/4]).
1296 open_temp_file(ReqName, Path, Stream, Options) :-
1297 select(type(binary), Options, encoding(octet), OptionsMod),
1298 !,
1299 open_temp_file(ReqName, Path, Stream, OptionsMod).
1300 open_temp_file(ReqName, Path, Stream, Options) :-
1301 % tmp_file_stream only allows controlling the extension, not the name before it.
1302 get_filename_extension(ReqName, Extension),
1303 tmp_file_stream(Path, Stream, [extension(Extension)|Options]).
1304
1305 :- else. % SICStus
1306
1307 open_temp_file(ReqName, Path, Stream, Options) :-
1308 open(temp(ReqName), write, Stream, [if_exists(generate_unique_name)|Options]),
1309 stream_property(Stream, file_name(Path)).
1310
1311 :- endif.
1312
1313 open_temp_file(ReqName, Path, Stream) :- open_temp_file(ReqName, Path, Stream, []).
1314
1315 % ------------------------------
1316
1317 % encoding atoms for Latex:
1318
1319 latex_escape_atom(Atom,EscAtom) :- \+ atom(Atom),!,
1320 add_internal_error('Cannot escape: ',latex_escape_atom(Atom,EscAtom)),
1321 EscAtom=Atom.
1322 latex_escape_atom(Atom,EscAtom) :-
1323 atom_codes(Atom,Codes), latex_escape_codes(Codes,ECodes), atom_codes(EscAtom,ECodes).
1324
1325 latex_escape_codes([],[]).
1326 %latex_escape_codes([92,C|T],[92,C|ET]) :- !, % already escaped
1327 % latex_escape_codes(T,ET).
1328 latex_escape_codes([C|T],[92,C|ET]) :- latex_escape_code(C),!, % 95 = _ underscore, 92 = \ backslash
1329 latex_escape_codes(T,ET).
1330 latex_escape_codes([Code|T],ET) :- translate_code(Code,String),
1331 !,
1332 append(String,ET2,ET),
1333 latex_escape_codes(T,ET2).
1334 latex_escape_codes([H|T],[H|ET]) :- latex_escape_codes(T,ET).
1335
1336 latex_escape_code(35). % #
1337 latex_escape_code(36). % $
1338 latex_escape_code(37). % %
1339 latex_escape_code(38). % &
1340 latex_escape_code(95). % 95 = _ underscore
1341 latex_escape_code(123). % {
1342 latex_escape_code(125). % }
1343
1344 translate_code(92,"\\textbackslash{}"). % \ % \textbackslash seems to work in both math and normal mode
1345 translate_code(94,"\\textasciicircum{}"). % ^
1346 translate_code(126,"\\textasciitilde{}"). % ~
1347 %translate_code(126,"\\~{}"). % 126 = ~ tilde -> \~{} (\sim would be alternative in math mode)
1348
1349 % ------------------------------
1350
1351 % encoding atoms for B Strings:
1352 % escape special characters so that we can output the string between quotes "..." and obtain a valid value
1353
1354 :- assert_must_succeed(tools:b_escape_string_atom('{"a"}','{\\"a\\"}')).
1355 :- assert_must_succeed(tools:b_escape_string_atom('{"a \\/ b"}','{\\"a \\/ b\\"}')).
1356
1357 b_escape_string_atom(Atom,EscAtom) :- \+ atom(Atom),!,
1358 add_internal_error('Cannot escape: ',b_escape_string_atom(Atom,EscAtom)),
1359 EscAtom=Atom.
1360 b_escape_string_atom(Atom,EscAtom) :-
1361 atom_codes(Atom,Codes), b_string_escape_codes(Codes,ECodes), atom_codes(EscAtom,ECodes).
1362
1363 b_string_escape_codes([],R) :- !, R=[].
1364 b_string_escape_codes([C|T],Res) :-
1365 (C=92, T=[C2|_], % 92 = \ backslash
1366 \+ valid_backslash_escape(C2) % we do not need to escape the \ in \x for example, but we need to escape in \n
1367 -> Res = [92|ET]
1368 ; b_escape_code(C,EC) -> Res = [92,EC|ET]
1369 ; Res = [C|ET]
1370 ),
1371 b_string_escape_codes(T,ET).
1372
1373 b_escape_code(9,116). % tab, 116 = t
1374 b_escape_code(10,110). % newline, 110 = n
1375 b_escape_code(13,114). % return 114 = r
1376 b_escape_code(34,34). % "
1377 %b_escape_code(39,39). % ' % not necessary for "..." literals
1378 b_escape_code(92,92). % \
1379
1380 % these are the escape codes the parser / ProB currently supports:
1381 valid_backslash_escape(34). % "
1382 valid_backslash_escape(39). % '
1383 valid_backslash_escape(92). % \
1384 valid_backslash_escape(110). %n
1385 valid_backslash_escape(114). %r
1386 valid_backslash_escape(116). %t
1387
1388 % ------------------------------
1389
1390
1391 %%
1392 % Escape is needed for &, \/, /\, ", ', etc.
1393 % used mainly for dot output
1394 % It seems dotty does not understand escapes, neither C style nor HTML style.
1395 % Dot does render '&' correctly, no matter of escape.
1396 %
1397
1398 print_escaped(Atom) :- string_escape(Atom,E), write(E).
1399
1400 :- use_module(library(lists), [
1401 maplist/3,
1402 scanlist/4]).
1403
1404 string_escape(Atom, EscapedAtom):-
1405 string_escape(dot_string_escape_map, Atom, EscapedAtom).
1406
1407
1408 string_escape(_,Number, EscapedAtom):-
1409 number(Number),!, number_chars(Number,C), atom_chars(EscapedAtom,C). % to detect when label=value
1410 string_escape(Map, Atom, EscapedAtom):-
1411 atom(Atom),
1412 atom_chars(Atom, Chars),
1413 maplist(Map, Chars, EscapedChars),
1414 scanlist(x_atom_concat_rev, EscapedChars, '', EscapedAtom),!.
1415 string_escape(Map,Term, EscapedTerm):-
1416 Term =.. [Fkt|Args],
1417 string_escape(Map, Fkt, EscapedFkt),
1418 maplist(string_escape(Map), Args, EscapedArgs),!,
1419 EscapedTerm =.. [EscapedFkt|EscapedArgs].
1420 string_escape(_,X,X).
1421
1422
1423 x_atom_concat_rev(A,B,BA):-
1424 atom_concat(B,A,BA).
1425
1426
1427 % simple escape, just ensuring no syntax errors and not disturbing records already constructed as B string,...
1428 % however, not that fields of records are already escaped
1429 simple_dot_string_escape(Number, EscapedAtom) :- number(Number),!,
1430 number_chars(Number,C), atom_chars(EscapedAtom,C).
1431 simple_dot_string_escape(Atom, EscapedAtom) :- atom(Atom),!,
1432 atom_chars(Atom,Chars),
1433 simple_dot_esc( Chars, EC), atom_chars(EscapedAtom,EC).
1434 simple_dot_string_escape(Atom,Res) :-
1435 add_internal_error('Not atomic: ',simple_dot_string_escape(Atom,Res)),
1436 Res=Atom.
1437
1438 simple_dot_esc([],[]).
1439 simple_dot_esc(['\\','"' | T],['\\','"' |TR]) :- !, % already escaped
1440 simple_dot_esc(T,TR).
1441 simple_dot_esc(['\\','\\' | T],['\\','\\' |TR]) :- !, % already escaped
1442 simple_dot_esc(T,TR).
1443 simple_dot_esc(['"' | T],['\\','"' |TR]) :- !,
1444 simple_dot_esc(T,TR).
1445 simple_dot_esc([H | T],[H|TR]) :-simple_dot_esc(T,TR).
1446
1447
1448 % ----------------
1449
1450
1451 % escape for XML attribute values for use in double quotes
1452 %https://stackoverflow.com/questions/19766669/which-characters-are-permitted-in-xml-attributes
1453 % AttValue ::= '"' ([^<&"] | Reference)* '"'
1454 % | "'" ([^<&'] | Reference)* "'"
1455
1456 xml_attribute_escape(Codes,EscapedCodes) :- xml_attr_escape(Codes,EscapedCodes,[]).
1457 xml_attr_escape([]) --> "".
1458 xml_attr_escape([0'&|T]) --> !, "&", xml_attr_escape(T).
1459 xml_attr_escape([0'<|T]) --> !, "<", xml_attr_escape(T).
1460 xml_attr_escape([0'>|T]) --> !, ">", xml_attr_escape(T). % strictly speaking not necessary for attribute values
1461 xml_attr_escape([10|T]) --> !, " ", xml_attr_escape(T). % newline
1462 xml_attr_escape([9|T]) --> !, " ", xml_attr_escape(T). % tab
1463 xml_attr_escape([0'"|T]) --> !, """, xml_attr_escape(T).
1464 xml_attr_escape([H|T]) --> [H], xml_attr_escape(T).
1465
1466 % ----------------
1467
1468 xml_escape(Number, EscapedAtom) :-
1469 number(Number),!, number_chars(Number,C), atom_chars(EscapedAtom,C).
1470 xml_escape(Atom, EscapedAtom) :-
1471 atom_codes(Atom,Codes),
1472 xml_escape_codes(Codes,ECodes),
1473 atom_codes(EscapedAtom,ECodes).
1474
1475 xml_escape_codes([],[]).
1476 xml_escape_codes([H|T],Res) :-
1477 xml_string_escape_map(H,NewCodes), !,
1478 append(NewCodes,TR,Res),
1479 xml_escape_codes(T,TR).
1480 xml_escape_codes([H|T],[H|TR]) :-
1481 xml_escape_codes(T,TR).
1482
1483 xml_string_escape_map(34,[38,113,117,111,116,59]) :- !. % " -> "
1484 xml_string_escape_map(38,[38,97,109,112,59]) :- !. % & -> &
1485 xml_string_escape_map(39,[38,97,112,111,115,59]) :- !. % ' -> '
1486 xml_string_escape_map(60,[38,108,116,59]) :- !. % < -> <
1487 xml_string_escape_map(62,[38,103,116,59]) :- !. % > -> >
1488
1489
1490 html_escape(Number, EscapedAtom) :-
1491 number(Number),!, number_chars(Number,C), atom_chars(EscapedAtom,C). % to detect when label=value
1492 html_escape(Atom, EscapedAtom) :-
1493 atom_codes(Atom,Codes),
1494 html_escape_codes(Codes,ECodes),
1495 atom_codes(EscapedAtom,ECodes).
1496 % atom_chars(Atom, Chars),
1497 % maplist(html_string_escape_map, Chars, EscapedChars),!,
1498 % scanlist(x_atom_concat_rev, EscapedChars, '', EscapedAtom). % very inefficient for large atoms
1499
1500
1501 html_escape_codes([],[]).
1502 html_escape_codes([H|T],Res) :-
1503 \+ no_escape_necessary(H), % avoid calling atom_codes
1504 atom_codes(Atom,[H]),
1505 html_string_escape_map(Atom,NewAtom), % TODO: rewrite html_escape map to work with codes
1506 !,
1507 atom_codes(NewAtom,NewCodes),
1508 append(NewCodes,TR,Res),
1509 html_escape_codes(T,TR).
1510 html_escape_codes([H|T],[H|TR]) :-
1511 html_escape_codes(T,TR).
1512
1513 no_escape_necessary(32).
1514 no_escape_necessary(40). % (
1515 no_escape_necessary(41). % )
1516 no_escape_necessary(44). % ,
1517 no_escape_necessary(45). % -
1518 no_escape_necessary(46). % .
1519 no_escape_necessary(61). % =
1520 no_escape_necessary(95).
1521 no_escape_necessary(X) :- (X>=97,X=<122) ; (X>=65, X=<90) ; (X>=48, X=<57). % alphadigit
1522
1523 dot_string_escape_map('\n', '\\n').
1524 dot_string_escape_map('\\', '\\\\').
1525 dot_string_escape_map('"', '\\"').
1526 dot_string_escape_map('\'', '\\\'').
1527 dot_string_escape_map('{', '\\{'). % important if used inside dot records
1528 dot_string_escape_map('}', '\\}'). % important if used inside dot records
1529 dot_string_escape_map('|', '\\|'). % important if used inside dot records
1530 dot_string_escape_map('>', '\\>'). % important if used inside dot records
1531 dot_string_escape_map('<', '\\<'). % important if used inside dot records
1532 dot_string_escape_map(A,B) :- x_string_escape_map(A,B).
1533
1534 html_string_escape_map('&', '&') :- !. % michael: habe diese 3 Zeilen auskommentiert
1535 html_string_escape_map('<', '<') :- !.
1536 html_string_escape_map('>', '>') :- !.
1537 html_string_escape_map('"', '"') :- !.
1538 html_string_escape_map(A,B) :- x_string_escape_map(A,B),!.
1539
1540
1541 % this is the SICSTus encoding for Unicode either \octal_number\ or \xHexNumber\
1542 % See Section 4.1.7.6 Escape Sequences in SICStus Manual (page 60)
1543 x_string_escape_map('\344\', 'ä'). % a mit Umlaut
1544 x_string_escape_map('\366\', 'ö'). % o mit Umlaut
1545 x_string_escape_map('\374\', 'ü'). % u mit Umlaut
1546 x_string_escape_map('\304\', 'Ä'). % A mit Umlaut
1547 x_string_escape_map('\326\', 'Ö'). % O mit Umlaut
1548 x_string_escape_map('\334\', 'Ü'). % U mit Umlaut
1549
1550 x_string_escape_map('\353\', 'ë'). % e mit Umlaut
1551 x_string_escape_map('\313\', 'Ë'). % E mit Umlaut
1552
1553 x_string_escape_map('\350\', 'è'). % e mit Accent
1554 x_string_escape_map('\351\', 'é').
1555 x_string_escape_map('\352\', 'ê').
1556 x_string_escape_map('\310\', 'È'). % E mit Accent
1557 x_string_escape_map('\311\', 'É').
1558 x_string_escape_map('\312\', 'Ê').
1559
1560 x_string_escape_map('\340\', 'à'). % a mit Accent
1561 x_string_escape_map('\341\', 'á').
1562 x_string_escape_map('\342\', 'â').
1563 x_string_escape_map('\300\', 'À'). % A mit Accent
1564 x_string_escape_map('\301\', 'Á').
1565 x_string_escape_map('\302\', 'Â').
1566
1567 x_string_escape_map('\354\', 'ì'). % i mit Accent
1568 x_string_escape_map('\355\', 'í').
1569 x_string_escape_map('\356\', 'î').
1570 x_string_escape_map('\314\', 'Ì'). % I mit Accent
1571 x_string_escape_map('\315\', 'Í').
1572 x_string_escape_map('\316\', 'Î').
1573
1574 x_string_escape_map('\362\', 'ò'). % o mit Accent
1575 x_string_escape_map('\363\', 'ó').
1576 x_string_escape_map('\364\', 'ô').
1577 x_string_escape_map('\322\', 'Ò'). % O mit Accent
1578 x_string_escape_map('\323\', 'Ó').
1579 x_string_escape_map('\324\', 'Ô').
1580
1581 x_string_escape_map('\347\', 'ç'). % cedille
1582 x_string_escape_map('\307\', 'Ç'). % Cedille
1583
1584 x_string_escape_map('\337\', 'ß'). % scharfes S (sz)
1585 x_string_escape_map('\361\', 'ñ'). % n with tilde
1586
1587 x_string_escape_map('\1661\', 'α'). % Greek
1588 x_string_escape_map('\1662\', 'β').
1589 x_string_escape_map('\1663\', 'γ').
1590 x_string_escape_map('\1664\', 'δ').
1591 x_string_escape_map('\1665\', 'ε').
1592 x_string_escape_map('\1666\', 'ζ').
1593 x_string_escape_map('\1667\', 'η').
1594 x_string_escape_map('\1670\', 'θ').
1595 x_string_escape_map('\1671\', 'ι').
1596 x_string_escape_map('\1672\', 'κ').
1597 x_string_escape_map('\1673\', 'λ').
1598 x_string_escape_map('\1674\', 'μ').
1599 x_string_escape_map('\1675\', 'ν').
1600 x_string_escape_map('\1676\', 'ξ').
1601 x_string_escape_map('\1677\', 'ο').
1602 x_string_escape_map('\1700\', 'π').
1603 x_string_escape_map('\1701\', 'ρ').
1604 x_string_escape_map('\1702\', 'ς').
1605 x_string_escape_map('\1703\', 'σ').
1606 x_string_escape_map('\1704\', 'τ').
1607 x_string_escape_map('\1705\', 'υ').
1608 x_string_escape_map('\1706\', 'φ').
1609 x_string_escape_map('\1707\', 'χ').
1610 x_string_escape_map('\1710\', 'ψ').
1611 x_string_escape_map('\1711\', 'ω').
1612
1613 % to do: add missing upper-case Greek letters:
1614 x_string_escape_map('\1624\', 'Δ').
1615 x_string_escape_map('\1630\', 'Θ').
1616 x_string_escape_map('\1633\', 'Λ').
1617 x_string_escape_map('\1636\', 'Ξ').
1618 x_string_escape_map('\1645\', 'Υ').
1619 x_string_escape_map('\1647\', 'Χ').
1620 x_string_escape_map('\1650\', 'Ψ').
1621 x_string_escape_map('\1651\', 'Ω').
1622
1623 % other symbols (converted using http://www.online-toolz.com/tools/unicode-html-entities-convertor.php )
1624 x_string_escape_map('\21242\','⊢'). %vdash turnstyle decimal: 8866
1625 x_string_escape_map('\21250\','⊨'). %models turnstyle decimal: 8872
1626 x_string_escape_map('\x21D4\','⇔'). % equivalence
1627 x_string_escape_map('\x21D2\','⇒'). % implication
1628 x_string_escape_map('\x2203\','∃'). % exists
1629 x_string_escape_map('\x2200\','∀'). % forall
1630 x_string_escape_map('ยท','·'). % dot used for quantifiers, ASCII 183
1631 x_string_escape_map('\x2227\','∧'). % conjunct
1632 x_string_escape_map('\x2228\','∨'). % disjunct
1633 x_string_escape_map('\xAC\','¬'). % negation
1634 x_string_escape_map('\x21A6\','↦'). % maplet |->
1635 x_string_escape_map('\x2286\','⊆'). % <: subseteq
1636 x_string_escape_map('\x222A\','∪'). % union
1637 x_string_escape_map('\x2229\','∩'). % intersection
1638 x_string_escape_map('\x2205\','∅'). % empty set
1639 x_string_escape_map('\x2260\','≠'). % not equal
1640 x_string_escape_map('\x2264\','≤'). % less equal
1641 x_string_escape_map('\x2265\','≥'). % greater equal
1642 x_string_escape_map('\x2124\','ℤ'). % Z (INTEGER)
1643 x_string_escape_map('\x2115\','ℕ'). % NATURAL
1644
1645 % Numbers without HTML translation: .. 8229
1646
1647 % translate unknown unicode chars to lozenge
1648 x_string_escape_map(Unicode, Result) :- atom(Unicode),
1649 atom_codes(Unicode,[Nr]), Nr>127,
1650 !,
1651 ajoin(['&#',Nr,';'],Result).
1652 %x_string_escape_map(Unicode, '◊') :-
1653 % atom(Unicode), atom_codes(Unicode,[Code]), Code>127.
1654 % format(user_output,'Uni: ~w ~n',[Unicode]).
1655 x_string_escape_map(X, X).
1656
1657 %
1658 % split_list(Pred,List,ListA,ListB):
1659 % List contains exactly the same elements as ListA and ListB
1660 % An element E is member of ListA iff Pred(E) is true and E is element of List.
1661 % An element E is member of ListB iff Pred(E) is false and E is element of List.
1662 % combination of include/exclude from library(lists) (include_exclude)
1663 :- assert_must_succeed(( split_list(number,[1,a,2,b],S,F), S==[1,2], F==[a,b] )).
1664 split_list(Pred,List,A,B) :-
1665 split_list2(List,Pred,A,B).
1666 split_list2([],_Pred,[],[]).
1667 split_list2([Elem|Rest],Pred,A,B) :-
1668 ? ( call(Pred,Elem) -> A=[Elem|AR], B=BR
1669 ; A=AR, B=[Elem|BR]),
1670 split_list2(Rest,Pred,AR,BR).
1671
1672
1673 :- assert_must_succeed(( map_split_list(just_for_unit_test_add(0),[1,2,3],S,F), S==[10,20,30], F==[] )).
1674 % like map_list but put unsuccessful elements in a second list
1675 map_split_list(Pred,List,A,B) :-
1676 map_split_list2(List,Pred,A,B).
1677 map_split_list2([],_Pred,[],[]).
1678 map_split_list2([Elem|Rest],Pred,A,B) :-
1679 ( call(Pred,Elem,Res) -> A=[Res|AR], B=BR
1680 ; A=AR, B=[Elem|BR]),
1681 map_split_list2(Rest,Pred,AR,BR).
1682
1683 % a variation of split_list which also returns a list of predicate results
1684 % with re_split_list_idx(L,PredResult,A,B) : we can split another list using the same pattern
1685 split_list_idx(Pred,List,PredResult,A,B) :-
1686 split_list_idx2(List,Pred,PredResult,A,B).
1687 split_list_idx2([],_Pred,[],[],[]).
1688 split_list_idx2([Elem|Rest],Pred,[PredTrue|PT],A,B) :-
1689 (call(Pred,Elem) -> PredTrue=true, A=[Elem|AR], B=BR
1690 ; PredTrue=false, A=AR, B=[Elem|BR]),
1691 split_list_idx2(Rest,Pred,PT,AR,BR).
1692
1693
1694 re_split_list_idx([],[],[],[]).
1695 re_split_list_idx([Elem|Rest],[PredTrue|PT],A,B) :-
1696 (PredTrue=true -> A=[Elem|AR], B=BR
1697 ; A=AR, B=[Elem|BR]),
1698 re_split_list_idx(Rest,PT,AR,BR).
1699
1700
1701
1702 % try and avoid going through same transitions twice
1703 % works with simple transition ids, or with atom/3 entries from ltl model_checker
1704 :- assert_must_succeed((minimize_lasso([0,1,2,4,8,14,7,12],[15,4,8,14,7,12],P,L),
1705 P==[0,1,2], L==[4,8,14,7,12,15])).
1706 minimize_lasso(Prefix,Loop,NewPrefix,NewLoop) :- reverse(Prefix,RP), reverse(Loop,RL),
1707 common_prefix(RP,RL,Common,RestP,RestLoop),
1708 append(RestLoop,Common,NewLR), reverse(NewLR,NewLoop),
1709 reverse(RestP,NewPrefix).
1710 common_prefix([H|T1],[H|T2],[H|Res],Rest1,Rest2) :- !, common_prefix(T1,T2,Res,Rest1,Rest2).
1711 common_prefix(T1,T2,[],T1,T2).
1712
1713
1714
1715 just_for_unit_test_add(A,B,C) :- C is A+(10*B).
1716 :- assert_must_succeed(( foldl(just_for_unit_test_add,[],0,R), R==0 )).
1717 :- assert_must_succeed(( foldl(just_for_unit_test_add,[3,6,7,2,6],0,R), R==36726 )).
1718
1719 foldl(MPred,List,Start,Result) :-
1720 foldl2(List,MPred,Start,Result).
1721 foldl2([],_Pred,Value,Value).
1722 foldl2([Elem|Rest],MPred,OldValue,NewValue) :-
1723 call(MPred,Elem,OldValue,Value),
1724 foldl2(Rest,MPred,Value,NewValue).
1725
1726
1727 just_for_unit_test_add2(A,B,C,D) :- D is 100*C+10*A+B.
1728 :- assert_must_succeed(( foldl(just_for_unit_test_add2,[],[],0,R), R==0 )).
1729 :- assert_must_succeed(( foldl(just_for_unit_test_add2,[3,6,7,2,6],[5,2,9,0,8],0,R), R==3562792068 )).
1730
1731 foldl(MPred,List,List1,Start,Result) :-
1732 foldl2(List,MPred,List1,Start,Result).
1733 foldl2([],_Pred,[],Value,Value).
1734 foldl2([Elem|Rest],MPred,[H1|R1],OldValue,NewValue) :-
1735 call(MPred,Elem,H1,OldValue,Value),
1736 foldl2(Rest,MPred,R1,Value,NewValue).
1737
1738
1739 just_for_unit_test_add3(A,B,C,D,E) :- E is D*1000+100*A+10*B+C.
1740 :- assert_must_succeed(( foldl(just_for_unit_test_add3,[],[],[],0,R), R==0 )).
1741 :- assert_must_succeed(( foldl(just_for_unit_test_add3,[3,6,7],[5,2,9],[4,1,0],0,R),
1742 R==354621790 )).
1743
1744 foldl(MPred,A,B,C,Start,Result) :-
1745 foldl2(A,MPred,B,C,Start,Result).
1746 foldl2([],_Pred,[],[],Value,Value).
1747 foldl2([Elem|Rest],MPred,[H1|R1],[H2|R2],OldValue,NewValue) :-
1748 call(MPred,Elem,H1,H2,OldValue,Value),
1749 foldl2(Rest,MPred,R1,R2,Value,NewValue).
1750
1751
1752 :- assert_must_succeed(( maplist5(just_for_unit_test_add2,[],[],[],R), R==[] )).
1753 :- assert_must_succeed(( maplist5(just_for_unit_test_add2,[1],[2],[3],R), R==[312] )).
1754 :- assert_must_succeed(( maplist5(just_for_unit_test_add2,[1,1],[2,0],[3,0],R), R==[312,10] )).
1755
1756 maplist5(_P,[],[],[],[]).
1757 maplist5(P,[H1|T1],[H2|T2],[H3|T3],[H4|T4]) :-
1758 if(call(P,H1,H2,H3,H4),
1759 ? maplist5(P,T1,T2,T3,T4),
1760 (add_internal_error('Call fails: ',maplist5(P,H1,H2,H3,H4)),
1761 fail)).
1762
1763
1764 :- assert_must_succeed(( average([2,4,8,10],Avg), D is abs(Avg-6),D<0.001 )).
1765 :- assert_must_succeed(( average([2],Avg), D is abs(Avg-2), D<0.001 )).
1766 average(List,Avg) :-
1767 length(List,N),sumlist(List,Sum),Avg is Sum/N.
1768
1769
1770 % assert_once works like assertz, but checks if the fact has already been stored before and
1771 % will not store it a second time
1772 assert_once(MPredicate) :-
1773 (call(MPredicate) -> true ; assertz(MPredicate)).
1774
1775
1776
1777 :- dynamic id_counter/1.
1778 unique_id(Prefix,Id) :-
1779 (id_counter(V) -> retractall(id_counter(_)) ; V is 0),
1780 N is V+1,
1781 assertz( id_counter(N) ),
1782 number_codes(N,NCodes),
1783 append(Prefix,NCodes,ICodes),
1784 atom_codes(Id,ICodes).
1785
1786 % PROBPATH is the runtime search path for defintion files not found relative to the original machine.
1787 % By default this is the stdlib directory relative to the prob base dir.
1788 % The user can provide a list of : separated directories in the PROBPATH
1789 % environment variables which are prepended to the default path.
1790 get_PROBPATH(PROBPATH) :-
1791 environ('PROBPATH', CustomPATH),
1792 atom_length(CustomPATH, L),
1793 L > 0, !,
1794 get_path_separator(PS),
1795 get_stdlib_path(STDLIB), ajoin([CustomPATH, PS, STDLIB], PROBPATH).
1796
1797 get_PROBPATH(PROBPATH) :- get_stdlib_path(PROBPATH).
1798
1799 get_stdlib_path(STDLIB) :- runtime_application_path(Base), atom_concat(Base, '/stdlib', STDLIB).
1800
1801 % Platform specific path separator char
1802 map_path_separator(windows, ';').
1803 map_path_separator(_, ':').
1804
1805 get_path_separator(PS) :- host_platform(Platform), map_path_separator(Platform, PS), !.
1806
1807 %% atom_to_number(?Atom, ?Number).
1808 atom_to_number(Atom, Number) :-
1809 atom(Atom),
1810 catch((
1811 atom_codes(Atom, Codes),
1812 number_codes(Number, Codes)
1813 ), _, fail).
1814 atom_to_number(Atom, Number) :-
1815 number(Number),
1816 number_codes(Number, Codes),
1817 atom_codes(Atom, Codes).
1818
1819 % ----------
1820
1821 % useful for e.g. SWI Prolog where redefine_warnings is not defined
1822 get_set_optional_prolog_flag(Flag,Old,New) :-
1823 (catch(current_prolog_flag(Flag, Old), error(domain_error(_, _), _), fail) ->
1824 set_prolog_flag(Flag, New)
1825 ;
1826 current_prolog_flag(dialect, Prolog),
1827 format('Prolog flag ~w not supported on ~w~n', [Flag, Prolog])
1828 ).
1829
1830
1831 % ----------
1832
1833 % predicates for lists with optional items represented using optional_value(V,pred_true/pred_false)
1834 % we assume that optional values constructors (optional_value/2) are instantiated *before* calling maplist_optional
1835
1836 ?map_optlist(Pred,List) :- map_optlist_aux(List,Pred).
1837
1838 :- block map_optlist_aux(-,?).
1839 map_optlist_aux([],_) :- !.
1840 map_optlist_aux([H|T],Pred) :- !,
1841 ? call_optional(Pred,H),
1842 ? map_optlist_aux(T,Pred).
1843 map_optlist_aux(Other,Pred) :-
1844 add_internal_error('First argument not a list:',map_optlist_aux(Other,Pred)).
1845
1846 call_optional(Pred,OptVal) :-
1847 is_optional_value(OptVal,Val,Use),
1848 !,
1849 call_optional_aux(Use,Pred,Val).
1850 ?call_optional(Pred,Val) :- call(Pred,Val).
1851
1852 :- block call_optional_aux(-,?,?).
1853 call_optional_aux(pred_true,Pred,Val) :- !, call(Pred,Val).
1854 call_optional_aux(pred_false,_,_) :- !. % ignore optional item
1855 call_optional_aux(Other,Pred,_) :-
1856 add_internal_error('First argument not a BOOL:',call_optional_aux(Other,Pred)).
1857
1858 :- block optlist_to_list(-,?).
1859 optlist_to_list([],R) :- !, R=[].
1860 optlist_to_list([OptVal|T],R) :- !,
1861 (is_optional_value(OptVal,Val,Use)
1862 -> optlist_to_list_aux(Use,Val,T,R)
1863 ; R = [OptVal|RT], optlist_to_list(T,RT)
1864 ).
1865 optlist_to_list(Other,R) :-
1866 add_internal_error('First argument not a list:',optlist_to_list(Other,R)),
1867 R=Other.
1868
1869 :- block optlist_to_list_aux(-,?,?,?).
1870 optlist_to_list_aux(pred_true,Val,T,[Val|TR]) :- !, optlist_to_list(T,TR).
1871 optlist_to_list_aux(pred_false,_,T,R) :- !, optlist_to_list(T,R).
1872 optlist_to_list_aux(Other,V,T,R) :-
1873 add_internal_error('First argument not a BOOL:',optlist_to_list_aux(Other,V,T,R)),
1874 fail.
1875
1876 is_optional_value(OptVal,Val,Use) :- nonvar(OptVal), OptVal = optional_value(Val,Use).
1877
1878 % ---------
1879
1880 % blackboard utilities
1881
1882
1883 bb_safe_get(Counter,R) :- (bb_get(Counter,X) -> R=X ; R=0).
1884
1885 bb_inc(Counter) :- bb_inc_by(Counter,1).
1886
1887 bb_inc_by(Counter,Inc) :-
1888 bb_safe_get(Counter,R),
1889 R1 is R+Inc, bb_put(Counter,R1).
1890
1891
1892 % ---------
1893
1894
1895 :- if(current_prolog_flag(dialect, swi)).
1896
1897 :- use_module(library(ugraphs),[top_sort/2]).
1898
1899 % this version fails if there are cycles and cannot report the number of unsorted nodes:
1900 top_sort(Graph,Sorted,UnsortedNr) :- top_sort(Graph, Sorted), UnsortedNr=0.
1901
1902 % disable code below currently for SWI, as top_sort below calls internal predicate of ugraphs: fanin_counts
1903 :- else.
1904 :- use_module(library(avl),[ord_list_to_avl/2]).
1905
1906 % a slight variation of top_sort from library(ugraphs) which allows the sorting to be not completed
1907 % top_sort(G,S,0) corresponds to top_sort in ugraphs
1908 top_sort(Graph,Sorted,UnsortedNr) :-
1909 ugraphs:fanin_counts(Graph, Counts),
1910 ugraphs:get_top_elements(Counts, Top, 0, I),
1911 ord_list_to_avl(Counts, Map),
1912 top_sort_aux(Top, I, Map, Sorted,UnsortedNr).
1913
1914 top_sort_aux([], I, _, [], UnsortedNr) :- UnsortedNr = I.
1915 top_sort_aux([V-VN|Top0], I, Map0, [V|Sorted],UnsortedNr) :-
1916 ugraphs:dec_counts(VN, I, J, Map0, Map, Top0, Top),
1917 top_sort_aux(Top, J, Map, Sorted,UnsortedNr).
1918 :- endif.