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