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(error_manager,[init_error_manager/0,
7 add_warning/2, add_warning/3, add_warning/4,
8 reset_errors/0, clear_wd_errors/0,
9 add_error/2, add_error/3, add_error/4,
10 add_error_and_fail/3, add_error_and_fail/2,
11 add_error_fail/3,
12 add_failed_call_error/1, add_internal_error/2, add_internal_error/4,
13 register_optional_error_or_warning/1, reset_optional_errors_or_warnings/0,
14 assert_true/1,
15 add_debug_message/3, add_debug_message/4,
16 add_message/2, add_message/3, add_message/4,
17 add_all_perrors/1, add_all_perrors/2, add_all_perrors/3,
18 get_perror/4,
19 no_real_perror_occurred/1,
20 get_all_errors/1, tcltk_get_all_errors/4,
21 get_tk_table_position_info/2,
22 get_all_errors_and_reset/1, % call if you want to start with a fresh top-level error scope
23 get_all_errors_with_span_info_and_reset/1, % ditto + obtain location info; excludes messages
24 get_all_errors_and_clear/1,
25 get_error/2, get_error_with_span/3,
26 get_warning/2, check_error_occured/2, check_warning_occured/2,
27 get_error_span_linecol/5, get_error_span_linecol/4,
28 simplify_span/2,
29 tk_get_error_span_linecol_for_main_file/4,
30 register_error_span/2,
31 check_error_span_file_linecol/6,
32 position_is_not_in_main_file/1,
33 error_or_warning_occured/0,
34 real_error_occurred/0, reset_real_error_occurred/0, assert_real_error_occurred/1,
35 warning_occurred/0, % true if a warning was raised
36 wd_error_occured/0,
37 test_error_occurred/1, count_errors_occurred/2,
38 get_total_number_of_errors/1,
39 reset_error_spans/0,
40
41 backup_errors/0, backed_up_error/4,
42
43 set_error_context/1, clear_error_context/0,
44 get_error_context/1, restore_error_context/1,
45 print_error_context/0,
46
47 extract_span_description/2, extract_symbolic_label_pos/2, extract_symbolic_label/2,
48 extract_line_col/5, extract_file_line_col/6,
49 extract_all_line_col/5,
50 extract_line_col_for_main_file/5,
51 extract_subsidiary_tail_file_name/2, extract_tail_file_name/2,
52 extract_file_number_and_name/3,
53 extract_additional_description/2, extract_pos_context/4,
54 print_error_span/1, print_message_span/1,
55
56 turn_show_error_source_on/0, turn_show_error_source_off/0,
57
58 enter_new_error_scope/1, enter_new_error_scope/2,
59 enter_new_clean_error_scope/1,
60 get_current_error_scope/1,
61 exit_error_scope/2, exit_error_scope/3,
62 error_occurred_at_level/1, specific_event_occurred_at_level/2,
63 %throw_errors_in_scope/3,
64 add_new_event_in_error_scope/1, add_new_event_in_error_scope/2,
65 event_occurred_in_error_scope/1, error_occurred_in_error_scope/0,
66 clear_events_in_error_scope/2, clear_events_in_current_error_scope/1,
67 translate_error_event/2,
68 clear_enumeration_warning_in_error_scope/1,
69 clear_all_errors_in_error_scope/1,
70 call_in_fresh_error_scope_for_one_solution/1,
71 enumeration_warning_occured_in_error_scope/0,
72 is_enumeration_warning_exception/1,
73 abort_error_occured_in_error_scope/0,
74 on_enumeration_warning/2, on_enumeration_warning_with_continue/3,
75 throw_enumeration_warnings_in_current_scope/0,
76 throw_enumeration_warnings_in_scope/3,
77 catch_enumeration_warning_exceptions/2, catch_enumeration_warning_exceptions/3,
78 catch_enumeration_warning_exceptions/4, catch_enumeration_warning_exceptions_and_wd_failures/5,
79 call_with_enumeration_warning/1,
80 observe_enumeration_warnings/2,
81 critical_enumeration_warning_occured_in_error_scope/4,
82 critical_enumeration_warning_occured_in_error_scope/0,
83 virtual_time_out_occured_in_error_scope/1, % variation which returns a virtual_time_out(.) term
84 clear_enumeration_warnings/0,
85 translate_events_in_current_scope_to_warnings/2,
86 time_out_with_enum_warning_one_solution/3, % use this for finding one solution
87 time_out_with_enum_warning_one_solution/4,
88 time_out_with_enum_warning_one_solution_no_new_error_scope/3,
89 is_time_out_result/1,
90 time_out_with_enum_warning_for_findall/3, % use this if you cycle through all solutions
91 time_out_with_enum_warning_for_findall_in_current_error_scope/4,
92 get_virtual_time_out_from_exception/2, % used by time_out_with_enum_warning_for_findall
93 clpfd_overflow_msg/1,
94 is_clpfd_overflow_representation_error/2, is_clpfd_overflow_representation_error_msg/1,
95 logged_error/4,
96 display_error_statistics/0,
97 set_error_manager_silent_mode/1
98 ]).
99
100 % meta_predicate annotations should appear before loading any code:
101 :- meta_predicate add_failed_call_error(0).
102 :- meta_predicate add_internal_error(-,:).
103 :- meta_predicate add_new_event_in_error_scope(-,2).
104
105 :- meta_predicate on_enumeration_warning(0,0).
106 :- meta_predicate on_enumeration_warning_with_continue(0,0,0).
107
108 :- meta_predicate catch_enumeration_warning_exceptions(0,0).
109 :- meta_predicate catch_enumeration_warning_exceptions(0,0,-).
110 :- meta_predicate catch_enumeration_warning_exceptions(0,0,-,-).
111 :- meta_predicate catch_enumeration_warning_exceptions_and_wd_failures(0,0,-,0,-).
112
113 :- meta_predicate observe_enumeration_warnings(0,0).
114
115 :- meta_predicate time_out_with_enum_warning_one_solution(0,-,-).
116 :- meta_predicate time_out_with_enum_warning_one_solution(0,-,-,-).
117
118 :- meta_predicate call_in_fresh_error_scope_for_one_solution(0).
119
120 :- meta_predicate call_with_enumeration_warning(0).
121
122 :- meta_predicate time_out_with_enum_warning_one_solution_no_new_error_scope(0,-,-).
123
124 :- meta_predicate time_out_with_enum_warning_for_findall(0,-,-).
125 :- meta_predicate time_out_with_enum_warning_for_findall2(-,0,-,-).
126
127 :- meta_predicate time_out_with_enum_warning_for_findall_in_current_error_scope(-,0,-,-).
128
129 :- meta_predicate assert_true(0).
130 :- meta_predicate catch_wd(-,0,-).
131
132 % ------------
133
134 :- use_module(library(lists)).
135
136 :- use_module(tools,[get_tail_filename/2]).
137 :- use_module(tools_lists,[count_occurences/2]).
138 :- use_module(tools_printing,[print_error/1,print_message_on_stream/3,format_error_with_nl/2,format_with_colour/4]).
139 :- use_module(tools_strings,[ajoin/2, string_concatenate/3]).
140
141 :- use_module(module_information,[module_info/2]).
142 :- module_info(group,infrastructure).
143 :- module_info(description,'The error_manager controls error messages. Error messages can be added, retrieved, counted,etc. The module also takes care of extracting source spans from error messages.').
144
145 %:- use_module(translate).
146 :- use_module(debug, [debug_mode/1, debug_println/1, debug_println/2, debug_format/3]).
147 :- use_module(preferences,[get_preference/2,reset_temporary_preference/2,
148 temporary_set_preference/3]).
149
150
151 :- use_module(extension('counter/counter'),
152 [counter_init/0, new_counter/1, get_counter/2, inc_counter/2, set_counter/2]).
153
154 % cur_block_level is now stored as a C counter, which needs to be initialised
155 init_error_manager :- counter_init, new_counter(cur_block_level).
156
157
158 :- dynamic optional_error_or_warning/1.
159 register_optional_error_or_warning(Type) :-
160 (optional_error_or_warning(Type) -> true ; assertz(optional_error_or_warning(Type))).
161 reset_optional_errors_or_warnings :- retractall(optional_error_or_warning(_)).
162
163 % INTERNAL ERRORS
164
165
166 add_failed_call_error(Call) :- !,
167 add_internal_error('Internal Error; call failed: ',Call).
168
169 add_internal_error(Module,Msg,Term,Span) :-
170 add_error(internal_error(Module),Msg,Term,Span).
171 add_internal_error(Msg,Module:Call) :- !,
172 add_error(internal_error(Module),Msg,Call).
173 add_internal_error(Msg,Call) :-
174 add_error(internal_error(unknown_module),Msg,Call).
175
176
177 % ERROR SCOPING
178
179 %:- dynamic cur_block_level/1.
180 %cur_block_level(0). % no realised as a C counter
181 :- volatile error_occurred_at_level/1.
182 :- dynamic error_occurred_at_level/1.
183 :- volatile throw_error/3.
184 :- dynamic throw_error/3.
185 :- volatile do_not_print_error/2.
186 :- dynamic do_not_print_error/2.
187
188
189 get_current_error_scope(Level) :- get_counter(cur_block_level,Level).
190
191 enter_new_error_scope(Level,_PP) :-
192 enter_new_error_scope(Level). %, tools_printing:print_term_summary(enter(Level,PP)),nl.
193 enter_new_error_scope(Level) :-
194 enter_new_clean_error_scope(Level),
195 L1 is Level - 1,
196 copy_throw_errors(L1,Level).
197 copy_throw_errors(L1,L) :-
198 ? throw_error(L1,Error,Span), %print(copy(throw(L1,L,Error))),nl,
199 assertz(throw_error(L,Error,Span)),fail.
200 copy_throw_errors(L1,L) :-
201 do_not_print_error(L1,Error),
202 assertz(do_not_print_error(L,Error)),fail.
203 copy_throw_errors(_,_).
204 enter_new_clean_error_scope(Level) :-
205 inc_counter(cur_block_level,L1),
206 (retract(throw_error(L1,_,_)) -> retractall(throw_error(L1,_,_)) ; true), % DO WE NEED THIS ??
207 (retract(do_not_print_error(L1,_)) -> retractall(do_not_print_error(L1,_)) ; true),
208 % print(enter(L1)),nl,trace,
209 Level=L1.
210
211
212 % mark that everything unifying with Error should be thrown rather than collected
213 throw_errors_in_scope(Level,Error,Span) :-
214 (\+ throw_error(Level,Error,Span) % TO DO: check that we are an instance of existing error !
215 -> assertz(throw_error(Level,Error,Span))
216 ; true).
217
218 % state that this event/error should not be printd
219 silent_enum_warnings_in_scope(Level,Critical) :-
220 Error = enumeration_warning(_,_,_,_,Critical),
221 assertz(do_not_print_error(Level,Error)).
222
223 clear_all_errors_in_error_scope(Level) :- %print(clearing(Level)),nl,
224 clear_events_in_error_scope(Level,_),
225 error_occurred_at_level(L1), L1>Level, %print(clearing(L1)),nl,
226 clear_events_in_error_scope(Level,_),fail.
227 clear_all_errors_in_error_scope(_).
228
229 % useful in call_cleanup; when error block may already be exited
230 exit_error_scope_if_necessary(Level,PP) :- get_counter(cur_block_level,CurLevel),
231 (Level =< CurLevel
232 -> exit_error_scope(Level,_,PP) %,print(exit(Level,CurLevel,PP)),nl
233 ; true).
234
235 exit_error_scope(Level,ErrorOcc) :- exit_error_scope(Level,ErrorOcc,unknown).
236 exit_error_scope(Level,ErrorOcc,PP) :- get_counter(cur_block_level,CurL),
237 (CurL = Level -> NewL is CurL-1
238 ; Level < CurL -> NewL is Level-1,
239 %print_error_scopes,
240 format('*** exiting multiple error blocks (~w -> ~w) for ~w ***~n',[CurL,NewL,PP])
241 ; format('*** block ~w already exited (currently at ~w) for ~w ***~n',[Level,CurL,PP]),
242 NewL is CurL
243 ), set_counter(cur_block_level,NewL),
244 copy_error_scope_events(CurL,NewL),
245 ? (retract(throw_error(CurL,_,_)) -> retractall(throw_error(CurL,_,_)) ; true),
246 (retract(do_not_print_error(CurL,_)) -> retractall(do_not_print_error(CurL,_)) ; true),
247 (retract(error_occurred_at_level(CurL))
248 -> ErrorOcc=true,
249 (error_occurred_at_level(NewL) -> true ; assertz(error_occurred_at_level(NewL)))
250 ; ErrorOcc=false).
251 %indent(Level), format('exit level ~w for ~w, cur level ~w, error occ = ~w~n',[Level,PP,CurL,ErrorOcc]).
252
253
254 % versions of enter_new_error_scope and exit_error_scope which re_enter blocks and clean up upon backtracking
255 %enter_new_error_scope_bt(Level,PP) :- enter_new_error_scope(Level,PP), exit_upon_fail(Level,PP).
256 %exit_upon_fail(_,_).
257 %exit_upon_fail(Level,PP) :- print(exit_upon_backtrack(Level,PP)),nl,
258 % exit_error_scope(Level,_,PP),fail.
259 %
260 %exit_error_scope_bt(Level,ErrorOcc,PP) :- exit_error_scope(Level,ErrorOcc,PP).
261 %exit_error_scope_bt(Level,_ErrorOcc,PP) :- print(re_enter_block(Level,PP)),nl,
262 % enter_new_error_scope(Level2,PP),
263 % (Level2=Level -> true ; print(mismatch_when_reentering_block(Level,PP)),nl),
264 % fail.
265
266 % ---------------------------
267
268
269
270 assert_real_error_in_current_block(Source) :- get_counter(cur_block_level,L),L>0,
271 %print(assert_real_error_in_current_block(L)),nl,
272 (specific_event_occurred_at_level(L,Source) -> true
273 ; assertz(specific_event_occurred_at_level(L,Source))), % ensures that clear_events_in_current_error_scope does not remove error_occurred_at_level if used for enumeration warnings, ...
274 \+ error_occurred_at_level(L), assertz(error_occurred_at_level(L)),!.
275 assert_real_error_in_current_block(_).
276
277
278 reset_error_scopes :-
279 (set_counter(cur_block_level,0) -> true
280 ; format(user_error,'~n*** set_counter(cur_block_level,0) failed!!~n',[]),fail
281 ), % try debug random gitlab failures; something really bad happened
282 retractall(error_occurred_at_level(_)),
283 retractall(specific_event_occurred_at_level(_,_)).
284
285 % for debugging / portraying error scopes:
286 % portray_error_scopes
287 :- public print_error_scopes/0.
288 print_error_scopes :-
289 if(get_counter(cur_block_level,L),
290 format(' Cur Block Level = ~w~n',[L]),
291 format(' *** NO Cur Block Level Information !!',[])
292 ),
293 fail.
294 print_error_scopes :-
295 findall(L,error_occurred_at_level(L),LL),
296 format(' Errors occured at those levels: ~w~n',[LL]),
297 format(' Specific events at levels:~n',[]),
298 specific_event_occurred_at_level(Level,Err),
299 format(' ~w --> ~w~n',[Level,Err]),
300 fail.
301 print_error_scopes.
302
303 % call a predicate in fresh error scope (assuming one solution is searched for only; failure is also ok)
304 % and then discard all errors
305 call_in_fresh_error_scope_for_one_solution(Call) :-
306 enter_new_error_scope(Level,call_in_fresh_error_scope_for_one_solution),
307 call_cleanup(Call,
308 (clear_all_errors_in_error_scope(_),
309 exit_error_scope(Level,_,call_in_fresh_error_scope_for_one_solution))).
310
311 :- volatile specific_event_occurred_at_level/2.
312 :- dynamic specific_event_occurred_at_level/2.
313
314 % can be used to keep track of whether specific events occurred within an error_scope
315 add_new_event_in_error_scope(Event) :-
316 add_new_event_in_error_scope(Event,do_nothing).
317 do_nothing(_,_).
318 add_new_event_in_error_scope(Event,PrintMessageCall) :-
319 get_counter(cur_block_level,L),
320 ? (specific_event_occurred_at_level(L,Event) -> fail
321 ; (throw_error(L,Event,Span)
322 -> (debug_mode(off) -> true ; print_message(informational,throwing(Event))), % trace, % <---
323 (do_not_print_error(L,Event), debug_mode(off) -> true ; call(PrintMessageCall,throwing,Span)),
324 % Note: event is not asserted ! See e.g. tests 1089, 1519, 1522, 1661, 1199, 1291, ...
325 throw(Event)
326 ; assertz(specific_event_occurred_at_level(L,Event)),
327 (do_not_print_error(L,Event), debug_mode(off) -> true ; call(PrintMessageCall,not_throwing,unknown))
328 )
329 ).
330
331 % call if you just want to add the error information; without throwing
332 assert_event_in_error_scope_without_throw(Event) :- get_counter(cur_block_level,L),
333 (specific_event_occurred_at_level(L,Event) -> true
334 ; assertz(specific_event_occurred_at_level(L,Event))).
335
336 error_occurred_in_error_scope :- get_counter(cur_block_level,L),error_occurred_at_level(L).
337 ?event_occurred_in_error_scope(Event) :- get_counter(cur_block_level,L),specific_event_occurred_at_level(L,Event).
338
339 copy_error_scope_events(FromLevel,ToLevel) :- retract(specific_event_occurred_at_level(FromLevel,Event)),
340 \+ specific_event_occurred_at_level(ToLevel,Event),
341 % print(copying_event(FromLevel,ToLevel,Event)),nl,
342 assertz(specific_event_occurred_at_level(ToLevel,Event)), % should we throw if this level demands it ?
343 (throw_error(ToLevel,Event,_Span)
344 -> debug_println(20,throw_copied_event(Event)), throw(Event)),
345 fail.
346 copy_error_scope_events(_,_).
347
348 clear_events_in_current_error_scope(Event) :- get_counter(cur_block_level,L),clear_events_in_error_scope(L,Event).
349
350 %clear_events_in_error_scope(L,Event) :-retract(specific_event_occurred_at_level(L,Event)), print(retract(L,Event)),nl,fail.
351
352 clear_enumeration_warning_in_error_scope(Level) :-
353 clear_events_in_error_scope(Level,enumeration_warning(_,_,_,_,_)).
354
355 clear_events_in_error_scope(L,Event) :-
356 ? (specific_event_occurred_at_level(L,_)
357 -> retractall(specific_event_occurred_at_level(L,Event)),
358 (specific_event_occurred_at_level(L,_) -> true % we have not removed all events
359 ; retract(error_occurred_at_level(L)) -> true
360 ; true
361 )
362 ; true). % no errors can have been there
363
364 throw_enumeration_warnings_in_current_scope :-
365 get_counter(cur_block_level,L), throw_enumeration_warnings_in_scope(L,_,unknown).
366
367 throw_enumeration_warnings_in_scope(Level,Critical,Span) :-
368 simplify_span(Span,SimplifiedSpan), % relevant for test 1562
369 throw_errors_in_scope(Level,enumeration_warning(_,_,_,_,Critical),SimplifiedSpan).
370
371 on_enumeration_warning(Call, BackupCall) :-
372 ? on_enumeration_warning_with_continue(Call, BackupCall, true).
373 % sets up a new error scope and forces enumeration_warnings to be thrown
374 % if an enumeration_warning happens the BackupCall is executed
375 on_enumeration_warning_with_continue(Call, _, _) :- is_true_call(Call),!. % happens e.g., for card_for_specific_closure3
376 on_enumeration_warning_with_continue(Call, BackupCall, TrueContinuation) :-
377 enter_new_error_scope(Level,on_enumeration_warning_with_continue),
378 throw_enumeration_warnings_in_scope(Level,_,unknown),
379 ? call_cleanup(
380 catch(
381 if(Call,
382 (exit_error_scope(Level,_,on_enumeration_warning_with_continue_true),
383 % TODO: we need a version that re-instates error_scope upon backtracking?!
384 call(TrueContinuation)),
385 (exit_error_scope(Level,_,on_enumeration_warning_with_continue_false),fail)
386 ),
387 Exc,
388 (exit_error_scope(Level,_,on_enumeration_warning_with_continue_exception), % We do not catch timeouts
389 (Exc=enumeration_warning(_,_,_,_,_) -> call(BackupCall) ; throw(Exc))
390 )
391 ),
392 exit_error_scope_if_necessary(Level,on_enumeration_warning_with_continue_timeout) % TIMEOUT
393 ).
394
395 % check if we are simply calling on_enumeration_warning with trivial true call; avoid call_cleanup, error_scope.
396 is_true_call(_:X) :- !, nonvar(X), is_true_call(X).
397 is_true_call(call(X)) :- !, is_true_call(X).
398 is_true_call(true).
399
400 catch_enumeration_warning_exceptions(Call, BackupCall) :-
401 catch_enumeration_warning_exceptions_and_wd_failures(Call,BackupCall,false,fail,unknown).
402 catch_enumeration_warning_exceptions(Call, BackupCall, AddAsEventError) :-
403 catch_enumeration_warning_exceptions_and_wd_failures(Call,BackupCall,AddAsEventError,fail,unknown).
404 catch_enumeration_warning_exceptions(Call, BackupCall, AddAsEventError,Source) :-
405 catch_enumeration_warning_exceptions_and_wd_failures(Call,BackupCall,AddAsEventError,fail,Source).
406
407 % can be used to check if an exception is an enumeration warning
408 is_enumeration_warning_exception(enumeration_warning(_Enumerating,_Type,_Range,_RestrRange,_Critical)).
409
410 % removed usage of call_cleanup; can cause huge runtime in debug_mode, cf SPRM-21383 but also e.g. for ProPlanGross.mch
411 % but simple_call_cleanup requires that C does not backtrack and CleanupCall called in case of exception
412 % does not catch timeouts, relevant for test 2355
413 % but using call_cleanup in SICStus 4.9 for PlanProGross.mch results in timeout after several minutes in setup constants
414 :- meta_predicate simple_call_cleanup(0,0).
415 ?simple_call_cleanup(C,CleanupCall) :- if(C,CleanupCall, (CleanupCall,fail)).
416
417 % AddAsEventError = true means that caught exceptions are added as event_errors in scope
418 % (this can be important if we later want to decide whether an enumeration warning occured)
419 % WDCall: this gets called when a well_definedness_error is raised by the Call
420 % assumes Call does not backtrack to use simple_call_cleanup
421 catch_enumeration_warning_exceptions_and_wd_failures(Call, BackupCall,AddAsEventError,WDCall,Source) :-
422 enter_new_error_scope(Level,catch_enumeration_warning_exceptions),
423 % print(enter(Level)),nl,
424 % difference: we do not force to throw_errors_in_scope
425 (Source = ignore(_) -> silent_enum_warnings_in_scope(Level,critical) ; true),
426 ? catch(
427 simple_call_cleanup(if(Call,true,catch_wd(Level,WDCall,Source)),
428 (%print(exit(Level)),nl,
429 exit_error_scope(Level,_,catch_enumeration_warning_exceptions))),
430 % call_cleanup can be tricky in case of success of Call: the error scope may not be exited immediately; TO DO: maybe rewrite using same style as above (using if + catch)
431 enumeration_warning(A,B,C,D,E),
432 (exit_error_scope(Level,_,catch_enumeration_warning_exceptions), % added due to simple_call_cleanup
433 (AddAsEventError=false
434 -> (Source=ignore(Src)
435 -> debug_format(19,'%%% Ignoring unbounded enumeration warning (source:~w).~n',[Src])
436 ; true)
437 % inform that enum warning was not serious: there is a fall-back solution
438 ; assert_event_in_error_scope_without_throw(enumeration_warning(A,B,C,D,E))),
439 BackupCall)).
440
441 catch_wd(Level,WDCall,Source) :-
442 WDCall \= fail,
443 % print(check_wd(Level,Source)),nl, portray_events_in_error_scope,nl,
444 specific_event_occurred_at_level(Level,well_definedness_error),!,
445 formatsilentmsg(user_output,'%%% well_definedness_error (source:~w).~n',[Source]),
446 call(WDCall).
447 catch_wd(_,_,_) :- fail.
448
449
450 % execute some code when enumeration warning occurs; and then throw exception again
451 observe_enumeration_warnings(Call,ObserverCallToExecute) :-
452 catch(Call, enumeration_warning(A,B,C,D,E),
453 call_cleanup(ObserverCallToExecute, throw(enumeration_warning(A,B,C,D,E)))).
454
455
456 % sets up a new error scope and forces enumeration_warnings to be thrown
457 % the exceptions are not caught !
458 call_with_enumeration_warning(Call) :-
459 enter_new_error_scope(Level,call_with_enumeration_warning),
460 throw_enumeration_warnings_in_scope(Level,_,unknown),
461 call_cleanup(
462 (Call, % the assumption is that Call will only have one solution
463 exit_error_scope(Level,_,call_with_enumeration_warning_true)),
464 exit_error_scope_if_necessary(Level,call_with_enumeration_warning_timeout) % failure, TIMEOUT or Exception
465 ).
466
467
468 % a version of time_out which treats enumeration_warnings like time-outs
469 % and also checks enumeration_warnings in case of failure
470 % assumes we only look for one solution (otherwise error scope cleanup has to be changed !! )
471 time_out_with_enum_warning_one_solution(Call,TO,TimeOutRes,ClearEnumWarnings) :-
472 enter_new_error_scope(Level,time_out_with_enum_warning_one_solution),
473 call_cleanup(
474 catch(
475 time_out_check_enum_warning_for_failure(Call,TO,TimeOutRes,ClearEnumWarnings,perform_cut),
476 enumeration_warning(A,B,C,D,E),
477 % no need to clear: we leave error_scope below
478 TimeOutRes=virtual_time_out(thrown_enumeration_warning(A,B,C,D,E))),
479 exit_error_scope(Level,_,time_out_with_enum_warning_one_solution)).
480
481 % here enumeration warnings are not cleared and propagated to outer error scope
482 time_out_with_enum_warning_one_solution(Call,TO,TimeOutRes) :-
483 time_out_with_enum_warning_one_solution(Call,TO,TimeOutRes,no_clear).
484
485
486 enumeration_warning_occured_in_error_scope :-
487 event_occurred_in_error_scope(enumeration_warning(_,_,_,_,_)).
488
489 abort_error_occured_in_error_scope :-
490 event_occurred_in_error_scope(abort_error(_)). % is this still being generated??
491 abort_error_occured_in_error_scope :-
492 event_occurred_in_error_scope(well_definedness_error).
493
494
495 % just like above; but does not set up new error_scope (for performance) and clears enumeration warnings in case of failure and success
496 time_out_with_enum_warning_one_solution_no_new_error_scope(Call,TO,TimeOutRes) :-
497 (enumeration_warning_occured_in_error_scope
498 -> %trace,
499 format('Events in error block:~n',[]),portray_events_in_error_scope,
500 add_internal_error('Error block already has enumeration warnings',time_out_with_enum_warning_one_solution_no_new_error_scope(Call,TO,TimeOutRes))
501 ; true),
502 % Note: will call safe_time_out which will not call time_out when time_out_preference_disabled / disable_time_out
503 catch(
504 time_out_check_enum_warning_for_failure(Call,TO,TimeOutRes,clear_errors,perform_cut), % clear errors so we can continue using same error scope
505 enumeration_warning(A,B,C,D,E),
506 %% (print(enum_warning),nl,TimeOutRes=time_out)). %%
507 TimeOutRes=virtual_time_out(thrown_enumeration_warning(A,B,C,D,E))).
508
509
510 % check if a result is a time_out:
511 is_time_out_result(time_out).
512 is_time_out_result(virtual_time_out(_)).
513
514 % a version which is to be used not for a single call but for backtracking
515 % generate virtual time_out at the end if enumeration warning occured
516
517 time_out_with_enum_warning_for_findall(Call,TO,TimeOutRes) :-
518 enter_new_error_scope(Level,time_out_with_enum_warning_for_findall),
519 time_out_with_enum_warning_for_findall2(Level,Call,TO,TimeOutRes).
520
521 time_out_with_enum_warning_for_findall2(_Level,Call,TO,TimeOutRes) :- %print(enter(_Level)),nl,
522 catch(
523 time_out_check_enum_warning_for_failure(Call,TO,TimeOutRes,no_clear,no_cut),
524 Exc,
525 get_virtual_time_out_from_exception(Exc,TimeOutRes)). % virtual time_out
526 time_out_with_enum_warning_for_findall2(Level,_Call,_TO,_TimeOutRes) :- % print(exit(Level)),nl,
527 clear_events_in_error_scope(Level,enumeration_warning(_,_,_,_,_)),
528 exit_error_scope(Level,_,time_out_with_enum_warning_for_findall2),fail.
529
530 % a version of time_out_with_enum_warning_for_findall where you manually have to enter_new_error_scope before
531 % and exit_error_scope afterwards; useful if you repeatedly call this predicate and want to set up the block only once
532 time_out_with_enum_warning_for_findall_in_current_error_scope(_Level,Call,TO,TimeOutRes) :- %print(enter(_Level)),nl,
533 ? catch(
534 time_out_check_enum_warning_for_failure(Call,TO,TimeOutRes,no_clear,no_cut),
535 Exc,
536 get_virtual_time_out_from_exception(Exc,TimeOutRes)). % virtual time_out
537 time_out_with_enum_warning_for_findall_in_current_error_scope(Level,_Call,_TO,_TimeOutRes) :-
538 % does not exit level
539 clear_events_in_error_scope(Level,enumeration_warning(_,_,_,_,_)),fail.
540
541 % ------------
542
543 % see if an exception corresponds to a virtual_timeout in the form of an enumeration warning
544 % also treats a CLPFD overflow as a virtual time-out in the sense that computation was aborted
545 get_virtual_time_out_from_exception(enumeration_warning(Cause,_,_,_,_),TimeOutRes) :- !,
546 get_virtual_time_out_res(Cause,TimeOutRes).
547 get_virtual_time_out_from_exception(error(_ErrMsg,ErrTerm),TimeOutRes) :-
548 is_clpfd_overflow_representation_error(ErrTerm,Cause),!,
549 clpfd_overflow_msg(Msg),
550 add_warning(clpfd_overflow,Msg),
551 TimeOutRes = virtual_time_out(Cause).
552 get_virtual_time_out_from_exception(Exc,_) :- % not detected as virtual time-out: throw again
553 throw(Exc).
554
555 get_virtual_time_out_res(kodkod_timeout,Res) :- !, Res= virtual_time_out(kodkod_timeout).
556 get_virtual_time_out_res(_,virtual_time_out(exception)).
557
558
559 is_clpfd_overflow_representation_error(representation_error(_Constraint,_,CauseMsg),CauseMsg) :-
560 is_clpfd_overflow_representation_error_msg(CauseMsg).
561 is_clpfd_overflow_representation_error_msg('CLPFD integer overflow').
562 is_clpfd_overflow_representation_error_msg('max_clpfd_integer').
563 is_clpfd_overflow_representation_error_msg('min_clpfd_integer').
564
565 clpfd_overflow_msg(M) :- clpfd_interface:is_64_bit_system, !,
566 M = 'A CLPFD integer overflow occurred.\nSet CLPFD preference to FALSE (Animation Preferences).'.
567 clpfd_overflow_msg('A CLPFD integer overflow occurred.\nSet CLPFD preference to FALSE (Animation Preferences) or use a 64 bit version of ProB.').
568
569 % -----------------
570
571 :- use_module(tools_meta,[safe_time_out/3]).
572 % a version of time_out which upon failure checks if enumeration warnings were generated
573 time_out_check_enum_warning_for_failure(Call,TO,TimeOutRes,ClearErrors,CutAfterFirstSol) :-
574 ? safe_time_out(Call,TO,TimeOutRes), % a safe version which checks that time-out value TO is not too large
575 %call(Call), TimeOutRes=ok,
576 (TimeOutRes = time_out -> ! %, print(real_timeout),nl
577 ; (ClearErrors=clear_errors -> clear_enumeration_warnings ; true),
578 (CutAfterFirstSol=perform_cut -> ! ; true)
579 %,print(sol),nl
580 ).
581 time_out_check_enum_warning_for_failure(_Call,_TO,TimeOutRes,ClearErrors,_) :- % print(failure),nl,
582 ? virtual_time_out_occured_in_error_scope(TimeOutRes),
583 (ClearErrors=clear_errors -> clear_enumeration_warnings ; true).
584
585 virtual_time_out_occured_in_error_scope(TimeOutRes) :-
586 ? event_occurred_in_error_scope(enumeration_warning(A,B,C,D,critical)), % print(virtual),nl,
587 TimeOutRes = virtual_time_out(failure_enumeration_warning(A,B,C,D,critical)). % we have not investigated all possibilities; generate virtual time_out
588
589 critical_enumeration_warning_occured_in_error_scope :-
590 critical_enumeration_warning_occured_in_error_scope(_,_,_,_).
591 critical_enumeration_warning_occured_in_error_scope(A,B,C,D) :-
592 event_occurred_in_error_scope(enumeration_warning(A,B,C,D,critical)).
593
594 clear_enumeration_warnings :-
595 clear_events_in_current_error_scope(enumeration_warning(_,_,_,_,_)).
596
597 % retract events and raise real warnings
598 % Src and Msg used if these are not enumeration warnings
599 translate_events_in_current_scope_to_warnings(Src,Msg) :-
600 get_counter(cur_block_level,L),
601 retract(specific_event_occurred_at_level(L,Event)),
602 (translate_enumeration_warning(Event,EMsg,Span)
603 -> add_warning(enumeration_warning,EMsg,'',Span)
604 ; add_warning(Src,Msg,Event)),
605 fail.
606 translate_events_in_current_scope_to_warnings(_,_).
607
608 % see also: print_enum_warning
609 translate_enumeration_warning(enumeration_warning(Enumerating,Type,Range,RestrictedRange,_Throwing), Msg,Span) :-
610 translate_enumeration_info(Enumerating,Info,Span),
611 ajoin(['Unbounded enumeration of ',Info,':',Type,', narrowing range: ',Range,' ---> ',RestrictedRange],Msg).
612 % Throwing=throwing -> print_pending_abort_info ?
613
614 translate_enumeration_info(enumerating(Info),Res,Span) :- !, translate_enumeration_info(Info,Res,Span). % TO DO: call get_trigger_info
615 translate_enumeration_info(b(identifier(Id),_,Info),Res,Span) :- !, Res=Id,Span=Info.
616 translate_enumeration_info(I,I,I).
617
618 % show all events in current error scope
619 portray_events_in_error_scope :- event_occurred_in_error_scope(E),
620 portray_event(E),fail.
621 portray_events_in_error_scope.
622
623 portray_event(enumeration_warning(Source,Type,Range,RestrictedRange,Critical)) :-
624 translate_enumeration_info(Source,Res,_Span), !,
625 format(' *** Enumeration Warning (~w): Source ~w, Type: ~w, Range reduction: ~w ---> ~w~n',
626 [Critical, Res, Type, Range, RestrictedRange]).
627 portray_event(E) :- format(' *** ~w~n',[E]).
628
629 % translate an event error to a short human readable form:
630 translate_error_event(Error,TransError) :-
631 (translate_enumeration_warning(Error,Msg,_)
632 -> TransError=Msg
633 ; TransError=Error). % TODO: translate other errors
634
635 % -----------------------
636
637 :- volatile logged_error_hash/5, real_error_occurred/0, logged_error_spans/2, saved_subsidiary_span_pos/4.
638 :- dynamic logged_error_hash/5.
639 :- dynamic logged_message/4.
640 :- dynamic real_error_occurred/0, warning_occurred/0.
641 :- dynamic logged_error_spans/2.
642 :- dynamic saved_subsidiary_span_pos/4. % for Tcl/Tk
643
644
645 reset_real_error_occurred :-
646 (retract(real_error_occurred) -> true ; true),
647 (retract(warning_occurred) -> true ; true).
648
649 reset_errors :-
650 (reset_errors_but_not_scopes -> true
651 ; format(user_error,'~n*** reset_errors_but_not_scopes failed!!~n',[]),
652 fail % something really bad happened
653 ),
654 reset_error_limit_reached,
655 reset_error_scopes. % call if you want to start again at a fresh top-level, without error scopes
656 reset_errors_but_not_scopes :-
657 reset_real_error_occurred,
658 retractall(logged_error_hash(_,_,_,_,_)),
659 retractall(logged_message(_,_,_,_)),
660 reset_error_spans,
661 clear_error_context.
662
663 reset_error_span_if_required :-
664 (logged_error_hash(_,_,_,_,_) -> true
665 ; retractall(logged_error_spans(_,_))).
666
667 reset_error_spans :-
668 retractall(logged_error_spans(_,_)),
669 retractall(saved_subsidiary_span_pos(_,_,_,_)).
670
671 wd_error_occured :-
672 test_error_occurred(well_definedness_error).
673
674 clear_wd_errors :-
675 clear_errors_with_source(well_definedness_error).
676 clear_errors_with_source(Source) :-
677 retractall(logged_error_spans(Source,_)),
678 retractall(logged_error_hash(_,Source,_S1,_TContext1,_Span1)),
679 retractall(logged_message(Source,_,_,_)),
680 (logged_error_hash(_,_Source2,_S2,_TContext2,_Span2) -> true
681 ; reset_real_error_occurred).
682
683 print_error_span(Span) :- print_error_span(Span,error).
684 print_error_span(unknown,_) :- !.
685 print_error_span(none,_) :- !. % from Rodin
686 print_error_span([],_) :- !. % empty info list
687 print_error_span(Span,Kind) :-
688 extract_span_description(Span,PosMsg), !, % also detects info lists
689 print_error(Kind,PosMsg).
690 print_error_span(b(E,T,I),Kind) :-
691 translate_bexpr(b(E,T,I),S),!,
692 print_error(Kind,S).
693 print_error_span(span_predicate(P,_,_),Kind) :- translate_bexpr(P,S),!,
694 % can happen in Event-B when no position info can be extracted
695 print_error(Kind,S).
696 print_error_span(List,Kind) :- List = [_|_], % info list which was not recognised; probably Event-B mode
697 debug_mode(off),
698 !,
699 include(useful_info,List,UsefulList), % only show useful infos
700 (UsefulList = [] -> true
701 ; print_error(Kind,UsefulList)).
702 print_error_span(Span,Kind) :- print_error(Kind,Span). % span not recognized !
703
704 useful_info(section(_)).
705 useful_info(used_ids(_)).
706
707
708 translate_bexpr(P,S) :-
709 (debug_mode(on) -> Lim=3000 ; Lim=1000),
710 translate:translate_subst_or_bexpr_with_limit(P,Lim,S).
711
712 % the same, but not using user_error and red and only printing when span recognised
713 % more detailed than translate:print_span
714 print_message_span(unknown) :- !.
715 print_message_span(Span) :-
716 extract_span_description(Span,PosMsg), !, print(PosMsg).
717 print_message_span(_). % span not recognized !
718
719 % try and extract a string (aka atom) describing the position
720 extract_span_description(span_predicate(P,_,_),PosMsg) :- !,
721 extract_span_description(P,PosMsg).
722 extract_span_description(b(E,_,I),PosMsg) :- !,
723 (extract_span_description(I,PosMsg) -> true
724 ; first_sub_expr(E,A) -> extract_span_description(A,PosMsg)).
725 extract_span_description(Span,PosMsg) :-
726 extract_line_col(Span,StartLine,StartCol,EndLine,EndCol),!,
727 (empty_line_col(StartLine,StartCol,EndLine,EndCol)
728 -> POS = ['Unknown position'|POS2]
729 ; POS = ['Line: ',StartLine,' Column: ',StartCol,
730 ' until Line: ',EndLine,' Column: ',EndCol|POS2]
731 ),
732 (extract_file_name(Span,Filename)
733 -> POS2 = [' in file: ',Filename|POS3] ; POS2 = POS3),
734 (extract_additional_description(Span,ContextMsg)
735 -> POS3 = [' within ',ContextMsg] ; POS3=[]),
736 ajoin(POS,PosMsg).
737 extract_span_description(Span,PosMsg) :-
738 extract_symbolic_label_pos(Span,Symbolic),!,
739 % TO DO: we could try and find section for Rodin
740 ajoin(['@label: ',Symbolic],PosMsg).
741 extract_span_description(Span,PosMsg) :-
742 % try if we have an unknown position with a known context (e.g., pos_context(unknown,call_stack(...))
743 extract_additional_description(Span,ContextMsg),!,
744 %POS = ['Unknown position within ',ContextMsg],
745 POS = ['Within ',ContextMsg],
746 ajoin(POS,PosMsg).
747 % Note: Atom Plugin is quite sensitive to above error message and capitalization
748 % (https://github.com/wysiib/language-b-eventb)
749
750
751
752
753 % detect if a position is empty; Line 0, Column -1 .. Line 0, Column -2 used for non available Library Definition files
754 % happens, e.g., when typing CHOOSE({1}\{1}) in REPL
755 empty_line_col(0,N1,0,N2) :- integer(N1), integer(N2), N1>N2.
756
757 assert_true(Code) :-
758 (call(Code) -> true ; add_internal_error('Assertion failed: ',Code)).
759
760 add_error_fail(Source,ErrMsg, ErrTerm) :- add_error_and_fail(Source,ErrMsg, ErrTerm).
761 add_error_and_fail(Source,ErrMsg, ErrTerm) :- add_error(Source,ErrMsg, ErrTerm),fail.
762 add_error_and_fail(Source,ErrMsg) :- add_error(Source,ErrMsg),fail.
763
764 % add_error/2, add_error/3 and add_error/4
765 add_error(Source,ErrMsg) :- add_error4(Source,ErrMsg, '',unknown).
766 add_error(Source,ErrMsg, ErrTerm) :- add_error4(Source,ErrMsg, ErrTerm,unknown).
767 add_error(Source,ErrMsg,ErrTerm,Span) :- add_error4(Source,ErrMsg,ErrTerm,Span).
768
769 add_error4(Source,ErrMsg,ErrTerm,Span) :-
770 assert_real_error_occurred(Source),
771 combine_msg_and_error_term(ErrMsg,ErrTerm,Span,S),
772 add_error_or_warning(Source,S,Span).
773
774 %:- use_module(translate, [translate_error_term/2, translate_context/2]).
775 combine_msg_and_error_term(Msg,ErrTerm,_,Res) :- ErrTerm=='', !, Res=Msg.
776 combine_msg_and_error_term(ErrMsg,ErrTerm,Span,S) :-
777 string_concatenate(ErrMsg,' ',ST),
778 safe_translate_error_term(ErrTerm,Span,RString),
779 string_concatenate(ST,RString,S).
780
781
782 :- dynamic show_error_source/0.
783 show_error_source. % True if error source and span to be printed
784 turn_show_error_source_on :- (show_error_source -> true ; assertz(show_error_source)).
785 turn_show_error_source_off :- retractall(show_error_source).
786
787 trace_if_user_wants_it :- (preferences:get_preference(trace_upon_error,true) -> safe_trace ; true).
788
789 % try Prolog's trace; if this fails (compiled code), then ask user for input.
790 safe_trace :- translate:install_b_portray_hook,
791 catch(trace, error(existence_error(_,_),_), type_to_continue).
792
793 :- dynamic do_not_interrupt_user_anymore/0.
794
795 type_to_continue :- do_not_interrupt_user_anymore,!.
796 type_to_continue :- format(user_output,'(type <RETURN> to continue, z<RETURN> to zip) ===> ',[]),
797 read_line(user_input,X),
798 (zip(X) -> assertz(do_not_interrupt_user_anymore) ; true).
799
800 zip([122|_]). %starts with z
801
802
803 print_error_source(well_definedness_error) :- !,print_error('A well-definedness error occured !').
804 print_error_source(warning(Source)) :- show_error_source,!,
805 format_error_with_nl('~n! A warning occurred (source: ~w) !',[Source]).
806 print_error_source(internal_error(Source)) :- show_error_source,!,
807 flush_output, % internal error should not happen; be sure to flush all other pending outputs so that we can see where it happened
808 format_error_with_nl('~n! An internal error occurred (source: ~w) !',[Source]).
809 print_error_source(Source) :- show_error_source,!,
810 format_error_with_nl('~n! An error occurred (source: ~w) !',[Source]).
811 print_error_source(_).
812
813 print_error_context(Kind,Context) :- ((Context = '' ; \+show_error_source) -> true ; print_error(Kind,Context)).
814
815 print_error(message,Term) :- !, print_message_on_stream(user_output,[blue],Term).
816 print_error(_,Term) :- print_error(Term).
817
818 safe_translate_error_term(ErrTerm,Span,RString) :-
819 temporary_set_preference(expand_avl_upto,5,CHNG),
820 translate:translate_error_term(ErrTerm,Span,RString),
821 reset_temporary_preference(expand_avl_upto,CHNG).
822
823 safe_translate_context(Result) :-
824 % avoid infinite loop when error occurs inside translate_context
825 current_context(Context),
826 !,
827 set_error_context(translate_context),
828 temporary_set_preference(expand_avl_upto,4,CHNG),
829 (translate:translate_context(Context,TContext)
830 -> true ; TContext=Context),
831 reset_temporary_preference(expand_avl_upto,CHNG),
832 restore_error_context(Context),
833 Result=TContext.
834 safe_translate_context(''). % no context
835
836 is_optional_error_or_warning(warning(Src)) :- !, optional_error_or_warning(Src).
837 is_optional_error_or_warning(Src) :- optional_error_or_warning(Src).
838
839 add_error_or_warning(Source,ErrMsg,Span) :-
840 safe_translate_context(Context),
841 reset_error_span_if_required,
842 simplify_span(Span,SSpan), % for better hashing, assertz, retract
843 assertz_logged_error_if_new(Source,ErrMsg,Context,SSpan,New),
844 log_error_or_msg(Source,ErrMsg,SSpan),
845 (New=false -> true
846 ; is_optional_error_or_warning(Source) ->
847 (extract_span_description(SSpan,PosMsg) -> true ; PosMsg=''),
848 formatsilentmsg(user_output,'% Optional error ~w occured: ~w ~w~n',[Source,ErrMsg,PosMsg]),
849 register_error_span(Source,SSpan,_)
850 ; register_error_span(Source,SSpan,NewSrcSpan),
851 (NewSrcSpan=false,
852 error_limit_reached,
853 Source \= internal_error(_) % always show internal errors
854 -> true % this is not a new Source,SSpan combination and we have already several errors;
855 ; print_error_source(Source),
856 print_error(ErrMsg),
857 print_error_context(error,Context),
858 print_error_span(SSpan)
859 ),
860 trace_if_user_wants_it
861 ).
862
863 % optionally log errors in to a ndsjon logfile
864 log_error_or_msg(Source,ErrMsg,Span) :- get_preference(error_log_file,LogFile),
865 LogFile \= '',
866 decompose_error_source(Source,Type,Src),
867 !,
868 ndjson_log(Type,Src,ErrMsg,Span,LogFile).
869 log_error_or_msg(_,_,_).
870
871 % log error, warning or message to NDJSON log file
872 % Type is warning, error, info
873 :- use_module(tools_io,[intelligent_open/4]).
874 ndjson_log(Type,Src,ErrMsg,Span,LogFile) :-
875 force_extract_position_from_span(Span,Filename,StartLine,StartCol,EndLine,EndCol),
876 catch(intelligent_open(LogFile,append,S,[encoding(utf8)]), E,
877 (format(user_error,'~n*** Cannot open error log file: ~w~n*** Exception: ~w~n',[LogFile,E]),fail)),
878 !,
879 ndjson_write(S,Type,ErrMsg,Src,Filename,StartLine,StartCol,EndLine,EndCol),
880 (extract_additional_pos_and_descr(Span,SubPos,_Desc),
881 extract_position_from_span(SubPos,Filename2,StartLine2,StartCol2,EndLine2,EndCol2),
882 ndjson_write(S,Type,ErrMsg,Src,Filename2,StartLine2,StartCol2,EndLine2,EndCol2),
883 fail
884 ;
885 true
886 ),
887 close(S).
888 ndjson_log(_,_,_,_,_).
889
890 % assign position to main file if we cannot extract the precise position
891 force_extract_position_from_span(Span,Filename,StartLine,StartCol,EndLine,EndCol) :-
892 extract_position_from_span(Span,Filename,StartLine,StartCol,EndLine,EndCol),!.
893 force_extract_position_from_span(_Span,Filename,StartLine,StartCol,EndLine,EndCol) :-
894 bmachine:b_get_main_filenumber(MainFN),
895 get_filename(MainFN,Filename),!,
896 % generate a virtual position, so that global errors without position are shown in Atom, VSCode,...
897 StartLine=1,StartCol=1,EndLine=1,EndCol=1.
898 force_extract_position_from_span(_Span,Filename,StartLine,StartCol,EndLine,EndCol) :-
899 specfile:currently_opened_file_status(Filename,_),
900 StartLine='-1',StartCol='-1',EndLine='-1',EndCol='-1'.
901
902 %ndjson format http://ndjson.org
903 % one JSON term per line
904 :- use_module(extrasrc(json_parser),[json_write_stream/2]).
905 ndjson_write(S,Type,ErrMsg,Src,Filename,StartLine,StartCol,EndLine,EndCol) :-
906 version:version_str(Version),
907 Term = json([type=string(Type), % Type is warning, error, info
908 message=string(ErrMsg),
909 reason=string(Src),
910 file=string(Filename),
911 start=json([line=number(StartLine),col=number(StartCol)]),
912 end=json([line=number(EndLine),col=number(EndCol)]),
913 version=string(Version)
914 ]),
915 json_write_stream(S,Term), nl(S).
916
917 decompose_error_source(warning(Source),warning,Res) :- !, Res=Source.
918 decompose_error_source(internal_error(Source),internal_error,Res) :- !, Res=Source.
919 decompose_error_source(message(Source),information,Res) :- !, Res=Source. % mainly for NDJSON
920 decompose_error_source(Msg,error,Msg).
921
922
923 % the total number of errors since start; no way to reset this; useful for validation reports
924 % TO DO: maybe use counter extension; but tricky to get dependency and initialisation right
925 get_total_number_of_errors(X) :-
926 (bb_get(total_number_of_errors,R) -> X=R
927 ; X=0).
928
929 inc_total_number_of_errors :-
930 (bb_get(total_number_of_errors,R)
931 -> R1 is R+1, bb_put(total_number_of_errors,R1)
932 ; bb_put(total_number_of_errors,1)).
933
934
935 total_number_of_errors_at_last_reset(Res) :-
936 (bb_get(total_number_of_errors_at_last_reset,R) -> Res=R ; Res=0).
937
938 reset_error_limit_reached :-
939 bb_put(error_limit_reached_printed,false),
940 get_total_number_of_errors(T),
941 bb_put(total_number_of_errors_at_last_reset,T).
942
943 error_limit_reached :- bb_get(error_limit_reached_printed,true),!.
944 error_limit_reached :- get_total_number_of_errors(Nr), Nr >= 100,
945 total_number_of_errors_at_last_reset(Last), Delta is Nr-Last, Delta >= 100,
946 format_error_with_nl('Error limit reached (total: ~w, delta: ~w); only printing new error source and locations!',[Nr,Delta]),
947 bb_put(error_limit_reached_printed,true).
948
949 assert_warning_occured :-
950 (preferences:get_preference(strict_raise_warnings,true)
951 -> assert_real_error_occurred(warning)
952 ; warning_occurred -> true
953 ; assertz(warning_occurred)).
954 assert_real_error_occurred(Source) :-
955 (real_error_occurred -> true ; assertz(real_error_occurred)),
956 inc_total_number_of_errors,
957 assert_real_error_in_current_block(Source).
958
959 :- use_module(hashing,[term_depth_hash/3]).
960 assertz_logged_error_if_new(Source,S,TContext,Span,New) :-
961 % limit depth mainly for TContext/Span; avoiding generating many similar error messages with same msg
962 % however, for WD errors often the msg varies (e.g. argument for function application); so this will not prevent a lot of errors
963 term_depth_hash(logged_error_hash(Source,S,TContext,Span),4,Hash),
964 (logged_error_hash(Hash,Source,S,TContext,Span)
965 -> debug_println(repeated_error(Hash)),New=false
966 ; %print(new(Hash,Source,S,TContext,Span)),nl,
967 assertz(logged_error_hash(Hash,Source,S,TContext,Span)),
968 New=true).
969
970 logged_error(Source,S,TContext,Span) :- logged_error_hash(_Hash,Source,S,TContext,Span).
971
972 add_warning(Source,ErrMsg, ErrTerm) :-
973 add_warning(Source,ErrMsg, ErrTerm,unknown).
974 add_warning(Source,ErrMsg, ErrTerm,Span) :-
975 safe_translate_error_term(ErrTerm,Span,RString),
976 string_concatenate(ErrMsg,RString,S),
977 assert_warning_occured,
978 add_error_or_warning(warning(Source),S,Span).
979 add_warning(Source,Message) :-
980 assert_warning_occured,
981 add_error_or_warning(warning(Source),Message,unknown).
982
983 % MESSAGES
984
985 % add message in debug mode
986 add_debug_message(Source,ErrMsg, ErrTerm) :-
987 add_debug_message(Source,ErrMsg, ErrTerm,unknown).
988 add_debug_message(Source,ErrMsg, ErrTerm, Span) :-
989 debug_mode(on),!,
990 add_message(Source,ErrMsg, ErrTerm, Span).
991 add_debug_message(_,_,_,_).
992
993
994 add_message(Source,ErrMsg, ErrTerm) :- /* same as add_error but does not add err msg */
995 add_message(Source,ErrMsg, ErrTerm,unknown).
996
997 add_message(_,_, _,unknown) :- error_manager_silent_mode(on),!.
998 add_message(Source,ErrMsg, ErrTerm,Span) :- /* same as add_error but does not add err msg */
999 safe_translate_error_term(ErrTerm,Span,RString),
1000 string_concatenate(ErrMsg,RString,S),
1001 add_message_direct(Source, S),
1002 safe_translate_context(Context),
1003 print_error_context(message,Context),
1004 print_error_span(Span,message),
1005 log_error_or_msg(message(Source),S,Span),
1006 assertz(logged_message(Source,S,Context,Span)).
1007
1008 add_message(_,_) :- error_manager_silent_mode(on),!.
1009 add_message(Source,ErrMsg) :- add_message_direct(Source,ErrMsg).
1010
1011 add_message_direct(Source,ErrMsg) :-
1012 (show_error_source -> format_with_colour(user_output,[light_gray],'! Message (source: ~w):~n',[Source]) ; true),
1013 print_error(message,ErrMsg).
1014
1015
1016 % adds a list of errors with position information
1017 % [error(Msg,Pos)] or [warning(Msg,Pos)...]
1018 no_real_perror_occurred([]).
1019 no_real_perror_occurred([warning(_,_)|T]) :- no_real_perror_occurred(T).
1020
1021 add_all_perrors(Errors) :- add_all_perrors(Errors,[],bmachine).
1022 add_all_perrors(Errors,Files) :- add_all_perrors(Errors,Files,bmachine).
1023 add_all_perrors(Errors,Files,Context) :- add_all_perrors(Errors,Files,Context,0,100).
1024
1025 add_all_perrors([],_,_,_,_).
1026 add_all_perrors([H|Rest],_Filenames,ContextOfError,NrOfErrors,MaxErrors) :-
1027 NrOfErrors >= MaxErrors,!,
1028 length([H|Rest],Len),
1029 add_error(ContextOfError,'Reached maximium number of errors; number of errors not reported: ',Len).
1030 add_all_perrors([Error|Rest],Filenames,ContextOfError,NrOfErrors,MaxErrors) :-
1031 get_perror(Error,ErrOrWarn,Msg,Pos),
1032 extract_perror_pos(Pos,Filenames,NewPos),
1033 (ErrOrWarn == warning -> add_warning(ContextOfError,Msg,'',NewPos)
1034 ; ErrOrWarn = internal_error -> add_internal_error(ContextOfError,Msg,'',NewPos)
1035 ; add_error(ContextOfError,Msg,'',NewPos)),
1036 N1 is NrOfErrors+1,
1037 add_all_perrors(Rest,Filenames,ContextOfError,N1,MaxErrors).
1038
1039 extract_perror_pos(Pos,Filenames,ResPOS) :-
1040 get_position_row_cols(Pos,Srow,Scol,Erow,Ecol),
1041 get_position_filenumber(Pos,Filenumber),!,
1042 ( get_filename(Filenumber,Filenames,Filename)
1043 %Ecol1 is Ecol+1,
1044 -> ResPOS = src_span(Filenumber,Filename,Srow,Scol,Erow,Ecol,[],[])
1045 % ; Filenumber = -1, Filenames=[FN] -> % just a single filename, e.g., in VisB parsing
1046 % % TODO: we need to adjust line and column numbers using a reference position
1047 % POS = src_position_with_filename_and_ec(Srow,Scol,Erow,Ecol,FN)
1048 ; ResPOS = src_span(Srow,Scol,Erow,Ecol,[],[])
1049 ).
1050 extract_perror_pos(pos(Srow,Scol,Filename),Files,POS) :- !, % deprecated ?
1051 adapt_null_file_name(Filename,Files,Filename2),
1052 S1 is Scol+0, % zero width span
1053 POS = src_position_with_filename_and_ec(Srow,Scol,Srow,S1,Filename2).
1054 extract_perror_pos(pos(Srow,Scol,Erow,Ecol,Filename),Files,POS) :- !,
1055 adapt_null_file_name(Filename,Files,Filename2),
1056 %Ecol1 is Ecol+1,
1057 POS = src_position_with_filename_and_ec(Srow,Scol,Erow,Ecol,Filename2).
1058 extract_perror_pos(pos(Srow,Scol),_,POS) :- !, print(deprecated_pos(Srow,Scol)),nl,
1059 POS = src_position(Srow,Scol,none,1).
1060 extract_perror_pos(Pos,_,Pos).
1061
1062 % adapt filename
1063 adapt_null_file_name(null,[File],Res) :-
1064 !, % the error is not associated to a given file, but we have a file list with just a single file;
1065 % occurs e.g. when parsing VisB JSON files
1066 Res=File.
1067 adapt_null_file_name(F,_,F).
1068
1069 get_perror(error(Msg,Pos),error,Msg,Pos) :- !.
1070 get_perror(internal_error(Msg,Pos),internal_error,Msg,Pos) :- !.
1071 get_perror(warning(Msg,Pos),warning,Msg,Pos) :- !.
1072 get_perror(M,_,M,unknown) :- format(user_error,'*** unknown perror: ~w~n',[M]).
1073
1074 % version without list of filenames
1075 get_filename(Filenumber,Filename) :-
1076 bmachine:b_get_all_used_filenames(FN),
1077 get_filename(Filenumber,FN,Filename).
1078
1079 get_filename(Filenumber,Filenames,Filename) :-
1080 number(Filenumber),!,
1081 nth1(Filenumber,Filenames,Filename).
1082 get_filename(N,F,R) :-
1083 add_internal_error('Cannot get filename: ',get_filename(N,F,R)),
1084 N=1,F=[R|_]. % return first file if possible
1085
1086 % check if error/warning occured and retract matching error/warning
1087 get_error_with_span(Source,ErrMsg,Span) :-
1088 retract(logged_error_hash(_Hash,Source,ErrMsg,_Context,Span)).
1089 get_error(Source,ErrMsg) :-
1090 retract(logged_error_hash(_,Source,ErrMsg,_,_)).
1091 get_warning(Source,ErrMsg) :-
1092 retract(logged_error_hash(_,warning(Source),ErrMsg,_,_)).
1093
1094 % now the same without actually retracting the error/warning:
1095 check_error_occured(Source,ErrMsg) :- logged_error(Source,ErrMsg,_,_).
1096 check_warning_occured(Source,ErrMsg) :- logged_error(warning(Source),ErrMsg,_,_).
1097
1098 get_next_error_or_warning(Msg) :- get_error_or_message(_Src,Type,Msg),
1099 Type \= message. % retract message, but do not return it
1100 get_error_or_message(Source,Type,Msg) :-
1101 retract_logged_error_or_message(Source,Type,ErrMsg,Context,Span),
1102 (extract_line_col(Span,StartLine,StartCol,EndLine,EndCol)
1103 -> POS = ['\n ### Line: ',StartLine,', Column: ',StartCol|POS1],
1104 ((StartLine,StartCol) \= (EndLine,EndCol)
1105 -> (StartLine=EndLine -> POS1 = [' until ',EndCol|POS2]
1106 ; POS1 = ['\n ### until Line: ',EndLine,', Column: ',EndCol|POS2]
1107 )
1108 ; POS1 = POS2
1109 ),
1110 (extract_additional_description(Span,CMsg)
1111 -> POS2 = ['\n ### within: ',CMsg,'\n\n']
1112 ; POS2 = ['\n\n']
1113 ),
1114 (extract_relative_file_name(Span,Filename)
1115 -> PosMsg = ['\n ### File: ',Filename | POS]
1116 ; PosMsg = POS
1117 ),
1118 tools:ajoin(PosMsg,EndStr)
1119 ; EndStr = '\n\n'
1120 ),
1121 ((Context='' ; Context = '???')
1122 -> string_concatenate(ErrMsg,EndStr,S0)
1123 ; safe_translate_error_term(Context,Span,CString),
1124 string_concatenate(CString,EndStr,CString2),
1125 string_concatenate(': Context = ',CString2,CString3),
1126 string_concatenate(ErrMsg,CString3,S0)
1127 ),
1128 (debug_mode(off) -> Msg = S0
1129 ; decompose_error_source(Source,_,SrcAtom),
1130 string_concatenate(SrcAtom,': ',S1),
1131 string_concatenate(S1,S0,Msg)
1132 ).
1133
1134 % retract an error
1135 retract_logged_error_or_message(Source,Type,ErrMsg,Context,Span) :- Type \== message,
1136 retract(logged_error_hash(_Hash,Source,ErrMsg,Context,Span)),
1137 (Source = warning(_) -> Type=warning
1138 ; Source = internal_error(_) -> Type=internal_error
1139 ; Type=error).
1140 retract_logged_error_or_message(message(Source),message,ErrMsg,Context,Span) :-
1141 retract(logged_message(Source,ErrMsg,Context,Span)).
1142
1143
1144 get_error_with_span_info(ErrMsg,Type,ErrLocations) :-
1145 retract_logged_error_or_message(_Source,Type,ErrMsg,_Context,Span),
1146 findall( error_span(Filename,StartLine,StartCol,EndLine,EndCol),
1147 extract_position_from_span(Span,Filename,StartLine,StartCol,EndLine,EndCol),
1148 ErrLocations).
1149
1150 extract_position_from_span(Span,Filename,StartLine,StartCol,EndLine,EndCol) :-
1151 extract_line_col(Span,StartLine,StartCol,EndLine,EndCol),
1152 (extract_file_name(Span,FName) -> Filename=FName ; Filename='').
1153
1154 % Tcl/Tk interface of SICStus cannot deal with certain strange Unicode symbols
1155 % see prob_examples/public_examples/B/Puzzles/LogicQuestion.mch where code 55349 appears
1156 tk_escape(Atom,EAtom) :- atom(Atom),!,
1157 atom_codes(Atom,C),
1158 maplist(tk_escape_code,C,EC),
1159 atom_codes(EAtom,EC).
1160 tk_escape(list(L),list(EL)) :- !, maplist(tk_escape,L,EL).
1161 tk_escape(X,X).
1162
1163 tk_escape_code(StrangeUnicode,Res) :-
1164 StrangeUnicode > 55000,!, % not sure what the limit should be here
1165 Res = 9633. % white box
1166 tk_escape_code(Code,Code).
1167
1168 tcltk_get_all_errors(Limit,list(ERes),NrErrorsShown,NrErrors) :-
1169 get_all_errors(All),
1170 length(All,NrErrors),
1171 (NrErrors =< Limit -> Res = All, NrErrorsShown = NrErrors
1172 ; prefix_length(All,Res,Limit), % truncate
1173 NrErrorsShown = Limit
1174 ),
1175 tk_escape(list(Res),list(ERes)).
1176
1177
1178 get_all_errors(All) :-
1179 findall(Err,get_next_error_or_warning(Err),All),
1180 All \= [],
1181 clear_error_context.
1182
1183 get_all_errors_and_clear(All) :-
1184 findall(Err,get_next_error_or_warning(Err),All),
1185 reset_errors_but_not_scopes,
1186 All \= [].
1187 get_all_errors_and_reset(All) :-
1188 findall(Err,get_next_error_or_warning(Err),All),
1189 reset_errors, % fresh top-level
1190 All \= [].
1191 get_all_errors_with_span_info_and_reset(All) :-
1192 findall(error(ErrMsg,ErrType,ErrLocations),get_error_with_span_info(ErrMsg,ErrType,ErrLocations),All),
1193 reset_errors.
1194
1195 error_or_warning_occured :- logged_error(_Source,_,_,_),!.
1196 test_error_occurred(Source) :- logged_error(Source,_,_,_),real_error_occurred,!.
1197
1198 %:- use_module(library(lists),[length/2]). length is builtin
1199
1200 count_errors_occurred(Source,NrOfErrors) :-
1201 findall(1,logged_error(Source,_,_,_),Ls),
1202 length(Ls,NrOfErrors).
1203
1204 display_error_statistics :- findall(Source,logged_error(Source,_,_,_),L),
1205 count_occurences(L,Occ),
1206 format('Error manager summary: ~w~n',[Occ]).
1207
1208
1209
1210
1211 % ERROR CONTEXTS
1212 % --------------
1213
1214 /* add context information; will be added to any error messages */
1215 % Note: Each Prolog module maintains its own blackboard for bb_get/bb_put
1216 set_error_context(Ctx) :- bb_put(error_manager_context,Ctx).
1217
1218 clear_error_context :- (bb_delete(error_manager_context,_) -> true ; true).
1219 % retractall with dynamic predicate seems to slow down
1220
1221 current_context(C) :- bb_get(error_manager_context,C).
1222
1223 get_error_context(C) :- (current_context(C) -> true ; C='???').
1224 print_error_context :- (safe_translate_context(R), R\='' -> print_error(error,R) ; true).
1225
1226 % restore an error context obtained by get_error_context
1227 restore_error_context('???') :- !, clear_error_context.
1228 restore_error_context(C) :- set_error_context(C).
1229
1230
1231 % -----------------
1232
1233 get_error_span(Source,Span) :-
1234 retract(logged_error_spans(Source,Span)).
1235
1236 % a way for external modules to register error locations, e.g., for display by Tcl/Tk HighlightSyntaxErrors
1237 register_error_span(Source,Span) :- register_error_span(Source,Span,_).
1238 register_error_span(_,unknown,New) :- !,New=false.
1239 register_error_span(Source,Span,New) :- logged_error_spans(Source,Span),!,New=false.
1240 register_error_span(Source,Span,New) :- assertz(logged_error_spans(Source,Span)),New=true.
1241
1242 get_error_span_linecol(Line,Col,EndLine,EndCol) :- get_error_span_linecol(_Source,Line,Col,EndLine,EndCol).
1243 get_error_span_linecol(Source,Line,Col,EndLine,EndCol) :-
1244 get_error_span(Source,Span), % looks at logged_error_spans and retracts
1245 extract_line_col(Span,Line,Col,EndLine,EndCol).
1246
1247 % gets repeatedly called from Tcl/Tk to get all error locations
1248 tk_get_error_span_linecol_for_main_file(Line,Col,EndLine,EndCol) :-
1249 retract(saved_subsidiary_span_pos(Line,Col,EndLine,EndCol)).
1250 tk_get_error_span_linecol_for_main_file(Line,Col,EndLine,EndCol) :-
1251 get_error_span(_Source,Span), % looks at logged_error_spans and retracts even if not in main file !
1252 (extract_primary_line_col_for_main_file(Span,Line,Col,EndLine,EndCol)
1253 -> (extract_additional_pos_and_descr(Span,SubPos,_),
1254 extract_line_col_for_main_file(SubPos,SLine,SCol,SEndLine,SEndCol),
1255 assertz(saved_subsidiary_span_pos(SLine,SCol,SEndLine,SEndCol)), % store for later lookup
1256 fail
1257 ; true)
1258 ; % try finding subsidiary position which is in main file:
1259 extract_additional_pos_and_descr(Span,SubPos,_),
1260 extract_line_col_for_main_file(SubPos,Line,Col,EndLine,EndCol)
1261 ).
1262
1263
1264 % just like get_error_span_linecol but does not retract and gets Filename
1265 check_error_span_file_linecol(Source, FullFilename,Line,Col,EndLine,EndCol) :-
1266 logged_error_spans(Source,Span),
1267 (extract_file_line_col(Span,FullFilename,Line,Col,EndLine,EndCol)
1268 ;
1269 extract_additional_pos_and_descr(Span,SubPos,_),
1270 extract_file_line_col(SubPos,FullFilename,Line,Col,EndLine,EndCol)).
1271
1272 extract_file_line_col(Span,FullFilename,Line,Col,EndLine,EndCol) :-
1273 (extract_file_number_and_name(Span,_,FullFilename)
1274 -> true
1275 ; FullFilename = unknown), % e.g. something like src_span/6; should we return unknown('?')
1276 extract_line_col(Span,Line,Col,EndLine,EndCol).
1277
1278 % try and extract symbolic (Rodin label) information
1279 extract_symbolic_label_pos(span_predicate(P,_,_),PosMsg) :- !,
1280 extract_symbolic_label_pos(P,PosMsg).
1281 extract_symbolic_label_pos(b(E,_,I),PosMsg) :- !,
1282 (extract_symbolic_label_pos(I,PosMsg) -> true
1283 ; first_sub_expr(E,A) -> extract_symbolic_label_pos(A,PosMsg)).
1284 extract_symbolic_label_pos([],_) :- !,fail.
1285 extract_symbolic_label_pos([H|T],SymbolicPos) :- !,
1286 posinfo_member(N,[H|T]),
1287 extract_symbolic_label_pos(N,SymbolicPos),!.
1288 extract_symbolic_label_pos(rodinpos(Label,_),Label). % see also get_texpr_labels in bsyntaxtree
1289 extract_symbolic_label_pos(rodinpos(Model,Name,_),Label) :- ajoin([Model,':',Name],Label).
1290 extract_symbolic_label_pos(rodin_derived_context_pos(Model,Context,LabelName),Label) :-
1291 ajoin([Model,'.',Context,':',LabelName],Label).
1292 extract_symbolic_label_pos(label(Label),Label).
1293
1294 % just extract label, without model
1295 extract_symbolic_label(span_predicate(P,_,_),PosMsg) :- !,
1296 extract_symbolic_label(P,PosMsg).
1297 extract_symbolic_label(b(E,_,I),PosMsg) :- !,
1298 (extract_symbolic_label(I,PosMsg) -> true
1299 ; first_sub_expr(E,A) -> extract_symbolic_label(A,PosMsg)).
1300 extract_symbolic_label([H|T],SymbolicPos) :- !,
1301 posinfo_member(N,[H|T]),
1302 extract_symbolic_label(N,SymbolicPos),!.
1303 extract_symbolic_label(rodinpos(Label,_),Label) :- Label \= []. % see also get_texpr_labels in bsyntaxtree
1304 extract_symbolic_label(rodinpos(_Model,Label,_),Label) :- Label \= [].
1305 extract_symbolic_label(rodin_derived_context_pos(_Model,_Context,Label),Label) :- Label \= [].
1306 extract_symbolic_label(label(Label),Label) :- Label \= [].
1307
1308 % quickly try and simplify a span, e.g., before asserting it in a fact (as it may become big)
1309 simplify_span(b(E,_,Infos),Res) :- !,
1310 ? (definite_posinfo_member(N,Infos) -> Res=N
1311 ; first_sub_expr(E,A) -> simplify_span(A,Res)
1312 ; Res=unknown).
1313 simplify_span(Infos,Res) :- Infos = [_|_],!,
1314 ? (definite_posinfo_member(N,Infos) -> Res=N ; Res=unknown).
1315 simplify_span(span_predicate(P,_,_),Res) :- !, simplify_span(P,Res).
1316 simplify_span(S,S).
1317
1318 % choose first sub-expression in case top-expression has no position info (it would be better if extract_info/3 in bsyntaxtree merges position info)
1319 first_sub_expr(negation(A,_),A).
1320 first_sub_expr(conjunct(A,_),A).
1321 first_sub_expr(disjunct(A,_),A).
1322 first_sub_expr(implication(A,_),A).
1323 first_sub_expr(equivalence(A,_),A).
1324 first_sub_expr(exists([A|_],_),A).
1325 first_sub_expr(forall([A|_],_),A).
1326 first_sub_expr(let_predicate([A|_],_,_),A).
1327 first_sub_expr(let_expression([A|_],_,_),A).
1328 first_sub_expr(let_expression_global([A|_],_,_),A).
1329 first_sub_expr(sequence([A|_]),A).
1330 first_sub_expr(parallel([A|_]),A).
1331 first_sub_expr(assign([A|_],_),A).
1332 first_sub_expr(var([A|_],_),A).
1333 first_sub_expr(equal(A,_),A).
1334 first_sub_expr(not_equal(A,_),A).
1335 first_sub_expr(function(A,_),A).
1336 first_sub_expr(less(A,_),A).
1337 first_sub_expr(less_equal(A,_),A).
1338 % TO DO: use bsyntaxtree:syntaxtraversion
1339
1340 :- use_module(tools_positions,[get_position_filenumber/2, get_position_row_cols/5]).
1341
1342 % extract_line_col(S,_,_,_,_) :- print(extract(S)),nl,fail.
1343 extract_line_col(Var,_,_,_,_) :- var(Var),!, write(variable_span(Var)),nl,
1344 fail.
1345 extract_line_col([],_,_,_,_) :- !,fail.
1346 extract_line_col([H|T],Srow,Scol,Erow,Ecol) :- !,
1347 posinfo_member(N,[H|T]),
1348 extract_line_col(N,Srow,Scol,Erow,Ecol),!.
1349 extract_line_col(closure(_,_,B),Srow,Scol,Erow,Ecol) :- !,
1350 extract_line_col(B,Srow,Scol,Erow,Ecol).
1351 extract_line_col(b(E,_,Infos),Srow,Scol,Erow,Ecol) :- !,
1352 (extract_line_col(Infos,Srow,Scol,Erow,Ecol) -> true
1353 ; first_sub_expr(E,A) -> extract_line_col(A,Srow,Scol,Erow,Ecol)).
1354 extract_line_col(span_predicate(P,_,_),Srow,Scol,Erow,Ecol) :- !,
1355 extract_line_col(P,Srow,Scol,Erow,Ecol).
1356 extract_line_col(PosTerm,Srow,S1,Erow,E1) :-
1357 get_position_row_cols(PosTerm,Srow,Scol,Erow,Ecol),
1358 number(Srow),
1359 % _Filenumber is an index into list provided by b_get_all_used_filenames
1360 number(Scol), number(Erow), number(Ecol),
1361 !,
1362 (Scol>0 -> S1 is Scol-1 ; S1 = Scol), % the BParser starts column numbering at 1
1363 (Ecol>0 -> E1 is Ecol-1 ; E1 = Ecol).
1364 %E1=Ecol. %Somehow the Ecol info is ok for Tcl
1365 extract_line_col(unknown,_,_,_,_) :- !,fail.
1366 extract_line_col(pos_context(A,_,_),StartLine,StartCol,EndLine,EndCol) :- !,
1367 extract_line_col(A,StartLine,StartCol,EndLine,EndCol).
1368 extract_line_col(src_span(_Filenr,_Filename,StartLine,SC,EndLine,EC,Offset,LenBytes),StartLine,StartCol,EndLine,EndCol)
1369 :- !,
1370 extract_line_col(src_span(StartLine,SC,EndLine,EC,Offset,LenBytes),StartLine,StartCol,EndLine,EndCol).
1371 extract_line_col(src_span(SL,SC,EL,EC,_Off,_LenBytes),StartLine,StartCol,EndLine,EndCol) :- !,
1372 StartLine=SL, StartCol is SC-1,
1373 EndLine = EL, EndCol is EC-1.
1374 %:- !, StartCol is SC-1, EndCol is StartCol+LenBytes, EndLine = StartLine. %% fix because new library generates erroneous EndLine/EndCol info
1375 % EndCol is EC-1.
1376 extract_line_col(span_info(_Info,Span),SL,SC,EL,EC) :- !, extract_line_col(Span,SL,SC,EL,EC).
1377 extract_line_col(src_span_operator(SP1,SP2),SL,SC,EL,EC) :- !,
1378 (extract_line_col(SP1,SL,SC,EL,EC) ; extract_line_col(SP2,SL,SC,EL,EC)).
1379 extract_line_col(multi_span(SL,SC,EL,EC,_Off,_Len,TAIL),StartLine,StartCol,EndLine,EndCol) :- !,
1380 % TO DO: replace by multi_span/2
1381 ( StartLine = SL, StartCol is SC-1,
1382 EndLine = EL, EndCol is EC-1
1383 ; extract_line_col(TAIL,StartLine,StartCol,EndLine,EndCol)).
1384 %extract_line_col(multi_span(A,B),StartLine,StartCol,EndLine,EndCol) :- !,
1385 % (extract_line_col(A,StartLine,StartCol,EndLine,EndCol) ;
1386 % extract_line_col(B,StartLine,StartCol,EndLine,EndCol)).
1387 extract_line_col(src_position(StartLine,SC,_Off,LenBytes),StartLine,StartCol,EndLine,EndCol) :- !,
1388 StartCol is SC-1, EndCol is StartCol+LenBytes, EndLine is StartLine.
1389 extract_line_col(src_position_with_filename(StartLine,SC,LenBytes,_Filename),StartLine,StartCol,EndLine,EndCol) :-
1390 !,
1391 StartCol is SC-1, EndCol is StartCol+LenBytes, EndLine is StartLine.
1392 extract_line_col(src_position_with_filename_and_ec(SL,SC,EL,EC,_Fname),StartLine,StartCol,EndLine,EndCol) :-
1393 !,
1394 StartLine=SL,StartCol is SC-1,EndLine = EL, EndCol is EC-1.
1395 extract_line_col(lineCol(StartLine,StartCol),StartLine,StartCol,EndLine,EndCol) :- !,
1396 EndLine=StartLine, EndCol=StartCol.
1397 extract_line_col(span_context(Span,_),StartLine,StartCol,EndLine,EndCol) :- !,
1398 extract_line_col(Span,StartLine,StartCol,EndLine,EndCol).
1399 extract_line_col(Pos,_,_,_,_) :- is_symbolic_position(Pos),!,fail. % cannot extract line/col infos
1400 %extract_line_col(Struct,StartLine,StartCol,EndLine,EndCol) :-
1401 % is_argument_of_compound_term(Struct,Arg),
1402 % functor(Arg,FF,NN),functor(Struct,FS,NS), write(detected(FF,NN,in,FS,NS)),nl,trace,
1403 % /* recursively look for error spans inside */
1404 % extract_line_col(Arg,StartLine,StartCol,EndLine,EndCol),!.
1405 %extract_line_col(S,_,_,_,_) :- print('COULD NOT EXTRACT LINE/COL INFO: '), print(S),
1406 % functor(S,F,N), print(' '),print(F/N),nl,nl,fail.
1407
1408 %:- use_module(library(between),[between/3]).
1409 %is_argument_of_compound_term(Term,Arg) :- functor(Term,_,Arity),
1410 % between(1,Arity,ArgNr), arg(ArgNr,Term,Arg),
1411 % % this is quite dangerous, and possibly expensive
1412 % ground(Arg).
1413
1414 is_symbolic_position(rodinpos(_,_)).
1415 is_symbolic_position(rodinpos(_,_,_)).
1416 is_symbolic_position(rodin_derived_context_pos(_,_,_)).
1417 is_symbolic_position(label(_)).
1418
1419
1420 /* For TCL TK: extract all line_col information in one go and in 4 lists */
1421 extract_all_line_col(Span, StartLineList,StartColList,EndLineList,EndColList) :-
1422 findall(lc(SL,SC,EL,EC), extract_line_col(Span,SL,SC,EL,EC),All),
1423 %print(all(All,Span)),nl,
1424 split_lc(All,StartLineList,StartColList,EndLineList,EndColList).
1425
1426 split_lc([], [],[],[],[]).
1427 split_lc([lc(SL,SC,EL,EC)|T],[SL|T1],[SC|T2],[EL|T3],[EC|T4]) :-
1428 split_lc(T,T1,T2,T3,T4).
1429
1430 % TO DO: merge with line_col and in Tcl/Tk use info to highlight proper file !
1431
1432
1433 % TODO: maybe add a preference to always get full filename path (cf always_print_filename in translate)
1434 % TODO: do not show filename if there is only one file ?
1435 extract_relative_file_name(Pos,RelFilename) :-
1436 extract_file_name(Pos,Filename),
1437 (specfile:currently_opened_file_status(Main,_),
1438 tools:get_parent_directory(Main,MainDir),
1439 tools:gen_relative_path(Filename,MainDir,Rel)
1440 -> RelFilename = Rel
1441 ; RelFilename = Filename).
1442 extract_file_name(Pos,Filename) :-
1443 extract_valid_file_number_and_name(Pos,_,Filename),
1444 Filename \=null. % Filename = null occurs in eval_strings !?
1445 extract_tail_file_name(Pos,Filename) :-
1446 extract_valid_file_number_and_name(Pos,_,FullFilename),
1447 tools:get_tail_filename(FullFilename,Filename).
1448 extract_subsidiary_tail_file_name(Pos,Filename) :-
1449 extract_valid_file_number_and_name(Pos,Nr,FullFilename),
1450 not_main_file(Nr,FullFilename),
1451 tools:get_tail_filename(FullFilename,Filename).
1452
1453 extract_valid_file_number_and_name(Pos,Nr,Filename) :-
1454 extract_file_number_and_name(Pos,Nr,Filename),
1455 valid_filename(Filename).
1456 valid_filename(F) :- atom(F). % not unknown(-1) which can come from REPL
1457 % should we detect null here?
1458
1459 % a version of extract_line_col which fails if the primary error location is not in the main file
1460 extract_primary_line_col_for_main_file(Span,Line,Col,EndLine,EndCol) :-
1461 \+((extract_file_number_and_name(Span,Nr,FullFilename),
1462 not_main_file(Nr,FullFilename))),
1463 extract_line_col(Span,Line,Col,EndLine,EndCol).
1464
1465 % a version of extract_line_col which fails if the error or subsidiary location is not in the main file
1466 extract_line_col_for_main_file(Span,Line,Col,EndLine,EndCol) :-
1467 (extract_file_number_and_name(Span,Nr,FullFilename),
1468 not_main_file(Nr,FullFilename)
1469 -> extract_additional_pos_and_descr(Span,SubPos,_),
1470 extract_line_col_for_main_file(SubPos,Line,Col,EndLine,EndCol)
1471 ; extract_line_col(Span,Line,Col,EndLine,EndCol)
1472 ).
1473
1474 extract_file_number_and_name(V,_,_) :- var(V),!,fail.
1475 extract_file_number_and_name(value(_),_,_) :- !,fail.
1476 extract_file_number_and_name(pos_context(A,_,_), Filenumber,Filename) :- !,
1477 extract_file_number_and_name(A, Filenumber,Filename).
1478 extract_file_number_and_name(span_predicate(P,_,_), Filenumber,Filename) :- !,
1479 extract_file_number_and_name(P, Filenumber,Filename).
1480 extract_file_number_and_name(Pos, ResFileNr,Res) :-
1481 get_position_filenumber(Pos,Filenumber),!,
1482 (get_filename(Filenumber,Filename)
1483 -> ResFileNr=Filenumber,Res=Filename
1484 ; ResFileNr=Filenumber,Res=unknown(Filenumber) % unknown(-1) which can come from REPL
1485 ).
1486 extract_file_number_and_name(src_span(_,Filename,_,_,_,_,_,_), ResFileNr, Res) :- !,ResFileNr=unknown, Res=Filename.
1487 extract_file_number_and_name(src_span(_,_,_, _,_,_), _ResFileNr, _Res) :- !,fail. % src_span/6, No file stored
1488 extract_file_number_and_name(src_position_with_filename(_,_,_,Filename), ResFileNr, Res) :- !,ResFileNr=unknown,Res=Filename.
1489 extract_file_number_and_name(src_position_with_filename_and_ec(_,_,_,_,Filename), ResFileNr, Res) :- !,ResFileNr=unknown,Res=Filename.
1490 extract_file_number_and_name(section(RodinFilename), ResFileNr, Res) :- !,ResFileNr=unknown,Res=RodinFilename.
1491 extract_file_number_and_name([H|T],Filenumber,Filename) :- !,
1492 posinfo_member(Arg,[H|T]),
1493 extract_file_number_and_name(Arg,Filenumber,Filename),!.
1494 extract_file_number_and_name(closure(_,_,B),Filenumber,Filename) :- !,
1495 extract_file_number_and_name(B,Filenumber,Filename).
1496 extract_file_number_and_name(b(E,_,Infos),Filenumber,Filename) :- !,
1497 (extract_file_number_and_name(Infos,Filenumber,Filename) -> true
1498 ; first_sub_expr(E,A) -> extract_file_number_and_name(A,Filenumber,Filename)).
1499 extract_file_number_and_name(span_context(Span,_),Filenumber,Filename) :- !,
1500 extract_file_number_and_name(Span,Filenumber,Filename).
1501 %extract_file_number_and_name(Struct,Filenumber,Filename) :-
1502 % /* recursively look for error spans inside */
1503 % is_argument_of_compound_term(Struct,Arg),
1504 % extract_file_number_and_name(Arg,Filenumber,Filename),!.
1505
1506 ?definite_posinfo_member(POS,Args) :- member(nodeid(POS),Args).
1507 posinfo_member(Arg,Args) :- % look for a nodeid(.) member
1508 ? (member(nodeid(POS),Args) -> Arg=POS). % no longer allow other members in lists ; member(Arg,Args)).
1509
1510 %:- use_module(bmachine,[b_get_all_used_filenames/1,b_get_main_filenumber/1]).
1511 position_is_not_in_main_file(Pos) :-
1512 get_position_filenumber(Pos,Filenumber),!, % B position info
1513 not_main_filenumber(Filenumber).
1514 position_is_not_in_main_file(src_span(_,Filename,_,_,_,_,_,_)) :- !,
1515 specfile:currently_opened_file_status(Main,_), Main \= Filename.
1516 position_is_not_in_main_file(src_position_with_filename(_,_,_,Filename)) :- !,
1517 specfile:currently_opened_file_status(Main,_), Main \= Filename.
1518 position_is_not_in_main_file(src_position_with_filename_ec(_,_,_,_,Filename)) :- !,
1519 specfile:currently_opened_file_status(Main,_), Main \= Filename.
1520 position_is_not_in_main_file(Struct) :- \+ atomic(Struct), Struct =.. [_|Args],
1521 /* recursively look for error spans inside */
1522 ? member(Arg,Args), position_is_not_in_main_file(Arg),!.
1523
1524
1525 not_main_file(Filenumber,_) :- number(Filenumber),!, % B Position info
1526 not_main_filenumber(Filenumber).
1527 not_main_file(_,Filename) :- % probably CSP position info; or unknown
1528 specfile:currently_opened_file_status(Main,_),
1529 \+ same_file_name(Main,Filename). %Main \= Filename.
1530
1531 :- use_module(tools,[get_tail_filename/2]).
1532 same_file_name(F1,F2) :-
1533 (F1=F2 -> true
1534 ; atom(F1), atom(F2), % we can have a non-atomic name like package(event_b_project)
1535 get_tail_filename(F1,T1),
1536 get_tail_filename(F2,T2), T1=T2).
1537
1538 not_main_filenumber(Filenumber) :-
1539 bmachine:b_get_main_filenumber(MainFN),
1540 MainFN \= Filenumber.
1541
1542 % ---------------------------------
1543
1544
1545
1546 % find a sub-position matching a given target like context_pos
1547 find_sub_position_match(Pos,Target) :- Target=Pos,!.
1548 find_sub_position_match(b(E,_,Infos),Target) :- !,
1549 (find_sub_position_match(Infos,Target) -> true
1550 ; first_sub_expr(E,A),find_sub_position_match(A,Target)).
1551 find_sub_position_match(span_predicate(P,_,_),Target) :- !,
1552 find_sub_position_match(P,Target).
1553 find_sub_position_match([H|T],Target) :- !,
1554 posinfo_member(N,[H|T]),
1555 find_sub_position_match(N,Target).
1556 find_sub_position_match(closure(_,_,B),Target) :- !,
1557 find_sub_position_match(B,Target).
1558
1559 extract_pos_context(Span,MainPos,Context,CtxtPos) :-
1560 find_sub_position_match(Span,pos_context(M,C,P)),!,
1561 MainPos=M, Context=C, CtxtPos=P.
1562
1563 % extract additional information about error span, e.g., Definition call context, other spans,...
1564 extract_additional_description(Span,FullDesc) :-
1565 extract_additional_pos_and_descr(Span,_Position,FullDesc).
1566
1567 extract_additional_pos_and_descr(Span,CtxtPos,FullDesc) :-
1568 extract_pos_context(Span,MainPos,Context,CtxtPos),
1569 %nl,print(pos_context(MainPos,Context,CtxtPos)),nl,
1570 extract_context_msg(Context,MainPos,CMsg),
1571 (extract_span_description(CtxtPos,PosMsg)
1572 -> ajoin([CMsg,' at ',PosMsg],FullDesc)
1573 ; FullDesc=CMsg). % no position info available
1574
1575 extract_context_msg(call_stack(Stack),MainPos,Msg) :- !,
1576 translate:translate_call_stack([top_level_call(MainPos)|Stack],Msg). % dynamic call stack; we add subsidiary DEFINITION calls to the Call stack
1577 % see result e.g., for public_examples/B/FeatureChecks/DEFINITIONS/DefCallStackDisplay.mch
1578 % TODO: should we also add_inner_context_description for use-cases like Atom editor
1579 extract_context_msg(definition_call(Name),MainPos,Msg) :- !, % static Definition macro expansion call stack
1580 ajoin(['DEFINITION call of ',Name],OuterMsg),
1581 add_inner_context_description(MainPos,OuterMsg,Msg).
1582 extract_context_msg(C,MainPos,Msg) :- ajoin(['CONTEXT: ',C],OuterMsg),
1583 add_inner_context_description(MainPos,OuterMsg,Msg).
1584
1585
1586 add_inner_context_description(Span,OuterCMsg,FullDesc) :-
1587 % used to have this check: Span = pos_context(MainPos,Context,CtxtPos),
1588 extract_additional_pos_and_descr(Span,_Pos,InnerCMsg),!,
1589 ajoin([InnerCMsg,' within ',OuterCMsg],FullDesc).
1590 add_inner_context_description(_,FullDesc,FullDesc).
1591
1592
1593
1594 % ---------------------------------
1595
1596 % Get Source Position Info string for use in Tcl/Tk tables (column must be called 'Source'):
1597 get_tk_table_position_info(Span,PosStr) :-
1598 extract_line_col_for_main_file(Span,StartRow,StartCol,EndRow,EndCol), !,
1599 ajoin([' at line ',StartRow,':',StartCol,' - ', EndRow, ':', EndCol],PosStr). % recognised by Tk Table viewer
1600 get_tk_table_position_info(Span,PosStr) :- extract_span_description(Span,PosStr),!.
1601 get_tk_table_position_info(_,'').
1602
1603
1604 % ---------------------------------
1605
1606 :- dynamic backed_up_error/4.
1607
1608 % copy current error facts into backed_up_error facts
1609 backup_errors :-
1610 retractall(backed_up_error(_,_,_,_)),
1611 logged_error(Source,S,TContext,Span),
1612 assertz(backed_up_error(Source,S,TContext,Span)),
1613 fail.
1614 backup_errors.
1615
1616 % ---------------------------------
1617
1618 :- dynamic error_manager_silent_mode/1.
1619 % separate from debug:silent_mode to avoid dependency to debug module
1620 error_manager_silent_mode(off).
1621
1622 set_error_manager_silent_mode(X) :- retractall(error_manager_silent_mode(_)),
1623 assertz(error_manager_silent_mode(X)).
1624
1625
1626 formatsilentmsg(Stream,FS,Args) :- error_manager_silent_mode(off) -> format(Stream,FS,Args) ; true.
1627
1628 % -------------------------------------------
1629
1630 :- use_module(eventhandling,[register_event_listener/3]).
1631 :- register_event_listener(reset_prob,reset_errors,
1632 'Reset Error Manager just like after starup_prob (except total_number_of_errors)').