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