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