<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># Copyright (C) 2002-2021 Free Software Foundation, Inc.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see &lt;https://www.gnu.org/licenses/&gt;.

###############################################################
# The main copy of this file is in Automake's git repository. #
# Updates should be sent to automake-patches@gnu.org.         #
###############################################################

package Automake::Channels;

=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 =&gt; 'warning';

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

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

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

  # Turn on all channels of type 'warning'.
  setup_channel_type 'warning', silent =&gt; 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

use 5.006;
use strict;
use warnings FATAL =&gt; 'all';

use Carp;
use Exporter;
use File::Basename;

our @ISA = qw (Exporter);
our @EXPORT = qw ($exit_code $warnings_are_errors
		  &amp;reset_local_duplicates &amp;reset_global_duplicates
		  &amp;register_channel &amp;msg &amp;exists_channel &amp;channel_type
		  &amp;setup_channel &amp;setup_channel_type
		  &amp;dup_channel_setup &amp;drop_channel_setup
		  &amp;buffer_messages &amp;flush_messages
		  &amp;setup_channel_queue &amp;pop_channel_queue
		  US_GLOBAL US_LOCAL
		  UP_NONE UP_TEXT UP_LOC_TEXT);

our %channels;
our $me = basename $0;

=head2 Global Variables

=over 4

=item C&lt;$exit_code&gt;

The greatest exit code seen so far. C&lt;$exit_code&gt; is updated from
the C&lt;exit_code&gt; options of C&lt;fatal&gt; and C&lt;error&gt; channels.

=cut

our $exit_code = 0;

=item C&lt;$warnings_are_errors&gt;

Set this variable to 1 if warning messages should be treated as
errors (i.e. if they should update C&lt;$exit_code&gt;).

=cut

our $warnings_are_errors = 0;

=back

=head2 Constants

=over 4

=item C&lt;UP_NONE&gt;, C&lt;UP_TEXT&gt;, C&lt;UP_LOC_TEXT&gt;

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

=cut

use constant UP_NONE =&gt; 0;
use constant UP_TEXT =&gt; 1;
use constant UP_LOC_TEXT =&gt; 2;

=item C&lt;US_LOCAL&gt;, C&lt;US_GLOBAL&gt;

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

=cut

# possible values for uniq_scope
use constant US_LOCAL =&gt; 0;
use constant US_GLOBAL =&gt; 1;

=back

=head2 Options

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

=over

=item C&lt;type =E&lt;gt&gt; 'warning'&gt;

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

=item C&lt;exit_code =E&lt;gt&gt; 1&gt;

The value to update C&lt;$exit_code&gt; with when a fatal or error message
is emitted.  C&lt;$exit_code&gt; is also updated for warnings output
when C&lt;$warnings_are_errors&gt; is set.

=item C&lt;file =E&lt;gt&gt; \*STDERR&gt;

The file where the error should be output.

=item C&lt;silent =E&lt;gt&gt; 0&gt;

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

=item C&lt;ordered =E&lt;gt&gt; 1&gt;

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

=item C&lt;uniq_part =E&lt;gt&gt; UP_LOC_TEXT&gt;

The part of the message subject to duplicate filtering.  See the
documentation for the C&lt;UP_NONE&gt;, C&lt;UP_TEXT&gt;, and C&lt;UP_LOC_TEXT&gt;
constants above.

C&lt;uniq_part&gt; can also be set to an arbitrary string that will be used
instead of the message when considering duplicates.

=item C&lt;uniq_scope =E&lt;gt&gt; US_LOCAL&gt;

The scope of duplicate filtering.  See the documentation for the
C&lt;US_LOCAL&gt;, and C&lt;US_GLOBAL&gt; constants above.

=item C&lt;header =E&lt;gt&gt; ''&gt;

A string to prepend to each message emitted through this channel.
With partial messages, only the first part will have C&lt;header&gt;
prepended.

=item C&lt;footer =E&lt;gt&gt; ''&gt;

A string to append to each message emitted through this channel.
With partial messages, only the final part will have C&lt;footer&gt;
appended.

=item C&lt;backtrace =E&lt;gt&gt; 0&gt;

Die with a stack backtrace after displaying the message.

=item C&lt;partial =E&lt;gt&gt; 0&gt;

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

Duplicate filtering will apply to the I&lt;global&gt; message resulting from
all I&lt;partial&gt; 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&lt;... A previously defined here&gt;" has been
filtered out.

Linking these messages using C&lt;partial&gt; as follows will prevent the
fourth message to disappear.

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

Note that because the stack of C&lt;partial&gt; messages is printed with the
first non-C&lt;partial&gt; message, most options of C&lt;partial&gt; messages will
be ignored.

=back

=cut

# Default options for a channel.
our %_default_options =
  (
   type =&gt; 'warning',
   exit_code =&gt; 1,
   file =&gt; \*STDERR,
   silent =&gt; 0,
   ordered =&gt; 1,
   queue =&gt; 0,
   queue_key =&gt; undef,
   uniq_scope =&gt; US_LOCAL,
   uniq_part =&gt; UP_LOC_TEXT,
   header =&gt; '',
   footer =&gt; '',
   backtrace =&gt; 0,
   partial =&gt; 0,
   );

# Filled with output messages as keys, to detect duplicates.
# The value associated with each key is the number of occurrences
# filtered out.
our %_local_duplicate_messages = ();
our %_global_duplicate_messages = ();

sub _reset_duplicates (\%)
{
  my ($ref) = @_;
  my $dup = 0;
  foreach my $k (keys %$ref)
    {
      $dup += $ref-&gt;{$k};
    }
  %$ref = ();
  return $dup;
}


=head2 Functions

=over 4

=item C&lt;reset_local_duplicates ()&gt;

Reset local duplicate messages (see C&lt;US_LOCAL&gt;), and
return the number of messages that have been filtered out.

=cut

sub reset_local_duplicates ()
{
  return _reset_duplicates %_local_duplicate_messages;
}

=item C&lt;reset_global_duplicates ()&gt;

Reset local duplicate messages (see C&lt;US_GLOBAL&gt;), and
return the number of messages that have been filtered out.

=cut

sub reset_global_duplicates ()
{
  return _reset_duplicates %_global_duplicate_messages;
}

sub _merge_options (\%%)
{
  my ($hash, %options) = @_;
  local $_;

  foreach (keys %options)
    {
      if (exists $hash-&gt;{$_})
	{
	  $hash-&gt;{$_} = $options{$_}
	}
      else
	{
	  confess "unknown option '$_'";
	}
    }
  if ($hash-&gt;{'ordered'})
    {
      confess "fatal messages cannot be ordered"
	if $hash-&gt;{'type'} eq 'fatal';
      confess "backtrace cannot be output on ordered messages"
	if $hash-&gt;{'backtrace'};
    }
}

=item C&lt;register_channel ($name, [%options])&gt;

Declare channel C&lt;$name&gt;, and override the default options
with those listed in C&lt;%options&gt;.

=cut

sub register_channel ($;%)
{
  my ($name, %options) = @_;
  my %channel_opts = %_default_options;
  _merge_options %channel_opts, %options;
  $channels{$name} = \%channel_opts;
}

=item C&lt;exists_channel ($name)&gt;

Returns true iff channel C&lt;$name&gt; has been registered.

=cut

sub exists_channel ($)
{
  my ($name) = @_;
  return exists $channels{$name};
}

=item C&lt;channel_type ($name)&gt;

Returns the type of channel C&lt;$name&gt; if it has been registered.
Returns the empty string otherwise.

=cut

sub channel_type ($)
{
  my ($name) = @_;
  return $channels{$name}{'type'} if exists_channel $name;
  return '';
}

# _format_sub_message ($LEADER, $MESSAGE)
# ---------------------------------------
# Split $MESSAGE at new lines and add $LEADER to each line.
sub _format_sub_message ($$)
{
  my ($leader, $message) = @_;
  return $leader . join ("\n" . $leader, split ("\n", $message)) . "\n";
}

# Store partial messages here. (See the 'partial' option.)
our $partial = '';

# _format_message ($LOCATION, $MESSAGE, %OPTIONS)
# -----------------------------------------------
# Format the message.  Return a string ready to print.
sub _format_message ($$%)
{
  my ($location, $message, %opts) = @_;
  my $msg = ($partial eq '' ? $opts{'header'} : '') . $message
	    . ($opts{'partial'} ? '' : $opts{'footer'});
  if (ref $location)
    {
      # If $LOCATION is a reference, assume it's an instance of the
      # Automake::Location class and display contexts.
      my $loc = $location-&gt;get || $me;
      $msg = _format_sub_message ("$loc: ", $msg);
      for my $pair ($location-&gt;get_contexts)
	{
	  $msg .= _format_sub_message ($pair-&gt;[0] . ":   ", $pair-&gt;[1]);
	}
    }
  else
    {
      $location ||= $me;
      $msg = _format_sub_message ("$location: ", $msg);
    }
  return $msg;
}

# _enqueue ($QUEUE, $KEY, $UNIQ_SCOPE, $TO_FILTER, $MSG, $FILE)
# -------------------------------------------------------------
# Push message on a queue, to be processed by another thread.
sub _enqueue ($$$$$$)
{
  my ($queue, $key, $uniq_scope, $to_filter, $msg, $file) = @_;
  $queue-&gt;enqueue ($key, $msg, $to_filter, $uniq_scope);
  confess "message queuing works only for STDERR"
    if $file ne \*STDERR;
}

# _dequeue ($QUEUE)
# -----------------
# Pop a message from a queue, and print, similarly to how
# _print_message would do it.  Return 0 if the queue is
# empty.  Note that the key has already been dequeued.
sub _dequeue ($)
{
  my ($queue) = @_;
  my $msg = $queue-&gt;dequeue || return 0;
  my $to_filter = $queue-&gt;dequeue;
  my $uniq_scope = $queue-&gt;dequeue;
  my $file = \*STDERR;

  if ($to_filter ne '')
    {
      # Do we want local or global uniqueness?
      my $dups;
      if ($uniq_scope == US_LOCAL)
	{
	  $dups = \%_local_duplicate_messages;
	}
      elsif ($uniq_scope == US_GLOBAL)
	{
	  $dups = \%_global_duplicate_messages;
	}
      else
	{
	  confess "unknown value for uniq_scope: " . $uniq_scope;
	}

      # Update the hash of messages.
      if (exists $dups-&gt;{$to_filter})
	{
	  ++$dups-&gt;{$to_filter};
	  return 1;
	}
      else
	{
	  $dups-&gt;{$to_filter} = 0;
	}
    }
  print $file $msg;
  return 1;
}


# _print_message ($LOCATION, $MESSAGE, %OPTIONS)
# ----------------------------------------------
# Format the message, check duplicates, and print it.
sub _print_message ($$%)
{
  my ($location, $message, %opts) = @_;

  return 0 if ($opts{'silent'});

  my $msg = _format_message ($location, $message, %opts);
  if ($opts{'partial'})
    {
      # Incomplete message.  Store, don't print.
      $partial .= $msg;
      return;
    }
  else
    {
      # Prefix with any partial message send so far.
      $msg = $partial . $msg;
      $partial = '';
    }

  msg ('note', '', 'warnings are treated as errors', uniq_scope =&gt; US_GLOBAL)
    if ($opts{'type'} eq 'warning' &amp;&amp; $warnings_are_errors);

  # Check for duplicate message if requested.
  my $to_filter;
  if ($opts{'uniq_part'} ne UP_NONE)
    {
      # Which part of the error should we match?
      if ($opts{'uniq_part'} eq UP_TEXT)
	{
	  $to_filter = $message;
	}
      elsif ($opts{'uniq_part'} eq UP_LOC_TEXT)
	{
	  $to_filter = $msg;
	}
      else
	{
	  $to_filter = $opts{'uniq_part'};
	}

      # Do we want local or global uniqueness?
      my $dups;
      if ($opts{'uniq_scope'} == US_LOCAL)
	{
	  $dups = \%_local_duplicate_messages;
	}
      elsif ($opts{'uniq_scope'} == US_GLOBAL)
	{
	  $dups = \%_global_duplicate_messages;
	}
      else
	{
	  confess "unknown value for uniq_scope: " . $opts{'uniq_scope'};
	}

      # Update the hash of messages.
      if (exists $dups-&gt;{$to_filter})
	{
	  ++$dups-&gt;{$to_filter};
	  return 0;
	}
      else
	{
	  $dups-&gt;{$to_filter} = 0;
	}
    }
  my $file = $opts{'file'};
  if ($opts{'ordered'} &amp;&amp; $opts{'queue'})
    {
      _enqueue ($opts{'queue'}, $opts{'queue_key'}, $opts{'uniq_scope'},
		$to_filter, $msg, $file);
    }
  else
    {
      print $file $msg;
    }
  return 1;
}

=item C&lt;msg ($channel, $location, $message, [%options])&gt;

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

C&lt;$message&gt; is the text of the message, and C&lt;$location&gt; is a location
associated to the message.

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

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

If channel C&lt;unused&gt; is not silent (and if this message is not a duplicate),
the following would be output:

  foo.c:10: unused variable 'mumble'

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

If C&lt;$message&gt; contains newline characters, C&lt;$location&gt; is prepended
to each line.  For instance,

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

becomes

  somewhere: 1st line
  somewhere: 2nd line

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

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

both print

  progname: fatal error

=cut


# See buffer_messages() and flush_messages() below.
our %buffering = ();	# The map of channel types to buffer.
our @backlog = ();		# The buffer of messages.

sub msg ($$;$%)
{
  my ($channel, $location, $message, %options) = @_;

  if (! defined $message)
    {
      $message = $location;
      $location = '';
    }

  confess "unknown channel $channel" unless exists $channels{$channel};

  my %opts = %{$channels{$channel}};
  _merge_options (%opts, %options);

  if (exists $buffering{$opts{'type'}})
    {
      push @backlog, [$channel, $location-&gt;clone, $message, %options];
      return;
    }

  # Print the message if needed.
  if (_print_message ($location, $message, %opts))
    {
      # Adjust exit status.
      if ($opts{'type'} eq 'error'
	  || $opts{'type'} eq 'fatal'
	  || ($opts{'type'} eq 'warning' &amp;&amp; $warnings_are_errors))
	{
	  my $es = $opts{'exit_code'};
	  $exit_code = $es if $es &gt; $exit_code;
	}

      # Die on fatal messages.
      confess if $opts{'backtrace'};
      if ($opts{'type'} eq 'fatal')
        {
	  # flush messages explicitly here, needed in worker threads.
	  STDERR-&gt;flush;
	  exit $exit_code;
	}
    }
}


=item C&lt;setup_channel ($channel, %options)&gt;

Override the options of C&lt;$channel&gt; with those specified by C&lt;%options&gt;.

=cut

sub setup_channel ($%)
{
  my ($name, %opts) = @_;
  confess "unknown channel $name" unless exists $channels{$name};
  _merge_options %{$channels{$name}}, %opts;
}

=item C&lt;setup_channel_type ($type, %options)&gt;

Override the options of any channel of type C&lt;$type&gt;
with those specified by C&lt;%options&gt;.

=cut

sub setup_channel_type ($%)
{
  my ($type, %opts) = @_;
  foreach my $channel (keys %channels)
    {
      setup_channel $channel, %opts
	if $channels{$channel}{'type'} eq $type;
    }
}

=item C&lt;dup_channel_setup ()&gt;, C&lt;drop_channel_setup ()&gt;

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&lt;dup_channel_setup ()&gt; saves a copy of the
current configuration for later restoration by
C&lt;drop_channel_setup ()&gt;.

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

=cut

our @_saved_channels = ();
our @_saved_werrors = ();

sub dup_channel_setup ()
{
  my %channels_copy;
  foreach my $k1 (keys %channels)
    {
      $channels_copy{$k1} = {%{$channels{$k1}}};
    }
  push @_saved_channels, \%channels_copy;
  push @_saved_werrors, $warnings_are_errors;
}

sub drop_channel_setup ()
{
  my $saved = pop @_saved_channels;
  %channels = %$saved;
  $warnings_are_errors = pop @_saved_werrors;
}

=item C&lt;buffer_messages (@types)&gt;, C&lt;flush_messages ()&gt;

By default, when C&lt;msg&gt; 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&lt;buffer_messages(@types)&gt; has been called, messages sent with
C&lt;msg&gt; to a channel whose type is listed in C&lt;@types&gt; will be stored in a
list for later processing.

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

C&lt;flush_messages&gt; cancels the effect of C&lt;buffer_messages&gt;.  Following
calls to C&lt;msg&gt; are processed immediately as usual.

=cut

sub buffer_messages (@)
{
  foreach my $type (@_)
    {
      $buffering{$type} = 1;
    }
}

sub flush_messages ()
{
  %buffering = ();
  foreach my $args (@backlog)
    {
      &amp;msg (@$args);
    }
  @backlog = ();
}

=item C&lt;setup_channel_queue ($queue, $key)&gt;

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

=cut
sub setup_channel_queue ($$)
{
  my ($queue, $key) = @_;
  foreach my $channel (keys %channels)
    {
      setup_channel $channel, queue =&gt; $queue, queue_key =&gt; $key
        if $channels{$channel}{'ordered'};
    }
}

=item C&lt;pop_channel_queue ($queue)&gt;

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

=cut
sub pop_channel_queue ($)
{
  my ($queue) = @_;
  return _dequeue ($queue);
}

=back

=head1 SEE ALSO

L&lt;Automake::Location&gt;

=head1 HISTORY

Written by Alexandre Duret-Lutz E&lt;lt&gt;F&lt;adl@gnu.org&gt;E&lt;gt&gt;.

=cut

1;
</pre></body></html>