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