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