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