<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package ExtUtils::Constant;
use vars qw (@ISA $VERSION @EXPORT_OK %EXPORT_TAGS);
$VERSION = '0.25';

=head1 NAME

ExtUtils::Constant - generate XS code to import C header constants

=head1 SYNOPSIS

    use ExtUtils::Constant qw (WriteConstants);
    WriteConstants(
        NAME =&gt; 'Foo',
        NAMES =&gt; [qw(FOO BAR BAZ)],
    );
    # Generates wrapper code to make the values of the constants FOO BAR BAZ
    #  available to perl

=head1 DESCRIPTION

ExtUtils::Constant facilitates generating C and XS wrapper code to allow
perl modules to AUTOLOAD constants defined in C library header files.
It is principally used by the C&lt;h2xs&gt; utility, on which this code is based.
It doesn't contain the routines to scan header files to extract these
constants.

=head1 USAGE

Generally one only needs to call the C&lt;WriteConstants&gt; function, and then

    #include "const-c.inc"

in the C section of C&lt;Foo.xs&gt;

    INCLUDE: const-xs.inc

in the XS section of C&lt;Foo.xs&gt;.

For greater flexibility use C&lt;constant_types()&gt;, C&lt;C_constant&gt; and
C&lt;XS_constant&gt;, with which C&lt;WriteConstants&gt; is implemented.

Currently this module understands the following types. h2xs may only know
a subset. The sizes of the numeric types are chosen by the C&lt;Configure&gt;
script at compile time.

=over 4

=item IV

signed integer, at least 32 bits.

=item UV

unsigned integer, the same size as I&lt;IV&gt;

=item NV

floating point type, probably C&lt;double&gt;, possibly C&lt;long double&gt;

=item PV

NUL terminated string, length will be determined with C&lt;strlen&gt;

=item PVN

A fixed length thing, given as a [pointer, length] pair. If you know the
length of a string at compile time you may use this instead of I&lt;PV&gt;

=item SV

A B&lt;mortal&gt; SV.

=item YES

Truth.  (C&lt;PL_sv_yes&gt;)  The value is not needed (and ignored).

=item NO

Defined Falsehood.  (C&lt;PL_sv_no&gt;)  The value is not needed (and ignored).

=item UNDEF

C&lt;undef&gt;.  The value of the macro is not needed.

=back

=head1 FUNCTIONS

=over 4

=cut

if ($] &gt;= 5.006) {
  eval "use warnings; 1" or die $@;
}
use strict;
use Carp qw(croak cluck);

use Exporter;
use ExtUtils::Constant::Utils qw(C_stringify);
use ExtUtils::Constant::XS qw(%XS_Constant %XS_TypeSet);

@ISA = 'Exporter';

%EXPORT_TAGS = ( 'all' =&gt; [ qw(
	XS_constant constant_types return_clause memEQ_clause C_stringify
	C_constant autoload WriteConstants WriteMakefileSnippet
) ] );

@EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

=item constant_types

A function returning a single scalar with C&lt;#define&gt; definitions for the
constants used internally between the generated C and XS functions.

=cut

sub constant_types {
  ExtUtils::Constant::XS-&gt;header();
}

sub memEQ_clause {
  cluck "ExtUtils::Constant::memEQ_clause is deprecated";
  ExtUtils::Constant::XS-&gt;memEQ_clause({name=&gt;$_[0], checked_at=&gt;$_[1],
					indent=&gt;$_[2]});
}

sub return_clause ($$) {
  cluck "ExtUtils::Constant::return_clause is deprecated";
  my $indent = shift;
  ExtUtils::Constant::XS-&gt;return_clause({indent=&gt;$indent}, @_);
}

sub switch_clause {
  cluck "ExtUtils::Constant::switch_clause is deprecated";
  my $indent = shift;
  my $comment = shift;
  ExtUtils::Constant::XS-&gt;switch_clause({indent=&gt;$indent, comment=&gt;$comment},
					@_);
}

sub C_constant {
  my ($package, $subname, $default_type, $what, $indent, $breakout, @items)
    = @_;
  ExtUtils::Constant::XS-&gt;C_constant({package =&gt; $package, subname =&gt; $subname,
				      default_type =&gt; $default_type,
				      types =&gt; $what, indent =&gt; $indent,
				      breakout =&gt; $breakout}, @items);
}

=item XS_constant PACKAGE, TYPES, XS_SUBNAME, C_SUBNAME

A function to generate the XS code to implement the perl subroutine
I&lt;PACKAGE&gt;::constant used by I&lt;PACKAGE&gt;::AUTOLOAD to load constants.
This XS code is a wrapper around a C subroutine usually generated by
C&lt;C_constant&gt;, and usually named C&lt;constant&gt;.

I&lt;TYPES&gt; should be given either as a comma separated list of types that the
C subroutine C&lt;constant&gt; will generate or as a reference to a hash. It should
be the same list of types as C&lt;C_constant&gt; was given.
[Otherwise C&lt;XS_constant&gt; and C&lt;C_constant&gt; may have different ideas about
the number of parameters passed to the C function C&lt;constant&gt;]

You can call the perl visible subroutine something other than C&lt;constant&gt; if
you give the parameter I&lt;XS_SUBNAME&gt;. The C subroutine it calls defaults to
the name of the perl visible subroutine, unless you give the parameter
I&lt;C_SUBNAME&gt;.

=cut

sub XS_constant {
  my $package = shift;
  my $what = shift;
  my $XS_subname = shift;
  my $C_subname = shift;
  $XS_subname ||= 'constant';
  $C_subname ||= $XS_subname;

  if (!ref $what) {
    # Convert line of the form IV,UV,NV to hash
    $what = {map {$_ =&gt; 1} split /,\s*/, ($what)};
  }
  my $params = ExtUtils::Constant::XS-&gt;params ($what);
  my $type;

  my $xs = &lt;&lt;"EOT";
void
$XS_subname(sv)
    PREINIT:
#ifdef dXSTARG
	dXSTARG; /* Faster if we have it.  */
#else
	dTARGET;
#endif
	STRLEN		len;
        int		type;
EOT

  if ($params-&gt;{IV}) {
    $xs .= "	IV		iv = 0; /* avoid uninit var warning */\n";
  } else {
    $xs .= "	/* IV\t\tiv;\tUncomment this if you need to return IVs */\n";
  }
  if ($params-&gt;{NV}) {
    $xs .= "	NV		nv = 0.0; /* avoid uninit var warning */\n";
  } else {
    $xs .= "	/* NV\t\tnv;\tUncomment this if you need to return NVs */\n";
  }
  if ($params-&gt;{PV}) {
    $xs .= "	const char	*pv = NULL; /* avoid uninit var warning */\n";
  } else {
    $xs .=
      "	/* const char\t*pv;\tUncomment this if you need to return PVs */\n";
  }

  $xs .= &lt;&lt; 'EOT';
    INPUT:
	SV *		sv;
        const char *	s = SvPV(sv, len);
EOT
  if ($params-&gt;{''}) {
  $xs .= &lt;&lt; 'EOT';
    INPUT:
	int		utf8 = SvUTF8(sv);
EOT
  }
  $xs .= &lt;&lt; 'EOT';
    PPCODE:
EOT

  if ($params-&gt;{IV} xor $params-&gt;{NV}) {
    $xs .= &lt;&lt; "EOT";
        /* Change this to $C_subname(aTHX_ s, len, &amp;iv, &amp;nv);
           if you need to return both NVs and IVs */
EOT
  }
  $xs .= "	type = $C_subname(aTHX_ s, len";
  $xs .= ', utf8' if $params-&gt;{''};
  $xs .= ', &amp;iv' if $params-&gt;{IV};
  $xs .= ', &amp;nv' if $params-&gt;{NV};
  $xs .= ', &amp;pv' if $params-&gt;{PV};
  $xs .= ', &amp;sv' if $params-&gt;{SV};
  $xs .= ");\n";

  # If anyone is insane enough to suggest a package name containing %
  my $package_sprintf_safe = $package;
  $package_sprintf_safe =~ s/%/%%/g;

  $xs .= &lt;&lt; "EOT";
      /* Return 1 or 2 items. First is error message, or undef if no error.
           Second, if present, is found value */
        switch (type) {
        case PERL_constant_NOTFOUND:
          sv =
	    sv_2mortal(newSVpvf("%s is not a valid $package_sprintf_safe macro", s));
          PUSHs(sv);
          break;
        case PERL_constant_NOTDEF:
          sv = sv_2mortal(newSVpvf(
	    "Your vendor has not defined $package_sprintf_safe macro %s, used",
				   s));
          PUSHs(sv);
          break;
EOT

  foreach $type (sort keys %XS_Constant) {
    # '' marks utf8 flag needed.
    next if $type eq '';
    $xs .= "\t/* Uncomment this if you need to return ${type}s\n"
      unless $what-&gt;{$type};
    $xs .= "        case PERL_constant_IS$type:\n";
    if (length $XS_Constant{$type}) {
      $xs .= &lt;&lt; "EOT";
          EXTEND(SP, 2);
          PUSHs(&amp;PL_sv_undef);
          $XS_Constant{$type};
EOT
    } else {
      # Do nothing. return (), which will be correctly interpreted as
      # (undef, undef)
    }
    $xs .= "          break;\n";
    unless ($what-&gt;{$type}) {
      chop $xs; # Yes, another need for chop not chomp.
      $xs .= " */\n";
    }
  }
  $xs .= &lt;&lt; "EOT";
        default:
          sv = sv_2mortal(newSVpvf(
	    "Unexpected return type %d while processing $package_sprintf_safe macro %s, used",
               type, s));
          PUSHs(sv);
        }
EOT

  return $xs;
}


=item autoload PACKAGE, VERSION, AUTOLOADER

A function to generate the AUTOLOAD subroutine for the module I&lt;PACKAGE&gt;
I&lt;VERSION&gt; is the perl version the code should be backwards compatible with.
It defaults to the version of perl running the subroutine.  If I&lt;AUTOLOADER&gt;
is true, the AUTOLOAD subroutine falls back on AutoLoader::AUTOLOAD for all
names that the constant() routine doesn't recognise.

=cut

# ' # Grr. syntax highlighters that don't grok pod.

sub autoload {
  my ($module, $compat_version, $autoloader) = @_;
  $compat_version ||= $];
  croak "Can't maintain compatibility back as far as version $compat_version"
    if $compat_version &lt; 5;
  my $func = "sub AUTOLOAD {\n"
  . "    # This AUTOLOAD is used to 'autoload' constants from the constant()\n"
  . "    # XS function.";
  $func .= "  If a constant is not found then control is passed\n"
  . "    # to the AUTOLOAD in AutoLoader." if $autoloader;


  $func .= "\n\n"
  . "    my \$constname;\n";
  $func .=
    "    our \$AUTOLOAD;\n"  if ($compat_version &gt;= 5.006);

  $func .= &lt;&lt;"EOT";
    (\$constname = \$AUTOLOAD) =~ s/.*:://;
    croak "&amp;${module}::constant not defined" if \$constname eq 'constant';
    my (\$error, \$val) = constant(\$constname);
EOT

  if ($autoloader) {
    $func .= &lt;&lt;'EOT';
    if ($error) {
	if ($error =~  /is not a valid/) {
	    $AutoLoader::AUTOLOAD = $AUTOLOAD;
	    goto &amp;AutoLoader::AUTOLOAD;
	} else {
	    croak $error;
	}
    }
EOT
  } else {
    $func .=
      "    if (\$error) { croak \$error; }\n";
  }

  $func .= &lt;&lt;'END';
    {
	no strict 'refs';
	# Fixed between 5.005_53 and 5.005_61
#XXX	if ($] &gt;= 5.00561) {
#XXX	    *$AUTOLOAD = sub () { $val };
#XXX	}
#XXX	else {
	    *$AUTOLOAD = sub { $val };
#XXX	}
    }
    goto &amp;$AUTOLOAD;
}

END

  return $func;
}


=item WriteMakefileSnippet

WriteMakefileSnippet ATTRIBUTE =E&lt;gt&gt; VALUE [, ...] 

A function to generate perl code for Makefile.PL that will regenerate
the constant subroutines.  Parameters are named as passed to C&lt;WriteConstants&gt;,
with the addition of C&lt;INDENT&gt; to specify the number of leading spaces
(default 2).

Currently only C&lt;INDENT&gt;, C&lt;NAME&gt;, C&lt;DEFAULT_TYPE&gt;, C&lt;NAMES&gt;, C&lt;C_FILE&gt; and
C&lt;XS_FILE&gt; are recognised.

=cut

sub WriteMakefileSnippet {
  my %args = @_;
  my $indent = $args{INDENT} || 2;

  my $result = &lt;&lt;"EOT";
ExtUtils::Constant::WriteConstants(
                                   NAME         =&gt; '$args{NAME}',
                                   NAMES        =&gt; \\\@names,
                                   DEFAULT_TYPE =&gt; '$args{DEFAULT_TYPE}',
EOT
  foreach (qw (C_FILE XS_FILE)) {
    next unless exists $args{$_};
    $result .= sprintf "                                   %-12s =&gt; '%s',\n",
      $_, $args{$_};
  }
  $result .= &lt;&lt;'EOT';
                                );
EOT

  $result =~ s/^/' 'x$indent/gem;
  return ExtUtils::Constant::XS-&gt;dump_names({default_type=&gt;$args{DEFAULT_TYPE},
					     indent=&gt;$indent,},
					    @{$args{NAMES}})
    . $result;
}

=item WriteConstants ATTRIBUTE =E&lt;gt&gt; VALUE [, ...]

Writes a file of C code and a file of XS code which you should C&lt;#include&gt;
and C&lt;INCLUDE&gt; in the C and XS sections respectively of your module's XS
code.  You probably want to do this in your C&lt;Makefile.PL&gt;, so that you can
easily edit the list of constants without touching the rest of your module.
The attributes supported are

=over 4

=item NAME

Name of the module.  This must be specified

=item DEFAULT_TYPE

The default type for the constants.  If not specified C&lt;IV&gt; is assumed.

=item BREAKOUT_AT

The names of the constants are grouped by length.  Generate child subroutines
for each group with this number or more names in.

=item NAMES

An array of constants' names, either scalars containing names, or hashrefs
as detailed in L&lt;"C_constant"&gt;.

=item PROXYSUBS

If true, uses proxy subs. See L&lt;ExtUtils::Constant::ProxySubs&gt;.

=item C_FH

A filehandle to write the C code to.  If not given, then I&lt;C_FILE&gt; is opened
for writing.

=item C_FILE

The name of the file to write containing the C code.  The default is
C&lt;const-c.inc&gt;.  The C&lt;-&gt; in the name ensures that the file can't be
mistaken for anything related to a legitimate perl package name, and
not naming the file C&lt;.c&gt; avoids having to override Makefile.PL's
C&lt;.xs&gt; to C&lt;.c&gt; rules.

=item XS_FH

A filehandle to write the XS code to.  If not given, then I&lt;XS_FILE&gt; is opened
for writing.

=item XS_FILE

The name of the file to write containing the XS code.  The default is
C&lt;const-xs.inc&gt;.

=item XS_SUBNAME

The perl visible name of the XS subroutine generated which will return the
constants. The default is C&lt;constant&gt;.

=item C_SUBNAME

The name of the C subroutine generated which will return the constants.
The default is I&lt;XS_SUBNAME&gt;.  Child subroutines have C&lt;_&gt; and the name
length appended, so constants with 10 character names would be in
C&lt;constant_10&gt; with the default I&lt;XS_SUBNAME&gt;.

=back

=cut

sub WriteConstants {
  my %ARGS =
    ( # defaults
     C_FILE =&gt;       'const-c.inc',
     XS_FILE =&gt;      'const-xs.inc',
     XS_SUBNAME =&gt;   'constant',
     DEFAULT_TYPE =&gt; 'IV',
     @_);

  $ARGS{C_SUBNAME} ||= $ARGS{XS_SUBNAME}; # No-one sane will have C_SUBNAME eq '0'

  croak "Module name not specified" unless length $ARGS{NAME};

  # Do this before creating (empty) files, in case it fails:
  require ExtUtils::Constant::ProxySubs if $ARGS{PROXYSUBS};

  my $c_fh = $ARGS{C_FH};
  if (!$c_fh) {
      if ($] &lt;= 5.008) {
	  # We need these little games, rather than doing things
	  # unconditionally, because we're used in core Makefile.PLs before
	  # IO is available (needed by filehandle), but also we want to work on
	  # older perls where undefined scalars do not automatically turn into
	  # anonymous file handles.
	  require FileHandle;
	  $c_fh = FileHandle-&gt;new();
      }
      open $c_fh, "&gt;$ARGS{C_FILE}" or die "Can't open $ARGS{C_FILE}: $!";
  }

  my $xs_fh = $ARGS{XS_FH};
  if (!$xs_fh) {
      if ($] &lt;= 5.008) {
	  require FileHandle;
	  $xs_fh = FileHandle-&gt;new();
      }
      open $xs_fh, "&gt;$ARGS{XS_FILE}" or die "Can't open $ARGS{XS_FILE}: $!";
  }

  # As this subroutine is intended to make code that isn't edited, there's no
  # need for the user to specify any types that aren't found in the list of
  # names.
  
  if ($ARGS{PROXYSUBS}) {
      $ARGS{C_FH} = $c_fh;
      $ARGS{XS_FH} = $xs_fh;
      ExtUtils::Constant::ProxySubs-&gt;WriteConstants(%ARGS);
  } else {
      my $types = {};

      print $c_fh constant_types(); # macro defs
      print $c_fh "\n";

      # indent is still undef. Until anyone implements indent style rules with
      # it.
      foreach (ExtUtils::Constant::XS-&gt;C_constant({package =&gt; $ARGS{NAME},
						   subname =&gt; $ARGS{C_SUBNAME},
						   default_type =&gt;
						       $ARGS{DEFAULT_TYPE},
						       types =&gt; $types,
						       breakout =&gt;
						       $ARGS{BREAKOUT_AT}},
						  @{$ARGS{NAMES}})) {
	  print $c_fh $_, "\n"; # C constant subs
      }
      print $xs_fh XS_constant ($ARGS{NAME}, $types, $ARGS{XS_SUBNAME},
				$ARGS{C_SUBNAME});
  }

  close $c_fh or warn "Error closing $ARGS{C_FILE}: $!" unless $ARGS{C_FH};
  close $xs_fh or warn "Error closing $ARGS{XS_FILE}: $!" unless $ARGS{XS_FH};
}

1;
__END__

=back

=head1 AUTHOR

Nicholas Clark &lt;nick@ccl4.org&gt; based on the code in C&lt;h2xs&gt; by Larry Wall and
others

=cut
</pre></body></html>