File Coverage

File:/usr/local/share/automake-1.11/Automake/Channels.pm
Coverage:39.2%

linestmtbrancondsubpodtimecode
1# Copyright (C) 2002, 2004, 2006, 2008 Free Software Foundation, Inc.
2
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 2, or (at your option)
6# any later version.
7
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU General Public License for more details.
12
13# You should have received a copy of the GNU General Public License
14# along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16###############################################################
17# The main copy of this file is in Automake's CVS repository. #
18# Updates should be sent to automake-patches@gnu.org. #
19###############################################################
20
21package Automake::Channels;
22
23 - 67
=head1 NAME

Automake::Channels - support functions for error and warning management

=head1 SYNOPSIS

  use Automake::Channels;

  # Register a channel to output warnings about unused variables.
  register_channel 'unused', type => 'warning';

  # Register a channel for system errors.
  register_channel 'system', type => 'error', exit_code => 4;

  # Output a message on channel 'unused'.
  msg 'unused', "$file:$line", "unused variable `$var'";

  # Make the 'unused' channel silent.
  setup_channel 'unused', silent => 1;

  # Turn on all channels of type 'warning'.
  setup_channel_type 'warning', silent => 0;

  # Redirect all channels to push messages on a Thread::Queue using
  # the specified serialization key.
  setup_channel_queue $queue, $key;

  # Output a message pending in a Thread::Queue.
  pop_channel_queue $queue;

  # Treat all warnings as errors.
  $warnings_are_errors = 1;

  # Exit with the greatest exit code encountered so far.
  exit $exit_code;

=head1 DESCRIPTION

This perl module provides support functions for handling diagnostic
channels in programs.  Channels can be registered to convey fatal,
error, warning, or debug messages.  Each channel has various options
(e.g. is the channel silent, should duplicate messages be removed,
etc.) that can also be overridden on a per-message basis.

=cut
68
69
1
1
1
33
4
1
use 5.005;
70
1
1
1
3
2
3
use strict;
71
1
1
1
4
1
3
use Exporter;
72
1
1
1
4
0
3
use Carp;
73
1
1
1
4
1
3
use File::Basename;
74
75
1
1
1
4
1
3
use vars qw (@ISA @EXPORT %channels $me);
76
77@ISA = qw (Exporter);
78@EXPORT = qw ($exit_code $warnings_are_errors
79              &reset_local_duplicates &reset_global_duplicates
80              &register_channel &msg &exists_channel &channel_type
81              &setup_channel &setup_channel_type
82              &dup_channel_setup &drop_channel_setup
83              &buffer_messages &flush_messages
84              &setup_channel_queue &pop_channel_queue
85              US_GLOBAL US_LOCAL
86              UP_NONE UP_TEXT UP_LOC_TEXT);
87
88$me = basename $0;
89
90 - 99
=head2 Global Variables

=over 4

=item C<$exit_code>

The greatest exit code seen so far. C<$exit_code> is updated from
the C<exit_code> options of C<fatal> and C<error> channels.

=cut
100
101
1
1
1
4
0
11
use vars qw ($exit_code);
102$exit_code = 0;
103
104 - 109
=item C<$warnings_are_errors>

Set this variable to 1 if warning messages should be treated as
errors (i.e. if they should update C<$exit_code>).

=cut
110
111
1
1
1
3
1
6
use vars qw ($warnings_are_errors);
112$warnings_are_errors = 0;
113
114=back
115
116 - 130
=head2 Constants

=over 4

=item C<UP_NONE>, C<UP_TEXT>, C<UP_LOC_TEXT>

Possible values for the C<uniq_part> options.  This selects the part
of the message that should be considered when filtering out duplicates.
If C<UP_LOC_TEXT> is used, the location and the explanation message
are used for filtering.  If C<UP_TEXT> is used, only the explanation
message is used (so the same message will be filtered out if it appears
at different locations).  C<UP_NONE> means that duplicate messages
should be output.

=cut
131
132
1
1
1
4
1
7
use constant UP_NONE => 0;
133
1
1
1
6
1
3
use constant UP_TEXT => 1;
134
1
1
1
4
0
3
use constant UP_LOC_TEXT => 2;
135
136 - 145
=item C<US_LOCAL>, C<US_GLOBAL>

Possible values for the C<uniq_scope> options.
Use C<US_GLOBAL> for error messages that should be printed only
once during the execution of the program, C<US_LOCAL> for message that
should be printed only once per file.  (Actually, C<Channels> does not
do this now when files are changed, it relies on you calling
C<reset_local_duplicates> when this happens.)

=cut
146
147# possible values for uniq_scope
148
1
1
1
4
2
2
use constant US_LOCAL => 0;
149
1
1
1
3
4
2
use constant US_GLOBAL => 1;
150
151=back
152
153 - 256
=head2 Options

Channels accept the options described below.  These options can be
passed as a hash to the C<register_channel>, C<setup_channel>, and C<msg>
functions.  The possible keys, with their default value are:

=over

=item C<type =E<gt> 'warning'>

The type of the channel.  One of C<'debug'>, C<'warning'>, C<'error'>, or
C<'fatal'>.  Fatal messages abort the program when they are output.
Error messages update the exit status.  Debug and warning messages are
harmless, except that warnings can be treated as errors of
C<$warnings_are_errors> is set.

=item C<exit_code =E<gt> 1>

The value to update C<$exit_code> with when a fatal or error message
is emitted.  C<$exit_code> is also updated for warnings output
when @<$warnings_are_errors> is set.

=item C<file =E<gt> \*STDERR>

The file where the error should be output.

=item C<silent =E<gt> 0>

Whether the channel should be silent.  Use this do disable a
category of warning, for instance.

=item C<ordered =E<gt> 1>

Whether, with multi-threaded execution, the message should be queued
for ordered output.

=item C<uniq_part =E<gt> UP_LOC_TEXT>

The part of the message subject to duplicate filtering.  See the
documentation for the C<UP_NONE>, C<UP_TEXT>, and C<UP_LOC_TEXT>
constants above.

C<uniq_part> can also be set to an arbitrary string that will be used
instead of the message when considering duplicates.

=item C<uniq_scope =E<gt> US_LOCAL>

The scope of duplicate filtering.  See the documentation for the
C<US_LOCAL>, and C<US_GLOBAL> constants above.

=item C<header =E<gt> ''>

A string to prepend to each message emitted through this channel.

=item C<footer =E<gt> ''>

A string to append to each message emitted through this channel.

=item C<backtrace =E<gt> 0>

Die with a stack backtrace after displaying the message.

=item C<partial =E<gt> 0>

When set, indicates a partial message that should
be output along with the next message with C<partial> unset.
Several partial messages can be stacked this way.

Duplicate filtering will apply to the I<global> message resulting from
all I<partial> messages, using the options from the last (non-partial)
message.  Linking associated messages is the main reason to use this
option.

For instance the following messages

  msg 'channel', 'foo:2', 'redefinition of A ...';
  msg 'channel', 'foo:1', '... A previously defined here';
  msg 'channel', 'foo:3', 'redefinition of A ...';
  msg 'channel', 'foo:1', '... A previously defined here';

will result in

 foo:2: redefinition of A ...
 foo:1: ... A previously defined here
 foo:3: redefinition of A ...

where the duplicate "I<... A previously defined here>" has been
filtered out.

Linking these messages using C<partial> as follows will prevent the
fourth message to disappear.

  msg 'channel', 'foo:2', 'redefinition of A ...', partial => 1;
  msg 'channel', 'foo:1', '... A previously defined here';
  msg 'channel', 'foo:3', 'redefinition of A ...', partial => 1;
  msg 'channel', 'foo:1', '... A previously defined here';

Note that because the stack of C<partial> messages is printed with the
first non-C<partial> message, most options of C<partial> messages will
be ignored.

=back

=cut
257
258
1
2
use vars qw (%_default_options %_global_duplicate_messages
259
1
1
4
1
             %_local_duplicate_messages);
260
261# Default options for a channel.
262%_default_options =
263  (
264   type => 'warning',
265   exit_code => 1,
266   file => \*STDERR,
267   silent => 0,
268   ordered => 1,
269   queue => 0,
270   queue_key => undef,
271   uniq_scope => US_LOCAL,
272   uniq_part => UP_LOC_TEXT,
273   header => '',
274   footer => '',
275   backtrace => 0,
276   partial => 0,
277   );
278
279# Filled with output messages as keys, to detect duplicates.
280# The value associated with each key is the number of occurrences
281# filtered out.
282%_local_duplicate_messages = ();
283%_global_duplicate_messages = ();
284
285sub _reset_duplicates (\%)
286{
287
0
0
  my ($ref) = @_;
288
0
0
  my $dup = 0;
289
0
0
  foreach my $k (keys %$ref)
290    {
291
0
0
      $dup += $ref->{$k};
292    }
293
0
0
  %$ref = ();
294
0
0
  return $dup;
295}
296
297
298 - 307
=head2 Functions

=over 4

=item C<reset_local_duplicates ()>

Reset local duplicate messages (see C<US_LOCAL>), and
return the number of messages that have been filtered out.

=cut
308
309sub reset_local_duplicates ()
310{
311
0
1
0
  return _reset_duplicates %_local_duplicate_messages;
312}
313
314 - 319
=item C<reset_global_duplicates ()>

Reset local duplicate messages (see C<US_GLOBAL>), and
return the number of messages that have been filtered out.

=cut
320
321sub reset_global_duplicates ()
322{
323
0
1
0
  return _reset_duplicates %_global_duplicate_messages;
324}
325
326sub _merge_options (\%%)
327{
328
85
131
  my ($hash, %options) = @_;
329
85
85
  local $_;
330
331
85
171
  foreach (keys %options)
332    {
333
37
61
      if (exists $hash->{$_})
334        {
335
37
81
          $hash->{$_} = $options{$_}
336        }
337      else
338        {
339
0
0
          confess "unknown option `$_'";
340        }
341    }
342
85
241
  if ($hash->{'ordered'})
343    {
344
17
39
      confess "fatal messages cannot be ordered"
345        if $hash->{'type'} eq 'fatal';
346
17
49
      confess "backtrace cannot be output on ordered messages"
347        if $hash->{'backtrace'};
348    }
349}
350
351 - 356
=item C<register_channel ($name, [%options])>

Declare channel C<$name>, and override the default options
with those listed in C<%options>.

=cut
357
358sub register_channel ($;%)
359{
360
15
1
34
  my ($name, %options) = @_;
361
15
80
  my %channel_opts = %_default_options;
362
15
43
  _merge_options %channel_opts, %options;
363
15
66
  $channels{$name} = \%channel_opts;
364}
365
366 - 370
=item C<exists_channel ($name)>

Returns true iff channel C<$name> has been registered.

=cut
371
372sub exists_channel ($)
373{
374
0
1
0
  my ($name) = @_;
375
0
0
  return exists $channels{$name};
376}
377
378 - 383
=item C<channel_type ($name)>

Returns the type of channel C<$name> if it has been registered.
Returns the empty string otherwise.

=cut
384
385sub channel_type ($)
386{
387
0
1
0
  my ($name) = @_;
388
0
0
  return $channels{$name}{'type'} if exists_channel $name;
389
0
0
  return '';
390}
391
392# _format_sub_message ($LEADER, $MESSAGE)
393# ---------------------------------------
394# Split $MESSAGE at new lines and add $LEADER to each line.
395sub _format_sub_message ($$)
396{
397
0
0
  my ($leader, $message) = @_;
398
0
0
  return $leader . join ("\n" . $leader, split ("\n", $message)) . "\n";
399}
400
401# _format_message ($LOCATION, $MESSAGE, %OPTIONS)
402# -----------------------------------------------
403# Format the message. Return a string ready to print.
404sub _format_message ($$%)
405{
406
0
0
  my ($location, $message, %opts) = @_;
407
0
0
  my $msg = '';
408
0
0
  if (ref $location)
409    {
410      # If $LOCATION is a reference, assume it's an instance of the
411      # Automake::Location class and display contexts.
412
0
0
      my $loc = $location->get || $me;
413
0
0
      $msg = _format_sub_message ("$loc: ", $opts{'header'}
414                                  . $message . $opts{'footer'});
415
0
0
      for my $pair ($location->get_contexts)
416        {
417
0
0
          $msg .= _format_sub_message ($pair->[0] . ": ", $pair->[1]);
418        }
419    }
420  else
421    {
422
0
0
      $location ||= $me;
423
0
0
      $msg = _format_sub_message ("$location: ", $opts{'header'}
424                                  . $message . $opts{'footer'});
425    }
426
0
0
  return $msg;
427}
428
429# _enqueue ($QUEUE, $KEY, $UNIQ_SCOPE, $TO_FILTER, $MSG, $FILE)
430# ------------------------------------------------------------
431# Push message on a queue, to be processed by another thread.
432sub _enqueue ($$$$$$)
433{
434
0
0
  my ($queue, $key, $uniq_scope, $to_filter, $msg, $file) = @_;
435
0
0
  $queue->enqueue ($key, $msg, $to_filter, $uniq_scope);
436
0
0
  confess "message queuing works only for STDERR"
437    if $file ne \*STDERR;
438}
439
440# _dequeue ($QUEUE)
441# -----------------
442# Pop a message from a queue, and print, similarly to how
443# _print_message would do it. Return 0 if the queue is
444# empty. Note that the key has already been dequeued.
445sub _dequeue ($)
446{
447
0
0
  my ($queue) = @_;
448
0
0
  my $msg = $queue->dequeue || return 0;
449
0
0
  my $to_filter = $queue->dequeue;
450
0
0
  my $uniq_scope = $queue->dequeue;
451
0
0
  my $file = \*STDERR;
452
453
0
0
  if ($to_filter ne '')
454    {
455      # Do we want local or global uniqueness?
456
0
0
      my $dups;
457
0
0
      if ($uniq_scope == US_LOCAL)
458        {
459
0
0
          $dups = \%_local_duplicate_messages;
460        }
461      elsif ($uniq_scope == US_GLOBAL)
462        {
463
0
0
          $dups = \%_global_duplicate_messages;
464        }
465      else
466        {
467
0
0
          confess "unknown value for uniq_scope: " . $uniq_scope;
468        }
469
470      # Update the hash of messages.
471
0
0
      if (exists $dups->{$to_filter})
472        {
473
0
0
          ++$dups->{$to_filter};
474
0
0
          return 1;
475        }
476      else
477        {
478
0
0
          $dups->{$to_filter} = 0;
479        }
480    }
481
0
0
  print $file $msg;
482
0
0
  return 1;
483}
484
485
486# Store partial messages here. (See the 'partial' option.)
487
1
1
1
4
1
6
use vars qw ($partial);
488$partial = '';
489
490# _print_message ($LOCATION, $MESSAGE, %OPTIONS)
491# ----------------------------------------------
492# Format the message, check duplicates, and print it.
493sub _print_message ($$%)
494{
495
65
243
  my ($location, $message, %opts) = @_;
496
497
65
394
  return 0 if ($opts{'silent'});
498
499
0
0
  my $msg = _format_message ($location, $message, %opts);
500
0
0
  if ($opts{'partial'})
501    {
502      # Incomplete message. Store, don't print.
503
0
0
      $partial .= $msg;
504
0
0
      return;
505    }
506  else
507    {
508      # Prefix with any partial message send so far.
509
0
0
      $msg = $partial . $msg;
510
0
0
      $partial = '';
511    }
512
513  # Check for duplicate message if requested.
514
0
0
  my $to_filter;
515
0
0
  if ($opts{'uniq_part'} ne UP_NONE)
516    {
517      # Which part of the error should we match?
518
0
0
      if ($opts{'uniq_part'} eq UP_TEXT)
519        {
520
0
0
          $to_filter = $message;
521        }
522      elsif ($opts{'uniq_part'} eq UP_LOC_TEXT)
523        {
524
0
0
          $to_filter = $msg;
525        }
526      else
527        {
528
0
0
          $to_filter = $opts{'uniq_part'};
529        }
530
531      # Do we want local or global uniqueness?
532
0
0
      my $dups;
533
0
0
      if ($opts{'uniq_scope'} == US_LOCAL)
534        {
535
0
0
          $dups = \%_local_duplicate_messages;
536        }
537      elsif ($opts{'uniq_scope'} == US_GLOBAL)
538        {
539
0
0
          $dups = \%_global_duplicate_messages;
540        }
541      else
542        {
543
0
0
          confess "unknown value for uniq_scope: " . $opts{'uniq_scope'};
544        }
545
546      # Update the hash of messages.
547
0
0
      if (exists $dups->{$to_filter})
548        {
549
0
0
          ++$dups->{$to_filter};
550
0
0
          return 0;
551        }
552      else
553        {
554
0
0
          $dups->{$to_filter} = 0;
555        }
556    }
557
0
0
  my $file = $opts{'file'};
558
0
0
  if ($opts{'ordered'} && $opts{'queue'})
559    {
560
0
0
      _enqueue ($opts{'queue'}, $opts{'queue_key'}, $opts{'uniq_scope'},
561                $to_filter, $msg, $file);
562    }
563  else
564    {
565
0
0
      print $file $msg;
566    }
567
0
0
  return 1;
568}
569
570 - 613
=item C<msg ($channel, $location, $message, [%options])>

Emit a message on C<$channel>, overriding some options of the channel with
those specified in C<%options>.  Obviously C<$channel> must have been
registered with C<register_channel>.

C<$message> is the text of the message, and C<$location> is a location
associated to the message.

For instance to complain about some unused variable C<mumble>
declared at line 10 in F<foo.c>, one could do:

  msg 'unused', 'foo.c:10', "unused variable `mumble'";

If channel C<unused> is not silent (and if this message is not a duplicate),
the following would be output:

  foo.c:10: unused variable `mumble'

C<$location> can also be an instance of C<Automake::Location>.  In this
case, the stack of contexts will be displayed in addition.

If C<$message> contains newline characters, C<$location> is prepended
to each line.  For instance,

  msg 'error', 'somewhere', "1st line\n2nd line";

becomes

  somewhere: 1st line
  somewhere: 2nd line

If C<$location> is an empty string, it is replaced by the name of the
program.  Actually, if you don't use C<%options>, you can even
elide the empty C<$location>.  Thus

  msg 'fatal', '', 'fatal error';
  msg 'fatal', 'fatal error';

both print

  progname: fatal error

=cut
614
615
616
1
1
1
4
1
3
use vars qw (@backlog %buffering);
617
618# See buffer_messages() and flush_messages() below.
619%buffering = (); # The map of channel types to buffer.
620@backlog = (); # The buffer of messages.
621
622sub msg ($$;$%)
623{
624
65
1
125
  my ($channel, $location, $message, %options) = @_;
625
626
65
118
  if (! defined $message)
627    {
628
0
0
      $message = $location;
629
0
0
      $location = '';
630    }
631
632
65
127
  confess "unknown channel $channel" unless exists $channels{$channel};
633
634
65
65
60
324
  my %opts = %{$channels{$channel}};
635
65
173
  _merge_options (%opts, %options);
636
637
65
138
  if (exists $buffering{$opts{'type'}})
638    {
639
0
0
      push @backlog, [$channel, $location->clone, $message, %options];
640
0
0
      return;
641    }
642
643  # Print the message if needed.
644
65
195
  if (_print_message ($location, $message, %opts))
645    {
646      # Adjust exit status.
647
0
0
      if ($opts{'type'} eq 'error'
648          || $opts{'type'} eq 'fatal'
649          || ($opts{'type'} eq 'warning' && $warnings_are_errors))
650        {
651
0
0
          my $es = $opts{'exit_code'};
652
0
0
          $exit_code = $es if $es > $exit_code;
653        }
654
655      # Die on fatal messages.
656
0
0
      confess if $opts{'backtrace'};
657
0
0
      if ($opts{'type'} eq 'fatal')
658        {
659          # flush messages explicitly here, needed in worker threads.
660
0
0
          STDERR->flush;
661
0
0
          exit $exit_code;
662        }
663    }
664}
665
666
667 - 671
=item C<setup_channel ($channel, %options)>

Override the options of C<$channel> with those specified by C<%options>.

=cut
672
673sub setup_channel ($%)
674{
675
5
1
11
  my ($name, %opts) = @_;
676
5
13
  confess "channel $name doesn't exist" unless exists $channels{$name};
677
5
5
5
15
  _merge_options %{$channels{$name}}, %opts;
678}
679
680 - 685
=item C<setup_channel_type ($type, %options)>

Override the options of any channel of type C<$type>
with those specified by C<%options>.

=cut
686
687sub setup_channel_type ($%)
688{
689
0
1
  my ($type, %opts) = @_;
690
0
  foreach my $channel (keys %channels)
691    {
692
0
      setup_channel $channel, %opts
693        if $channels{$channel}{'type'} eq $type;
694    }
695}
696
697 - 710
=item C<dup_channel_setup ()>, C<drop_channel_setup ()>

Sometimes it is necessary to make temporary modifications to channels.
For instance one may want to disable a warning while processing a
particular file, and then restore the initial setup.  These two
functions make it easy: C<dup_channel_setup ()> saves a copy of the
current configuration for later restoration by
C<drop_channel_setup ()>.

You can think of this as a stack of configurations whose first entry
is the active one.  C<dup_channel_setup ()> duplicates the first
entry, while C<drop_channel_setup ()> just deletes it.

=cut
711
712
1
1
1
4
1
2
use vars qw (@_saved_channels);
713@_saved_channels = ();
714
715sub dup_channel_setup ()
716{
717
0
1
  my %channels_copy;
718
0
  foreach my $k1 (keys %channels)
719    {
720
0
0
      $channels_copy{$k1} = {%{$channels{$k1}}};
721    }
722
0
  push @_saved_channels, \%channels_copy;
723}
724
725sub drop_channel_setup ()
726{
727
0
1
  my $saved = pop @_saved_channels;
728
0
  %channels = %$saved;
729}
730
731 - 751
=item C<buffer_messages (@types)>, C<flush_messages ()>

By default, when C<msg> is called, messages are processed immediately.

Sometimes it is necessary to delay the output of messages.
For instance you might want to make diagnostics before
channels have been completely configured.

After C<buffer_messages(@types)> has been called, messages sent with
C<msg> to a channel whose type is listed in C<@types> will be stored in a
list for later processing.

This backlog of messages is processed when C<flush_messages> is
called, with the current channel options (not the options in effect,
at the time of C<msg>).  So for instance, if some channel was silenced
in the meantime, messages to this channel will not be printed.

C<flush_messages> cancels the effect of C<buffer_messages>.  Following
calls to C<msg> are processed immediately as usual.

=cut
752
753sub buffer_messages (@)
754{
755
0
1
  foreach my $type (@_)
756    {
757
0
      $buffering{$type} = 1;
758    }
759}
760
761sub flush_messages ()
762{
763
0
1
  %buffering = ();
764
0
  foreach my $args (@backlog)
765    {
766
0
      &msg (@$args);
767    }
768
0
  @backlog = ();
769}
770
771 - 776
=item C<setup_channel_queue ($queue, $key)>

Set the queue to fill for each channel that is ordered,
and the key to use for serialization.

=cut
777sub setup_channel_queue ($$)
778{
779
0
1
  my ($queue, $key) = @_;
780
0
  foreach my $channel (keys %channels)
781    {
782
0
      setup_channel $channel, queue => $queue, queue_key => $key
783        if $channels{$channel}{'ordered'};
784    }
785}
786
787 - 791
=item C<pop_channel_queue ($queue)>

pop a message off the $queue; the key has already been popped.

=cut
792sub pop_channel_queue ($)
793{
794
0
1
  my ($queue) = @_;
795
0
  return _dequeue ($queue);
796}
797
798=back
799
800 - 808
=head1 SEE ALSO

L<Automake::Location>

=head1 HISTORY

Written by Alexandre Duret-Lutz E<lt>F<adl@gnu.org>E<gt>.

=cut
809
8101;
811
812### Setup "GNU" style for perl-mode and cperl-mode.
813## Local Variables:
814## perl-indent-level: 2
815## perl-continued-statement-offset: 2
816## perl-continued-brace-offset: 0
817## perl-brace-offset: 0
818## perl-brace-imaginary-offset: 0
819## perl-label-offset: -2
820## cperl-indent-level: 2
821## cperl-brace-offset: 0
822## cperl-continued-brace-offset: 0
823## cperl-label-offset: -2
824## cperl-extra-newline-before-brace: t
825## cperl-merge-trailing-else: nil
826## cperl-continued-statement-offset: 2
827## End: