Re: Change 34005: Re: CPAN Upload: S/SA/SAPER/Sys-Syslog-0.25.tar.gz
[p5sagit/p5-mst-13.2.git] / lib / ExtUtils / Constant.pm
index aeaaf9f..91e9b1d 100644 (file)
@@ -1,4 +1,6 @@
 package ExtUtils::Constant;
+use vars qw (@ISA $VERSION @EXPORT_OK %EXPORT_TAGS);
+$VERSION = 0.21;
 
 =head1 NAME
 
@@ -6,14 +8,13 @@ ExtUtils::Constant - generate XS code to import C header constants
 
 =head1 SYNOPSIS
 
-    use ExtUtils::Constant qw (constant_types C_constant XS_constant);
-    print constant_types(); # macro defs
-    foreach (C_constant ("Foo", undef, "IV", undef, undef, undef,
-                         @names) ) {
-       print $_, "\n"; # C constant subs
-    }
-    print "MODULE = Foo                PACKAGE = Foo\n";
-    print XS_constant ("Foo", {NV => 1, IV => 1}); # XS for Foo::constant
+    use ExtUtils::Constant qw (WriteConstants);
+    WriteConstants(
+        NAME => 'Foo',
+        NAMES => [qw(FOO BAR BAZ)],
+    );
+    # Generates wrapper code to make the values of the constants FOO BAR BAZ
+    #  available to perl
 
 =head1 DESCRIPTION
 
@@ -25,8 +26,18 @@ constants.
 
 =head1 USAGE
 
-Generally one only needs to call the 3 functions shown in the synopsis,
-C<constant_types()>, C<C_constant> and C<XS_constant>.
+Generally one only needs to call the C<WriteConstants> function, and then
+
+    #include "const-c.inc"
+
+in the C section of C<Foo.xs>
+
+    INCLUDE: const-xs.inc
+
+in the XS section of C<Foo.xs>.
+
+For greater flexibility use C<constant_types()>, C<C_constant> and
+C<XS_constant>, with which C<WriteConstants> 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<Configure>
@@ -55,6 +66,10 @@ NUL terminated string, length will be determined with C<strlen>
 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<PV>
 
+=item SV
+
+A B<mortal> SV.
+
 =item YES
 
 Truth.  (C<PL_sv_yes>)  The value is not needed (and ignored).
@@ -75,73 +90,25 @@ C<undef>.  The value of the macro is not needed.
 
 =cut
 
-require 5.006; # I think, for [:cntrl:] in REGEXP
-use warnings;
+if ($] >= 5.006) {
+  eval "use warnings; 1" or die $@;
+}
 use strict;
-use Carp;
+use Carp qw(croak cluck);
 
 use Exporter;
-use vars qw (@ISA $VERSION %XS_Constant %XS_TypeSet @EXPORT_OK %EXPORT_TAGS);
-use Text::Wrap;
-$Text::Wrap::huge = 'overflow';
-$Text::Wrap::columns = 80;
+use ExtUtils::Constant::Utils qw(C_stringify);
+use ExtUtils::Constant::XS qw(%XS_Constant %XS_TypeSet);
 
 @ISA = 'Exporter';
-$VERSION = '0.04';
 
 %EXPORT_TAGS = ( 'all' => [ qw(
        XS_constant constant_types return_clause memEQ_clause C_stringify
-       C_constant autoload
+       C_constant autoload WriteConstants WriteMakefileSnippet
 ) ] );
 
 @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
 
-%XS_Constant = (
-                IV => 'PUSHi(iv)',
-                UV => 'PUSHu((UV)iv)',
-                NV => 'PUSHn(nv)',
-                PV => 'PUSHp(pv, strlen(pv))',
-                PVN => 'PUSHp(pv, iv)',
-               YES => 'PUSHs(&PL_sv_yes)',
-               NO => 'PUSHs(&PL_sv_no)',
-               UNDEF => '',    # implicit undef
-);
-
-%XS_TypeSet = (
-                IV => '*iv_return =',
-                UV => '*iv_return = (IV)',
-                NV => '*nv_return =',
-                PV => '*pv_return =',
-                PVN => ['*pv_return =', '*iv_return = (IV)'],
-               YES   => undef,
-               NO    => undef,
-               UNDEF => undef,
-);
-
-
-=item C_stringify NAME
-
-A function which returns a correctly \ escaped version of the string passed
-suitable for C's "" or ''.  It will also be valid as a perl "" string.
-
-=cut
-
-# Hopefully make a happy C identifier.
-sub C_stringify {
-  local $_ = shift;
-  return unless defined $_;
-  s/\\/\\\\/g;
-  s/([\"\'])/\\$1/g;   # Grr. fix perl mode.
-  s/\n/\\n/g;          # Ensure newlines don't end up in octal
-  s/\r/\\r/g;
-  s/\t/\\t/g;
-  s/\f/\\f/g;
-  s/\a/\\a/g;
-  s/([[:cntrl:]])/sprintf "\\%03o", ord $1/ge;
-  s/\177/\\177/g;      # DEL doesn't seem to be a [:cntrl:]
-  $_;
-}
-
 =item constant_types
 
 A function returning a single scalar with C<#define> definitions for the
@@ -149,516 +116,37 @@ constants used internally between the generated C and XS functions.
 
 =cut
 
-sub constant_types () {
-  my $start = 1;
-  my @lines;
-  push @lines, "#define PERL_constant_NOTFOUND\t$start\n"; $start++;
-  push @lines, "#define PERL_constant_NOTDEF\t$start\n"; $start++;
-  foreach (sort keys %XS_Constant) {
-    push @lines, "#define PERL_constant_IS$_\t$start\n"; $start++;
-  }
-  push @lines, << 'EOT';
-
-#ifndef NVTYPE
-typedef double NV; /* 5.6 and later define NVTYPE, and typedef NV to it.  */
-#endif
-EOT
-
-  return join '', @lines;
+sub constant_types {
+  ExtUtils::Constant::XS->header();
 }
 
-=item memEQ_clause NAME, CHECKED_AT, INDENT
-
-A function to return a suitable C C<if> statement to check whether I<NAME>
-is equal to the C variable C<name>. If I<CHECKED_AT> is defined, then it
-is used to avoid C<memEQ> for short names, or to generate a comment to
-highlight the position of the character in the C<switch> statement.
-
-=cut
-
 sub memEQ_clause {
-#    if (memEQ(name, "thingy", 6)) {
-  # Which could actually be a character comparison or even ""
-  my ($name, $checked_at, $indent) = @_;
-  $indent = ' ' x ($indent || 4);
-  my $len = length $name;
-
-  if ($len < 2) {
-    return $indent . "{\n" if (defined $checked_at and $checked_at == 0);
-    # We didn't switch, drop through to the code for the 2 character string
-    $checked_at = 1;
-  }
-  if ($len < 3 and defined $checked_at) {
-    my $check;
-    if ($checked_at == 1) {
-      $check = 0;
-    } elsif ($checked_at == 0) {
-      $check = 1;
-    }
-    if (defined $check) {
-      my $char = C_stringify (substr $name, $check, 1);
-      return $indent . "if (name[$check] == '$char') {\n";
-    }
-  }
-  # Could optimise a memEQ on 3 to 2 single character checks here
-  $name = C_stringify ($name);
-  my $body = $indent . "if (memEQ(name, \"$name\", $len)) {\n";
-    $body .= $indent . "/*               ". (' ' x $checked_at) . '^'
-      . (' ' x ($len - $checked_at + length $len)) . "    */\n"
-        if defined $checked_at;
-  return $body;
+  cluck "ExtUtils::Constant::memEQ_clause is deprecated";
+  ExtUtils::Constant::XS->memEQ_clause({name=>$_[0], checked_at=>$_[1],
+                                       indent=>$_[2]});
 }
 
-=item assign INDENT, TYPE, VALUE...
-
-A function to return a suitable assignment clause. If I<TYPE> is aggregate
-(eg I<PVN> expects both pointer and length) then there should be multiple
-I<VALUE>s for the components.
-
-=cut
-
-# Hmm. value undef to to NOTDEF? value () to do NOTFOUND?
-
-sub assign {
+sub return_clause ($$) {
+  cluck "ExtUtils::Constant::return_clause is deprecated";
   my $indent = shift;
-  my $type = shift;
-  my $clause;
-  die "Can't generate code for type $type" unless exists $XS_TypeSet{$type};
-  my $typeset = $XS_TypeSet{$type};
-  if (ref $typeset) {
-    die "Type $type is aggregate, but only single value given"
-      if @_ == 1;
-    foreach (0 .. $#$typeset) {
-      $clause .= $indent . "$typeset->[$_] $_[$_];\n";
-    }
-  } elsif (defined $typeset) {
-    die "Aggregate value given for type $type"
-      if @_ > 1;
-    $clause .= $indent . "$typeset $_[0];\n";
-  }
-  $clause .= "${indent}return PERL_constant_IS$type;\n";
-  return $clause;
+  ExtUtils::Constant::XS->return_clause({indent=>$indent}, @_);
 }
 
-=item return_clause VALUE, TYPE, INDENT, MACRO, DEFAULT
-
-A function to return a suitable C<#ifdef> clause. I<MACRO> defaults to
-I<VALUE> when not defined.  If I<TYPE> is aggregate (eg I<PVN> expects both
-pointer and length) then I<VALUE> should be a reference to an array of
-values in the order expected by the type.  C<C_constant> will always call
-this function with I<MACRO> defined, defaulting to the constant's name.
-I<DEFAULT> if defined is an array reference giving default type and and
-value(s) if the clause generated by I<MACRO> doesn't evaluate to true.
-
-=cut
-
-sub return_clause ($$$$$) {
-##ifdef thingy
-#      *iv_return = thingy;
-#      return PERL_constant_ISIV;
-##else
-#      return PERL_constant_NOTDEF;
-##endif
-  my ($value, $type, $indent, $macro, $default) = @_;
-  $macro = $value unless defined $macro;
-  $indent = ' ' x ($indent || 6);
-
-  my $clause;
-
-  ##ifdef thingy
-  if (ref $macro) {
-    $clause = $macro->[0];
-  } else {
-    $clause = "#ifdef $macro\n";
-  }
-
-  #      *iv_return = thingy;
-  #      return PERL_constant_ISIV;
-  $clause .= assign ($indent, $type, ref $value ? @$value : $value);
-
-  ##else
-  $clause .= "#else\n";
-  
-  #      return PERL_constant_NOTDEF;
-  if (!defined $default) {
-    $clause .= "${indent}return PERL_constant_NOTDEF;\n";
-  } else {
-    $clause .= assign ($indent, ref $default ? @$default : $default);
-  }
-
-  ##endif
-  if (ref $macro) {
-    $clause .= $macro->[1];
-  } else {
-    $clause .= "#endif\n";
-  }
-  return $clause
-}
-
-=item params WHAT
-
-An internal function. I<WHAT> should be a hashref of types the constant
-function will return. I<params> returns the list of flags C<$use_iv, $use_nv,
-$use_pv> to show which combination of pointers will be needed in the C
-argument list.
-
-=cut
-
-sub params {
-  my $what = shift;
-  foreach (sort keys %$what) {
-    warn "ExtUtils::Constant doesn't know how to handle values of type $_" unless defined $XS_Constant{$_};
-  }
-  my $use_iv = $what->{IV} || $what->{UV} || $what->{PVN};
-  my $use_nv = $what->{NV};
-  my $use_pv = $what->{PV} || $what->{PVN};
-  return ($use_iv, $use_nv, $use_pv);
-}
-
-=item dump_names  
-
-dump_names  PACKAGE, SUBNAME, DEFAULT_TYPE, TYPES, INDENT, ITEM...
-
-An internal function to generate the embedded perl code that will regenerate
-the constant subroutines.  Parameters are the same as for C_constant, except
-that there is no NAMELEN.
-
-=cut
-
-sub dump_names {
-  my ($package, $subname, $default_type, $what, $indent, @items) = @_;
-  my (@simple, @complex);
-  foreach (@items) {
-    my $type = $_->{type} || $default_type;
-    if ($type eq $default_type and 0 == ($_->{name} =~ tr/A-Za-z0-9_//c)
-        and !defined ($_->{macro}) and !defined ($_->{value})
-        and !defined ($_->{default})) {
-      # It's the default type, and the name consists only of A-Za-z0-9_
-      push @simple, $_->{name};
-    } else {
-      push @complex, $_;
-    }
-  }
-  my $result = <<"EOT";
-  /* When generated this function returned values for the list of names given
-     in this section of perl code.  Rather than manually editing these functions
-     to add or remove constants, which would result in this comment and section
-     of code becoming inaccurate, we recommend that you edit this section of
-     code, and use it to regenerate a new set of constant functions which you
-     then use to replace the originals.
-
-     Regenerate these constant functions by feeding this entire source file to
-     perl -x
-
-#!$^X -w
-use ExtUtils::Constant qw (constant_types C_constant XS_constant);
-
-EOT
-  $result .= 'my $types = {' . join (", ", map "$_ => 1", sort keys %$what)
- . "};\n";
-  $result .= wrap ("my \@names = (qw(",
-                  "               ", join (" ", sort @simple) . ")");
-  if (@complex) {
-    foreach my $item (sort {$a->{name} cmp $b->{name}} @complex) {
-      my $name = C_stringify $item->{name};
-      my ($macro, $value, $default) = @$item{qw (macro value default)};
-      my $line = ",\n            {name=>\"$name\"";
-      $line .= ", type=>\"$item->{type}\"" if defined $item->{type};
-      if (defined $macro) {
-        if (ref $macro) {
-          $line .= ', macro=>["'. join ('", "', map {C_stringify $_} @$macro)
-            . '"]';
-        } else {
-          $line .= ", macro=>\"" . C_stringify($macro) . "\"";
-        }
-      }
-      if (defined $value) {
-        if (ref $value) {
-          $line .= ', value=>["'. join ('", "', map {C_stringify $_} @$value)
-            . '"]';
-        } else {
-          $line .= ", value=>\"" . C_stringify($value) . "\"";
-        }
-      }
-      if (defined $default) {
-        if (ref $default) {
-          $line .= ', default=>["'. join ('", "', map {C_stringify $_}
-                                          @$default)
-            . '"]';
-        } else {
-          $line .= ", default=>\"" . C_stringify($default) . "\"";
-        }
-      }
-      $line .= "}";
-      # Ensure that the enclosing C comment doesn't end
-      # by turning */  into *" . "/
-      $line =~ s!\*\/!\*" . "/!gs;
-      # gcc -Wall doesn't like finding /* inside a comment
-      $line =~ s!\/\*!/" . "\*!gs;
-      $result .= $line;
-    }
-  }
-  $result .= ");\n";
-
-  $result .= <<'EOT';
-
-print constant_types(); # macro defs
-EOT
-  $package = C_stringify($package);
-  $result .=
-    "foreach (C_constant (\"$package\", '$subname', '$default_type', \$types, ";
-  # The form of the indent parameter isn't defined. (Yet)
-  if (defined $indent) {
-    require Data::Dumper;
-    $Data::Dumper::Terse=1;
-    chomp ($indent = Data::Dumper::Dumper ($indent));
-    $result .= $indent;
-  } else {
-    $result .= 'undef';
-  }
-  $result .= ', undef, @names) ) {
-    print $_, "\n"; # C constant subs
-}
-print "#### XS Section:\n";
-print XS_constant ("' . $package . '", $types);
-__END__
-   */
-
-';
-  
-  $result;
+sub switch_clause {
+  cluck "ExtUtils::Constant::switch_clause is deprecated";
+  my $indent = shift;
+  my $comment = shift;
+  ExtUtils::Constant::XS->switch_clause({indent=>$indent, comment=>$comment},
+                                       @_);
 }
 
-=item C_constant 
-
-C_constant PACKAGE, SUBNAME, DEFAULT_TYPE, TYPES, INDENT, NAMELEN, ITEM...
-
-A function that returns a B<list> of C subroutine definitions that return
-the value and type of constants when passed the name by the XS wrapper.
-I<ITEM...> gives a list of constant names. Each can either be a string,
-which is taken as a C macro name, or a reference to a hash with the following
-keys
-
-=over 8
-
-=item name
-
-The name of the constant, as seen by the perl code.
-
-=item type
-
-The type of the constant (I<IV>, I<NV> etc)
-
-=item value
-
-A C expression for the value of the constant, or a list of C expressions if
-the type is aggregate. This defaults to the I<name> if not given.
-
-=item macro
-
-The C pre-processor macro to use in the C<#ifdef>. This defaults to the
-I<name>, and is mainly used if I<value> is an C<enum>. If a reference an
-array is passed then the first element is used in place of the C<#ifdef>
-line, and the second element in place of the C<#endif>. This allows
-pre-processor constructions such as
-
-    #if defined (foo)
-    #if !defined (bar)
-    ...
-    #endif
-    #endif
-
-to be used to determine if a constant is to be defined.
-
-=item default
-
-Default value to use (instead of C<croak>ing with "your vendor has not
-defined...") to return if the macro isn't defined. Specify a reference to
-an array with type followed by value(s).
-
-=back
-
-I<PACKAGE> is the name of the package, and is only used in comments inside the
-generated C code.
-
-The next 5 arguments can safely be given as C<undef>, and are mainly used
-for recursion. I<SUBNAME> defaults to C<constant> if undefined.
-
-I<DEFAULT_TYPE> is the type returned by C<ITEM>s that don't specify their
-type. In turn it defaults to I<IV>. I<TYPES> should be given either as a comma
-separated list of types that the C subroutine C<constant> will generate or as
-a reference to a hash. I<DEFAULT_TYPE> will be added to the list if not
-present, as will any types given in the list of I<ITEM>s. The resultant list
-should be the same list of types that C<XS_constant> is given. [Otherwise
-C<XS_constant> and C<C_constant> may differ in the number of parameters to the
-constant function. I<INDENT> is currently unused and ignored. In future it may
-be used to pass in information used to change the C indentation style used.]
-The best way to maintain consistency is to pass in a hash reference and let
-this function update it.
-
-I<NAMELEN> if defined signals that all the I<name>s of the I<ITEM>s are of
-this length, and that the constant name passed in by perl is checked and
-also of this length. It is used during recursion, and should be C<undef>
-unless the caller has checked all the lengths during code generation, and
-the generated subroutine is only to be called with a name of this length.
-
-=cut
-
 sub C_constant {
-  my ($package, $subname, $default_type, $what, $indent, $namelen, @items) = @_;
-  $package ||= 'Foo';
-  $subname ||= 'constant';
-  # I'm not using this. But a hashref could be used for full formatting without
-  # breaking this API
-  # $indent ||= 0;
-   $default_type ||= 'IV';
-  if (!ref $what) {
-    # Convert line of the form IV,UV,NV to hash
-    $what = {map {$_ => 1} split /,\s*/, ($what || '')};
-    # Figure out what types we're dealing with, and assign all unknowns to the
-    # default type
-  }
-  my %items;
-  foreach (@items) {
-    my $name;
-    if (ref $_) {
-      # Make a copy which is a normalised version of the ref passed in.
-      $name = $_->{name};
-      my ($type, $macro, $value, $default) = @$_{qw (type macro value default)};
-      $type ||= $default_type;
-      $what->{$type} = 1;
-      $_ = {name=>$name, type=>$type};
-
-      undef $macro if defined $macro and $macro eq $name;
-      $_->{macro} = $macro if defined $macro;
-      undef $value if defined $value and $value eq $name;
-      $_->{value} = $value if defined $value;
-      $_->{default} = $default if defined $default;
-    } else {
-      $name = $_;
-      $_ = {name=>$_, type=>$default_type};
-      $what->{$default_type} = 1;
-    }
-    warn "ExtUtils::Constant doesn't know how to handle values of type $_ used in macro $name" unless defined $XS_Constant{$_->{type}};
-    if (exists $items{$name}) {
-      die "Multiple definitions for macro $name";
-    }
-    $items{$name} = $_;
-  }
-  my ($use_iv, $use_nv, $use_pv) = params ($what);
-
-  my ($body, @subs) = "static int\n$subname (const char *name";
-  $body .= ", STRLEN len" unless defined $namelen;
-  $body .= ", IV *iv_return" if $use_iv;
-  $body .= ", NV *nv_return" if $use_nv;
-  $body .= ", const char **pv_return" if $use_pv;
-  $body .= ") {\n";
-
-  if (defined $namelen) {
-    # We are a child subroutine. Print the simple description
-    my @names = sort map {$_->{name}} @items;
-    my $names = << 'EOT'
-  /* When generated this function returned values for the list of names given
-     here.  However, subsequent manual editing may have added or removed some.
-EOT
-     . wrap ("     ", "     ", join (" ", @names) . " */") . "\n";
-    # Figure out what to switch on.
-    # (RMS, Spread of jump table, Position, Hashref)
-    my @best = (1e38, ~0);
-    foreach my $i (0 .. ($namelen - 1)) {
-      my ($min, $max) = (~0, 0);
-      my %spread;
-      foreach (@names) {
-        my $char = substr $_, $i, 1;
-        my $ord = ord $char;
-        $max = $ord if $ord > $max; 
-        $min = $ord if $ord < $min;
-        push @{$spread{$char}}, $_;
-        # warn "$_ $char";
-      }
-      # I'm going to pick the character to split on that minimises the root
-      # mean square of the number of names in each case. Normally this should
-      # be the one with the most keys, but it may pick a 7 where the 8 has
-      # one long linear search. I'm not sure if RMS or just sum of squares is
-      # actually better.
-      # $max and $min are for the tie-breaker if the root mean squares match.
-      # Assuming that the compiler may be building a jump table for the
-      # switch() then try to minimise the size of that jump table.
-      # Finally use < not <= so that if it still ties the earliest part of
-      # the string wins. Because if that passes but the memEQ fails, it may
-      # only need the start of the string to bin the choice.
-      # I think. But I'm micro-optimising. :-)
-      my $ss;
-      $ss += @$_ * @$_ foreach values %spread;
-      my $rms = sqrt ($ss / keys %spread);
-      if ($rms < $best[0] || ($rms == $best[0] && ($max - $min) < $best[1])) {
-        @best = ($rms, $max - $min, $i, \%spread);
-      }
-    }
-    die "Internal error. Failed to pick a switch point for @names"
-      unless defined $best[2];
-    # use Data::Dumper; print Dumper (@best);
-    my ($offset, $best) = @best[2,3];
-    $body .= "  /* Names all of length $namelen.  */\n";
-    $body .= $names;
-    $body .= "  /* Offset $offset gives the best switch position.  */\n";
-    $body .= "  switch (name[$offset]) {\n";
-    foreach my $char (sort keys %$best) {
-      $body .= "  case '" . C_stringify ($char) . "':\n";
-      foreach my $name (sort @{$best->{$char}}) {
-        my $thisone = $items{$name};
-        my ($value, $macro, $default) = @$thisone{qw (value macro default)};
-        $value = $name unless defined $value;
-        $macro = $name unless defined $macro;
-
-        $body .= memEQ_clause ($name, $offset); # We have checked this offset.
-        $body .= return_clause ($value, $thisone->{type}, undef, $macro,
-                                $default);
-        $body .= "    }\n";
-      }
-      $body .= "    break;\n";
-    }
-    $body .= "  }\n";
-  } else {
-    # We are the top level.
-    $body .= "  /* Initially switch on the length of the name.  */\n";
-    $body .= dump_names ($package, $subname, $default_type, $what, $indent,
-                         @items);
-    $body .= "  switch (len) {\n";
-    # Need to group names of the same length
-    my @by_length;
-    foreach (@items) {
-      push @{$by_length[length $_->{name}]}, $_;
-    }
-    foreach my $i (0 .. $#by_length) {
-      next unless $by_length[$i];      # None of this length
-      $body .= "  case $i:\n";
-      if (@{$by_length[$i]} == 1) {
-        my $thisone = $by_length[$i]->[0];
-        my ($name, $value, $macro, $default)
-          = @$thisone{qw (name value macro default)};
-        $value = $name unless defined $value;
-        $macro = $name unless defined $macro;
-
-        $body .= memEQ_clause ($name);
-        $body .= return_clause ($value, $thisone->{type}, undef, $macro,
-                                $default);
-        $body .= "    }\n";
-      } else {
-        push @subs, C_constant ($package, "${subname}_$i", $default_type,
-                                $what, $indent, $i, @{$by_length[$i]});
-        $body .= "    return ${subname}_$i (name";
-        $body .= ", iv_return" if $use_iv;
-        $body .= ", nv_return" if $use_nv;
-        $body .= ", pv_return" if $use_pv;
-        $body .= ");\n";
-      }
-      $body .= "    break;\n";
-    }
-    $body .= "  }\n";
-  }
-  $body .= "  return PERL_constant_NOTFOUND;\n}\n";
-  return (@subs, $body);
+  my ($package, $subname, $default_type, $what, $indent, $breakout, @items)
+    = @_;
+  ExtUtils::Constant::XS->C_constant({package => $package, subname => $subname,
+                                     default_type => $default_type,
+                                     types => $what, indent => $indent,
+                                     breakout => $breakout}, @items);
 }
 
 =item XS_constant PACKAGE, TYPES, SUBNAME, C_SUBNAME
@@ -675,7 +163,7 @@ be the same list of types as C<C_constant> was given.
 the number of parameters passed to the C function C<constant>]
 
 You can call the perl visible subroutine something other than C<constant> if
-you give the parameter I<SUBNAME>. The C subroutine it calls defaults to the
+you give the parameter I<SUBNAME>. The C subroutine it calls defaults to
 the name of the perl visible subroutine, unless you give the parameter
 I<C_SUBNAME>.
 
@@ -693,7 +181,7 @@ sub XS_constant {
     # Convert line of the form IV,UV,NV to hash
     $what = {map {$_ => 1} split /,\s*/, ($what)};
   }
-  my ($use_iv, $use_nv, $use_pv) = params ($what);
+  my $params = ExtUtils::Constant::XS->params ($what);
   my $type;
 
   my $xs = <<"EOT";
@@ -709,17 +197,17 @@ $subname(sv)
         int            type;
 EOT
 
-  if ($use_iv) {
+  if ($params->{IV}) {
     $xs .= "   IV              iv;\n";
   } else {
     $xs .= "   /* IV\t\tiv;\tUncomment this if you need to return IVs */\n";
   }
-  if ($use_nv) {
+  if ($params->{NV}) {
     $xs .= "   NV              nv;\n";
   } else {
     $xs .= "   /* NV\t\tnv;\tUncomment this if you need to return NVs */\n";
   }
-  if ($use_pv) {
+  if ($params->{PV}) {
     $xs .= "   const char      *pv;\n";
   } else {
     $xs .=
@@ -730,46 +218,69 @@ EOT
     INPUT:
        SV *            sv;
         const char *   s = SvPV(sv, len);
+EOT
+  if ($params->{''}) {
+  $xs .= << 'EOT';
+    INPUT:
+       int             utf8 = SvUTF8(sv);
+EOT
+  }
+  $xs .= << 'EOT';
     PPCODE:
 EOT
 
-  if ($use_iv xor $use_nv) {
+  if ($params->{IV} xor $params->{NV}) {
     $xs .= << "EOT";
-        /* Change this to $C_subname(s, len, &iv, &nv);
+        /* Change this to $C_subname(aTHX_ s, len, &iv, &nv);
            if you need to return both NVs and IVs */
 EOT
   }
-  $xs .= "     type = $C_subname(s, len";
-  $xs .= ', &iv' if $use_iv;
-  $xs .= ', &nv' if $use_nv;
-  $xs .= ', &pv' if $use_pv;
+  $xs .= "     type = $C_subname(aTHX_ s, len";
+  $xs .= ', utf8' if $params->{''};
+  $xs .= ', &iv' if $params->{IV};
+  $xs .= ', &nv' if $params->{NV};
+  $xs .= ', &pv' if $params->{PV};
+  $xs .= ', &sv' if $params->{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 .= << "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 macro", s));
+          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 macro %s used", s));
+           "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->{$type};
-    $xs .= << "EOT";
-        case PERL_constant_IS$type:
+    $xs .= "        case PERL_constant_IS$type:\n";
+    if (length $XS_Constant{$type}) {
+      $xs .= << "EOT";
           EXTEND(SP, 1);
           PUSHs(&PL_sv_undef);
           $XS_Constant{$type};
-          break;
 EOT
+    } else {
+      # Do nothing. return (), which will be correctly interpreted as
+      # (undef, undef)
+    }
+    $xs .= "          break;\n";
     unless ($what->{$type}) {
       chop $xs; # Yes, another need for chop not chomp.
       $xs .= " */\n";
@@ -778,7 +289,7 @@ EOT
   $xs .= << "EOT";
         default:
           sv = sv_2mortal(newSVpvf(
-           "Unexpected return type %d while processing $package macro %s used",
+           "Unexpected return type %d while processing $package_sprintf_safe macro %s, used",
                type, s));
           PUSHs(sv);
         }
@@ -814,7 +325,7 @@ sub autoload {
 
   $func .= "\n\n"
   . "    my \$constname;\n";
-  $func .= 
+  $func .=
     "    our \$AUTOLOAD;\n"  if ($compat_version >= 5.006);
 
   $func .= <<"EOT";
@@ -857,6 +368,190 @@ END
 
   return $func;
 }
+
+
+=item WriteMakefileSnippet
+
+WriteMakefileSnippet ATTRIBUTE =E<gt> VALUE [, ...] 
+
+A function to generate perl code for Makefile.PL that will regenerate
+the constant subroutines.  Parameters are named as passed to C<WriteConstants>,
+with the addition of C<INDENT> to specify the number of leading spaces
+(default 2).
+
+Currently only C<INDENT>, C<NAME>, C<DEFAULT_TYPE>, C<NAMES>, C<C_FILE> and
+C<XS_FILE> are recognised.
+
+=cut
+
+sub WriteMakefileSnippet {
+  my %args = @_;
+  my $indent = $args{INDENT} || 2;
+
+  my $result = <<"EOT";
+ExtUtils::Constant::WriteConstants(
+                                   NAME         => '$args{NAME}',
+                                   NAMES        => \\\@names,
+                                   DEFAULT_TYPE => '$args{DEFAULT_TYPE}',
+EOT
+  foreach (qw (C_FILE XS_FILE)) {
+    next unless exists $args{$_};
+    $result .= sprintf "                                   %-12s => '%s',\n",
+      $_, $args{$_};
+  }
+  $result .= <<'EOT';
+                                );
+EOT
+
+  $result =~ s/^/' 'x$indent/gem;
+  return ExtUtils::Constant::XS->dump_names({default_type=>$args{DEFAULT_TYPE},
+                                            indent=>$indent,},
+                                           @{$args{NAMES}})
+    . $result;
+}
+
+=item WriteConstants ATTRIBUTE =E<gt> VALUE [, ...]
+
+Writes a file of C code and a file of XS code which you should C<#include>
+and C<INCLUDE> in the C and XS sections respectively of your module's XS
+code.  You probably want to do this in your C<Makefile.PL>, 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<IV> 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<"C_constant">.
+
+=item PROXYSUBS
+
+If true, uses proxy subs. See L<ExtUtils::Constant::ProxySubs>.
+
+=item C_FH
+
+A filehandle to write the C code to.  If not given, then I<C_FILE> is opened
+for writing.
+
+=item C_FILE
+
+The name of the file to write containing the C code.  The default is
+C<const-c.inc>.  The C<-> 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<.c> avoids having to override Makefile.PL's
+C<.xs> to C<.c> rules.
+
+=item XS_FH
+
+A filehandle to write the XS code to.  If not given, then I<XS_FILE> is opened
+for writing.
+
+=item XS_FILE
+
+The name of the file to write containing the XS code.  The default is
+C<const-xs.inc>.
+
+=item SUBNAME
+
+The perl visible name of the XS subroutine generated which will return the
+constants. The default is C<constant>.
+
+=item C_SUBNAME
+
+The name of the C subroutine generated which will return the constants.
+The default is I<SUBNAME>.  Child subroutines have C<_> and the name
+length appended, so constants with 10 character names would be in
+C<constant_10> with the default I<XS_SUBNAME>.
+
+=back
+
+=cut
+
+sub WriteConstants {
+  my %ARGS =
+    ( # defaults
+     C_FILE =>       'const-c.inc',
+     XS_FILE =>      'const-xs.inc',
+     SUBNAME =>      'constant',
+     DEFAULT_TYPE => 'IV',
+     @_);
+
+  $ARGS{C_SUBNAME} ||= $ARGS{SUBNAME}; # No-one sane will have C_SUBNAME eq '0'
+
+  croak "Module name not specified" unless length $ARGS{NAME};
+
+  my $c_fh = $ARGS{C_FH};
+  if (!$c_fh) {
+      if ($] <= 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->new();
+      }
+      open $c_fh, ">$ARGS{C_FILE}" or die "Can't open $ARGS{C_FILE}: $!";
+  }
+
+  my $xs_fh = $ARGS{XS_FH};
+  if (!$xs_fh) {
+      if ($] <= 5.008) {
+         require FileHandle;
+         $xs_fh = FileHandle->new();
+      }
+      open $xs_fh, ">$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}) {
+      require ExtUtils::Constant::ProxySubs;
+      $ARGS{C_FH} = $c_fh;
+      $ARGS{XS_FH} = $xs_fh;
+      ExtUtils::Constant::ProxySubs->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->C_constant({package => $ARGS{NAME},
+                                                  subname => $ARGS{C_SUBNAME},
+                                                  default_type =>
+                                                      $ARGS{DEFAULT_TYPE},
+                                                      types => $types,
+                                                      breakout =>
+                                                      $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__