83c7320168eef5a8ca4cf68baaa6c129bd98dd0d
[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 struct msg_handler msg_handler = { .output_msg = NULL };
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 void
110 msg_set_handler (const struct msg_handler *handler)
111 {
112   msg_handler = *handler;
113 }
114 \f
115 /* msg_location. */
116
117 void
118 msg_location_uninit (struct msg_location *loc)
119 {
120   if (msg_handler.lex_source_unref)
121     msg_handler.lex_source_unref (loc->src);
122   intern_unref (loc->file_name);
123 }
124
125 void
126 msg_location_destroy (struct msg_location *loc)
127 {
128   if (loc)
129     {
130       msg_location_uninit (loc);
131       free (loc);
132     }
133 }
134
135 static int
136 msg_point_compare_3way (const struct msg_point *a, const struct msg_point *b)
137 {
138   return (!a->line ? 1
139           : !b->line ? -1
140           : a->line > b->line ? 1
141           : a->line < b->line ? -1
142           : !a->column ? 1
143           : !b->column ? -1
144           : a->column > b->column ? 1
145           : a->column < b->column ? -1
146           : 0);
147 }
148
149 void
150 msg_location_remove_columns (struct msg_location *location)
151 {
152   location->start.column = 0;
153   location->end.column = 0;
154 }
155
156 void
157 msg_location_merge (struct msg_location **dstp, const struct msg_location *src)
158 {
159   struct msg_location *dst = *dstp;
160   if (!dst)
161     {
162       *dstp = msg_location_dup (src);
163       return;
164     }
165
166   if (dst->file_name != src->file_name)
167     {
168       /* Failure. */
169       return;
170     }
171   if (msg_point_compare_3way (&dst->start, &src->start) > 0)
172     dst->start = src->start;
173   if (msg_point_compare_3way (&dst->end, &src->end) < 0)
174     dst->end = src->end;
175 }
176
177 struct msg_location *
178 msg_location_dup (const struct msg_location *src)
179 {
180   if (!src)
181     return NULL;
182
183   struct msg_location *dst = xmalloc (sizeof *dst);
184   *dst = *src;
185   if (src->file_name)
186     dst->file_name = intern_ref (src->file_name);
187   if (msg_handler.lex_source_ref && src->src)
188     msg_handler.lex_source_ref (dst->src);
189   return dst;
190 }
191
192 bool
193 msg_location_is_empty (const struct msg_location *loc)
194 {
195   return !loc || (!loc->file_name
196                   && loc->start.line <= 0
197                   && loc->start.column <= 0);
198 }
199
200 void
201 msg_location_format (const struct msg_location *loc, struct string *s)
202 {
203   if (!loc)
204     return;
205
206   if (loc->file_name)
207     ds_put_cstr (s, loc->file_name);
208
209   int l1 = loc->start.line;
210   int l2 = MAX (l1, loc->end.line);
211   int c1 = loc->start.column;
212   int c2 = MAX (c1, loc->end.column);
213
214   if (l1 > 0)
215     {
216       if (loc->file_name)
217         ds_put_byte (s, ':');
218
219       if (l2 > l1)
220         {
221           if (c1 > 0)
222             ds_put_format (s, "%d.%d-%d.%d", l1, c1, l2, c2);
223           else
224             ds_put_format (s, "%d-%d", l1, l2);
225         }
226       else
227         {
228           if (c1 > 0)
229             {
230               if (c2 > c1)
231                 {
232                   /* The GNU coding standards say to use
233                      LINENO-1.COLUMN-1-COLUMN-2 for this case, but GNU
234                      Emacs interprets COLUMN-2 as LINENO-2 if I do that.
235                      I've submitted an Emacs bug report:
236                      http://debbugs.gnu.org/cgi/bugreport.cgi?bug=7725.
237
238                      For now, let's be compatible. */
239                   ds_put_format (s, "%d.%d-%d.%d", l1, c1, l1, c2);
240                 }
241               else
242                 ds_put_format (s, "%d.%d", l1, c1);
243             }
244           else
245             ds_put_format (s, "%d", l1);
246         }
247     }
248   else if (c1 > 0)
249     {
250       if (c2 > c1)
251         ds_put_format (s, ".%d-%d", c1, c2);
252       else
253         ds_put_format (s, ".%d", c1);
254     }
255 }
256 \f
257 /* msg_stack */
258
259 void
260 msg_stack_destroy (struct msg_stack *stack)
261 {
262   if (stack)
263     {
264       msg_location_destroy (stack->location);
265       free (stack->description);
266       free (stack);
267     }
268 }
269
270 struct msg_stack *
271 msg_stack_dup (const struct msg_stack *src)
272 {
273   struct msg_stack *dst = xmalloc (sizeof *src);
274   *dst = (struct msg_stack) {
275     .location = msg_location_dup (src->location),
276     .description = xstrdup_if_nonnull (src->description),
277   };
278   return dst;
279 }
280 \f
281 /* Working with messages. */
282
283 const char *
284 msg_severity_to_string (enum msg_severity severity)
285 {
286   switch (severity)
287     {
288     case MSG_S_ERROR:
289       return _("error");
290     case MSG_S_WARNING:
291       return _("warning");
292     case MSG_S_NOTE:
293     default:
294       return _("note");
295     }
296 }
297
298 /* Duplicate a message */
299 struct msg *
300 msg_dup (const struct msg *src)
301 {
302   struct msg_stack **ms = xmalloc (src->n_stack * sizeof *ms);
303   for (size_t i = 0; i < src->n_stack; i++)
304     ms[i] = msg_stack_dup (src->stack[i]);
305
306   struct msg *dst = xmalloc (sizeof *dst);
307   *dst = (struct msg) {
308     .category = src->category,
309     .severity = src->severity,
310     .stack = ms,
311     .n_stack = src->n_stack,
312     .location = msg_location_dup (src->location),
313     .command_name = xstrdup_if_nonnull (src->command_name),
314     .text = xstrdup (src->text),
315   };
316   return dst;
317 }
318
319 /* Frees a message created by msg_dup().
320
321    (Messages not created by msg_dup(), as well as their file_name
322    members, are typically not dynamically allocated, so this function should
323    not be used to destroy them.) */
324 void
325 msg_destroy (struct msg *m)
326 {
327   if (m)
328     {
329       for (size_t i = 0; i < m->n_stack; i++)
330         msg_stack_destroy (m->stack[i]);
331       free (m->stack);
332       msg_location_destroy (m->location);
333       free (m->text);
334       free (m->command_name);
335       free (m);
336     }
337 }
338
339 char *
340 msg_to_string (const struct msg *m)
341 {
342   struct string s;
343
344   ds_init_empty (&s);
345
346   for (size_t i = 0; i < m->n_stack; i++)
347     {
348       const struct msg_stack *ms = m->stack[i];
349       if (!msg_location_is_empty (ms->location))
350         {
351           msg_location_format (ms->location, &s);
352           ds_put_cstr (&s, ": ");
353         }
354       ds_put_format (&s, "%s\n", ms->description);
355     }
356   if (m->category != MSG_C_GENERAL && !msg_location_is_empty (m->location))
357     {
358       msg_location_format (m->location, &s);
359       ds_put_cstr (&s, ": ");
360     }
361
362   ds_put_format (&s, "%s: ", msg_severity_to_string (m->severity));
363
364   if (m->category == MSG_C_SYNTAX && m->command_name != NULL)
365     ds_put_format (&s, "%s: ", m->command_name);
366
367   ds_put_cstr (&s, m->text);
368
369   const struct msg_location *loc = m->location;
370   if (m->category != MSG_C_GENERAL
371       && loc->src && loc->start.line && loc->start.column
372       && msg_handler.lex_source_get_line)
373     {
374       int l0 = loc->start.line;
375       int l1 = loc->end.line;
376       int nl = l1 - l0;
377       for (int ln = l0; ln <= l1; ln++)
378         {
379           if (nl > 3 && ln == l0 + 2)
380             {
381               ds_put_cstr (&s, "\n  ... |");
382               ln = l1;
383             }
384
385           struct substring line = msg_handler.lex_source_get_line (
386             loc->src, ln);
387           ss_rtrim (&line, ss_cstr ("\n\r"));
388
389           ds_put_format (&s, "\n%5d | ", ln);
390           ds_put_substring (&s, line);
391
392           int c0 = ln == l0 ? loc->start.column : 1;
393           int c1 = ln == l1 ? loc->end.column : ss_utf8_count_columns (line);
394           if (c0 > 0 && c1 >= c0)
395             {
396               ds_put_cstr (&s, "\n      |");
397               ds_put_byte_multiple (&s, ' ', c0);
398               if (ln == l0)
399                 {
400                   ds_put_byte (&s, '^');
401                   if (c1 > c0)
402                     ds_put_byte_multiple (&s, '~', c1 - c0);
403                 }
404               else
405                 ds_put_byte_multiple (&s, '-', c1 - c0 + 1);
406             }
407         }
408     }
409
410   return ds_cstr (&s);
411 }
412 \f
413
414 /* Number of messages reported, by severity level. */
415 static int counts[MSG_N_SEVERITIES];
416
417 /* True after the maximum number of errors or warnings has been exceeded. */
418 static bool too_many_errors;
419
420 /* True after the maximum number of notes has been exceeded. */
421 static bool too_many_notes;
422
423 /* True iff warnings have been explicitly disabled (MXWARNS = 0) */
424 static bool warnings_off = false;
425
426 /* Checks whether we've had so many errors that it's time to quit
427    processing this syntax file. */
428 bool
429 msg_ui_too_many_errors (void)
430 {
431   return too_many_errors;
432 }
433
434 void
435 msg_ui_disable_warnings (bool x)
436 {
437   warnings_off = x;
438 }
439
440
441 void
442 msg_ui_reset_counts (void)
443 {
444   int i;
445
446   for (i = 0; i < MSG_N_SEVERITIES; i++)
447     counts[i] = 0;
448   too_many_errors = false;
449   too_many_notes = false;
450 }
451
452 bool
453 msg_ui_any_errors (void)
454 {
455   return counts[MSG_S_ERROR] > 0;
456 }
457
458
459 static void
460 ship_message (const struct msg *m)
461 {
462   enum { MAX_STACK = 4 };
463   static const struct msg *stack[MAX_STACK];
464   static size_t n;
465
466   /* If we're recursing on a given message, or recursing deeply, drop it. */
467   if (n >= MAX_STACK)
468     return;
469   for (size_t i = 0; i < n; i++)
470     if (stack[i] == m)
471       return;
472
473   stack[n++] = m;
474   if (msg_handler.output_msg && n <= 1)
475     msg_handler.output_msg (m, msg_handler.aux);
476   else
477     fprintf (stderr, "%s\n", m->text);
478   n--;
479 }
480
481 static void
482 submit_note (char *s)
483 {
484   struct msg m = {
485     .category = MSG_C_GENERAL,
486     .severity = MSG_S_NOTE,
487     .text = s,
488   };
489   ship_message (&m);
490
491   free (s);
492 }
493
494 static void
495 process_msg (struct msg *m)
496 {
497   int n_msgs, max_msgs;
498
499   if (too_many_errors
500       || (too_many_notes && m->severity == MSG_S_NOTE)
501       || (warnings_off && m->severity == MSG_S_WARNING))
502     return;
503
504   ship_message (m);
505
506   counts[m->severity]++;
507   max_msgs = settings_get_max_messages (m->severity);
508   n_msgs = counts[m->severity];
509   if (m->severity == MSG_S_WARNING)
510     n_msgs += counts[MSG_S_ERROR];
511   if (n_msgs > max_msgs)
512     {
513       if (m->severity == MSG_S_NOTE)
514         {
515           too_many_notes = true;
516           submit_note (xasprintf (_("Notes (%d) exceed limit (%d).  "
517                                     "Suppressing further notes."),
518                                   n_msgs, max_msgs));
519         }
520       else
521         {
522           too_many_errors = true;
523           if (m->severity == MSG_S_WARNING)
524             submit_note (xasprintf (_("Warnings (%d) exceed limit (%d).  Syntax processing will be halted."),
525                                     n_msgs, max_msgs));
526           else
527             submit_note (xasprintf (_("Errors (%d) exceed limit (%d).  Syntax processing will be halted."),
528                                     n_msgs, max_msgs));
529         }
530     }
531 }
532
533
534 /* Emits M as an error message.  Takes ownership of M. */
535 void
536 msg_emit (struct msg *m)
537 {
538   if (!messages_disabled)
539     process_msg (m);
540   msg_destroy (m);
541 }
542
543 /* Disables message output until the next call to msg_enable.  If
544    this function is called multiple times, msg_enable must be
545    called an equal number of times before messages are actually
546    re-enabled. */
547 void
548 msg_disable (void)
549 {
550   messages_disabled++;
551 }
552
553 /* Enables message output that was disabled by msg_disable. */
554 void
555 msg_enable (void)
556 {
557   assert (messages_disabled > 0);
558   messages_disabled--;
559 }
560 \f
561 /* Private functions. */
562
563 static char fatal_error_message[1024];
564 static int fatal_error_message_bytes = 0;
565
566 static char diagnostic_information[1024];
567 static int diagnostic_information_bytes = 0;
568
569 static int
570 append_message (char *msg, int bytes_used, const char *fmt, ...)
571 {
572   va_list va;
573   va_start (va, fmt);
574   int ret = vsnprintf (msg + bytes_used, 1024 - bytes_used, fmt, va);
575   va_end (va);
576   assert (ret >= 0);
577
578   return ret;
579 }
580
581
582 /* Generate a row of asterisks held in statically allocated memory  */
583 static struct substring
584 generate_banner (void)
585 {
586   static struct substring banner;
587   if (!banner.string)
588     banner = ss_cstr ("******************************************************\n");
589   return banner;
590 }
591
592 const char *
593 prepare_fatal_error_message (void)
594 {
595   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, generate_banner ().string);
596
597   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "You have discovered a bug in PSPP.  Please report this\n");
598   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "to " PACKAGE_BUGREPORT ".  Please include this entire\n");
599   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "message, *plus* several lines of output just above it.\n");
600   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "For the best chance at having the bug fixed, also\n");
601   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "include the syntax file that triggered it and a sample\n");
602   fatal_error_message_bytes += append_message (fatal_error_message, fatal_error_message_bytes, "of any data file used for input.\n");
603   return fatal_error_message;
604 }
605
606 const char *
607 prepare_diagnostic_information (void)
608 {
609   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "version:             %s\n", version);
610   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "host_system:         %s\n", host_system);
611   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "build_system:        %s\n", build_system);
612   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "locale_dir:          %s\n", relocate (locale_dir));
613   diagnostic_information_bytes += append_message (diagnostic_information, diagnostic_information_bytes, "compiler version:    %s\n",
614 #ifdef __VERSION__
615            __VERSION__
616 #else
617            "Unknown"
618 #endif
619 );
620
621   return diagnostic_information;
622 }
623
624 void
625 request_bug_report (const char *msg)
626 {
627   write (STDERR_FILENO, fatal_error_message, fatal_error_message_bytes);
628   write (STDERR_FILENO, "proximate cause:     ", 21);
629   write (STDERR_FILENO, msg, strlen (msg));
630   write (STDERR_FILENO, "\n", 1);
631   write (STDERR_FILENO, diagnostic_information, diagnostic_information_bytes);
632   const struct substring banner = generate_banner ();
633   write (STDERR_FILENO, banner.string, banner.length);
634 }