work toward better error reporting
[pspp] / src / libpspp / message.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010,
3    2011, 2013 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
17
18 #include <config.h>
19
20 #include "libpspp/message.h"
21
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28
29 #include "libpspp/cast.h"
30 #include "libpspp/str.h"
31 #include "libpspp/version.h"
32 #include "data/settings.h"
33
34 #include "gl/minmax.h"
35 #include "gl/progname.h"
36 #include "gl/relocatable.h"
37 #include "gl/xalloc.h"
38 #include "gl/xvasprintf.h"
39
40 #include "gettext.h"
41 #define _(msgid) gettext (msgid)
42
43 /* Message handler as set by msg_set_handler(). */
44 static void (*msg_handler)  (const struct msg *, void *aux);
45 static void *msg_aux;
46
47 /* Disables emitting messages if positive. */
48 static int messages_disabled;
49
50 /* Public functions. */
51
52
53 void
54 vmsg (enum msg_class class, const struct msg_location *location,
55       const char *format, va_list args)
56 {
57   struct msg *m = xmalloc (sizeof *m);
58   *m = (struct msg) {
59     .category = msg_class_to_category (class),
60     .severity = msg_class_to_severity (class),
61     .location = msg_location_dup (location),
62     .text = xvasprintf (format, args),
63   };
64   msg_emit (m);
65 }
66
67 /* Writes error message in CLASS, with text FORMAT, formatted with
68    printf, to the standard places. */
69 void
70 msg (enum msg_class class, const char *format, ...)
71 {
72   va_list args;
73   va_start (args, format);
74   vmsg (class, NULL, format, args);
75   va_end (args);
76 }
77
78 /* Outputs error message in CLASS, with text FORMAT, formatted with printf.
79    LOCATION is the reported location for the message. */
80 void
81 msg_at (enum msg_class class, const struct msg_location *location,
82         const char *format, ...)
83 {
84   va_list args;
85   va_start (args, format);
86   vmsg (class, location, format, args);
87   va_end (args);
88 }
89
90 void
91 msg_error (int errnum, const char *format, ...)
92 {
93   va_list args;
94   va_start (args, format);
95   struct string s = DS_EMPTY_INITIALIZER;
96   ds_put_vformat (&s, format, args);
97   va_end (args);
98   ds_put_format (&s, ": %s", strerror (errnum));
99
100   struct msg *m = xmalloc (sizeof *m);
101   *m = (struct msg) {
102     .category = MSG_C_GENERAL,
103     .severity = MSG_S_ERROR,
104     .text = ds_steal_cstr (&s),
105   };
106   msg_emit (m);
107 }
108
109
110
111 void
112 msg_set_handler (void (*handler) (const struct msg *, void *aux), void *aux)
113 {
114   msg_handler = handler;
115   msg_aux = aux;
116 }
117 \f
118 /* msg_location. */
119
120 void
121 msg_location_uninit (struct msg_location *loc)
122 {
123   free (loc->file_name);
124 }
125
126 void
127 msg_location_destroy (struct msg_location *loc)
128 {
129   if (loc)
130     {
131       msg_location_uninit (loc);
132       free (loc);
133     }
134 }
135
136 struct msg_location *
137 msg_location_dup (const struct msg_location *src)
138 {
139   if (!src)
140     return NULL;
141
142   struct msg_location *dst = xmalloc (sizeof *dst);
143   *dst = (struct msg_location) {
144     .file_name = xstrdup_if_nonnull (src->file_name),
145     .first_line = src->first_line,
146     .last_line = src->last_line,
147     .first_column = src->first_column,
148     .last_column = src->last_column,
149   };
150   return dst;
151 }
152
153 bool
154 msg_location_is_empty (const struct msg_location *loc)
155 {
156   return !loc || (!loc->file_name
157                   && loc->first_line <= 0
158                   && loc->first_column <= 0);
159 }
160
161 void
162 msg_location_format (const struct msg_location *loc, struct string *s)
163 {
164   if (!loc)
165     return;
166
167   if (loc->file_name)
168     ds_put_cstr (s, loc->file_name);
169
170   int l1 = loc->first_line;
171   int l2 = MAX (loc->first_line, loc->last_line - 1);
172   int c1 = loc->first_column;
173   int c2 = MAX (loc->first_column, loc->last_column - 1);
174
175   if (l1 > 0)
176     {
177       if (loc->file_name)
178         ds_put_byte (s, ':');
179
180       if (l2 > l1)
181         {
182           if (c1 > 0)
183             ds_put_format (s, "%d.%d-%d.%d", l1, c1, l2, c2);
184           else
185             ds_put_format (s, "%d-%d", l1, l2);
186         }
187       else
188         {
189           if (c1 > 0)
190             {
191               if (c2 > c1)
192                 {
193                   /* The GNU coding standards say to use
194                      LINENO-1.COLUMN-1-COLUMN-2 for this case, but GNU
195                      Emacs interprets COLUMN-2 as LINENO-2 if I do that.
196                      I've submitted an Emacs bug report:
197                      http://debbugs.gnu.org/cgi/bugreport.cgi?bug=7725.
198
199                      For now, let's be compatible. */
200                   ds_put_format (s, "%d.%d-%d.%d", l1, c1, l1, c2);
201                 }
202               else
203                 ds_put_format (s, "%d.%d", l1, c1);
204             }
205           else
206             ds_put_format (s, "%d", l1);
207         }
208     }
209   else if (c1 > 0)
210     {
211       if (c2 > c1)
212         ds_put_format (s, ".%d-%d", c1, c2);
213       else
214         ds_put_format (s, ".%d", c1);
215     }
216 }
217 \f
218 /* msg_stack */
219
220 void
221 msg_stack_destroy (struct msg_stack *stack)
222 {
223   if (stack)
224     {
225       msg_location_destroy (stack->location);
226       free (stack->description);
227       free (stack);
228     }
229 }
230
231 struct msg_stack *
232 msg_stack_dup (const struct msg_stack *src)
233 {
234   struct msg_stack *dst = xmalloc (sizeof *src);
235   *dst = (struct msg_stack) {
236     .location = msg_location_dup (src->location),
237     .description = xstrdup_if_nonnull (src->description),
238   };
239   return dst;
240 }
241 \f
242 /* Working with messages. */
243
244 const char *
245 msg_severity_to_string (enum msg_severity severity)
246 {
247   switch (severity)
248     {
249     case MSG_S_ERROR:
250       return _("error");
251     case MSG_S_WARNING:
252       return _("warning");
253     case MSG_S_NOTE:
254     default:
255       return _("note");
256     }
257 }
258
259 /* Duplicate a message */
260 struct msg *
261 msg_dup (const struct msg *src)
262 {
263   struct msg_stack **ms = xmalloc (src->n_stack * sizeof *ms);
264   for (size_t i = 0; i < src->n_stack; i++)
265     ms[i] = msg_stack_dup (src->stack[i]);
266
267   struct msg *dst = xmalloc (sizeof *dst);
268   *dst = (struct msg) {
269     .category = src->category,
270     .severity = src->severity,
271     .stack = ms,
272     .n_stack = src->n_stack,
273     .location = msg_location_dup (src->location),
274     .command_name = xstrdup_if_nonnull (src->command_name),
275     .text = xstrdup (src->text),
276   };
277   return dst;
278 }
279
280 /* Frees a message created by msg_dup().
281
282    (Messages not created by msg_dup(), as well as their file_name
283    members, are typically not dynamically allocated, so this function should
284    not be used to destroy them.) */
285 void
286 msg_destroy (struct msg *m)
287 {
288   if (m)
289     {
290       for (size_t i = 0; i < m->n_stack; i++)
291         msg_stack_destroy (m->stack[i]);
292       free (m->stack);
293       msg_location_destroy (m->location);
294       free (m->text);
295       free (m->command_name);
296       free (m);
297     }
298 }
299
300 char *
301 msg_to_string (const struct msg *m)
302 {
303   struct string s;
304
305   ds_init_empty (&s);
306
307   for (size_t i = 0; i < m->n_stack; i++)
308     {
309       const struct msg_stack *ms = m->stack[i];
310       if (!msg_location_is_empty (ms->location))
311         {
312           msg_location_format (ms->location, &s);
313           ds_put_cstr (&s, ": ");
314         }
315       ds_put_format (&s, "%s\n", ms->description);
316     }
317   if (m->category != MSG_C_GENERAL && !msg_location_is_empty (m->location))
318     {
319       msg_location_format (m->location, &s);
320       ds_put_cstr (&s, ": ");
321     }
322
323   ds_put_format (&s, "%s: ", msg_severity_to_string (m->severity));
324
325   if (m->category == MSG_C_SYNTAX && m->command_name != NULL)
326     ds_put_format (&s, "%s: ", m->command_name);
327
328   ds_put_cstr (&s, m->text);
329
330   return ds_cstr (&s);
331 }
332 \f
333
334 /* Number of messages reported, by severity level. */
335 static int counts[MSG_N_SEVERITIES];
336
337 /* True after the maximum number of errors or warnings has been exceeded. */
338 static bool too_many_errors;
339
340 /* True after the maximum number of notes has been exceeded. */
341 static bool too_many_notes;
342
343 /* True iff warnings have been explicitly disabled (MXWARNS = 0) */
344 static bool warnings_off = false;
345
346 /* Checks whether we've had so many errors that it's time to quit
347    processing this syntax file. */
348 bool
349 msg_ui_too_many_errors (void)
350 {
351   return too_many_errors;
352 }
353
354 void
355 msg_ui_disable_warnings (bool x)
356 {
357   warnings_off = x;
358 }
359
360
361 void
362 msg_ui_reset_counts (void)
363 {
364   int i;
365
366   for (i = 0; i < MSG_N_SEVERITIES; i++)
367     counts[i] = 0;
368   too_many_errors = false;
369   too_many_notes = false;
370 }
371
372 bool
373 msg_ui_any_errors (void)
374 {
375   return counts[MSG_S_ERROR] > 0;
376 }
377
378
379 static void
380 ship_message (const struct msg *m)
381 {
382   enum { MAX_STACK = 4 };
383   static const struct msg *stack[MAX_STACK];
384   static size_t n;
385
386   /* If we're recursing on a given message, or recursing deeply, drop it. */
387   if (n >= MAX_STACK)
388     return;
389   for (size_t i = 0; i < n; i++)
390     if (stack[i] == m)
391       return;
392
393   stack[n++] = m;
394   if (msg_handler && n <= 1)
395     msg_handler (m, msg_aux);
396   else
397     fprintf (stderr, "%s\n", m->text);
398   n--;
399 }
400
401 static void
402 submit_note (char *s)
403 {
404   struct msg m = {
405     .category = MSG_C_GENERAL,
406     .severity = MSG_S_NOTE,
407     .text = s,
408   };
409   ship_message (&m);
410
411   free (s);
412 }
413
414 static void
415 process_msg (struct msg *m)
416 {
417   int n_msgs, max_msgs;
418
419   if (too_many_errors
420       || (too_many_notes && m->severity == MSG_S_NOTE)
421       || (warnings_off && m->severity == MSG_S_WARNING))
422     return;
423
424   ship_message (m);
425
426   counts[m->severity]++;
427   max_msgs = settings_get_max_messages (m->severity);
428   n_msgs = counts[m->severity];
429   if (m->severity == MSG_S_WARNING)
430     n_msgs += counts[MSG_S_ERROR];
431   if (n_msgs > max_msgs)
432     {
433       if (m->severity == MSG_S_NOTE)
434         {
435           too_many_notes = true;
436           submit_note (xasprintf (_("Notes (%d) exceed limit (%d).  "
437                                     "Suppressing further notes."),
438                                   n_msgs, max_msgs));
439         }
440       else
441         {
442           too_many_errors = true;
443           if (m->severity == MSG_S_WARNING)
444             submit_note (xasprintf (_("Warnings (%d) exceed limit (%d).  Syntax processing will be halted."),
445                                     n_msgs, max_msgs));
446           else
447             submit_note (xasprintf (_("Errors (%d) exceed limit (%d).  Syntax processing will be halted."),
448                                     n_msgs, max_msgs));
449         }
450     }
451 }
452
453
454 /* Emits M as an error message.  Takes ownership of M. */
455 void
456 msg_emit (struct msg *m)
457 {
458   if (!messages_disabled)
459     process_msg (m);
460   msg_destroy (m);
461 }
462
463 /* Disables message output until the next call to msg_enable.  If
464    this function is called multiple times, msg_enable must be
465    called an equal number of times before messages are actually
466    re-enabled. */
467 void
468 msg_disable (void)
469 {
470   messages_disabled++;
471 }
472
473 /* Enables message output that was disabled by msg_disable. */
474 void
475 msg_enable (void)
476 {
477   assert (messages_disabled > 0);
478   messages_disabled--;
479 }
480 \f
481 /* Private functions. */
482
483 static char fatal_error_message[1024];
484 static int fatal_error_message_bytes = 0;
485
486 static char diagnostic_information[1024];
487 static int diagnostic_information_bytes = 0;
488
489 static int
490 append_message (char *msg, int bytes_used, const char *fmt, ...)
491 {
492   va_list va;
493   va_start (va, fmt);
494   int ret = vsnprintf (msg + bytes_used, 1024 - bytes_used, fmt, va);
495   va_end (va);
496   assert (ret >= 0);
497
498   return ret;
499 }
500
501
502 /* Generate a row of asterisks held in statically allocated memory  */
503 static struct substring
504 generate_banner (void)
505 {
506   static struct substring banner;
507   if (!banner.string)
508     banner = ss_cstr ("******************************************************\n");
509   return banner;
510 }
511
512 const char *
513 prepare_fatal_error_message (void)
514 {
515   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, generate_banner ().string);
516
517   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "You have discovered a bug in PSPP.  Please report this\n");
518   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "to " PACKAGE_BUGREPORT ".  Please include this entire\n");
519   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "message, *plus* several lines of output just above it.\n");
520   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "For the best chance at having the bug fixed, also\n");
521   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "include the syntax file that triggered it and a sample\n");
522   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "of any data file used for input.\n");
523   return fatal_error_message;
524 }
525
526 const char *
527 prepare_diagnostic_information (void)
528 {
529   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "version:             %s\n", version);
530   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "host_system:         %s\n", host_system);
531   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "build_system:        %s\n", build_system);
532   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "locale_dir:          %s\n", relocate (locale_dir));
533   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "compiler version:    %s\n",
534 #ifdef __VERSION__
535            __VERSION__
536 #else
537            "Unknown"
538 #endif
539 );
540
541   return diagnostic_information;
542 }
543
544 void
545 request_bug_report (const char *msg)
546 {
547   write (STDERR_FILENO, fatal_error_message, fatal_error_message_bytes);
548   write (STDERR_FILENO, "proximate cause:     ", 21);
549   write (STDERR_FILENO, msg, strlen (msg));
550   write (STDERR_FILENO, "\n", 1);
551   write (STDERR_FILENO, diagnostic_information, diagnostic_information_bytes);
552   const struct substring banner = generate_banner ();
553   write (STDERR_FILENO, banner.string, banner.length);
554 }