4 use File::Basename qw(&basename &dirname);
7 # List explicitly here the variables you want Configure to
8 # generate. Metaconfig only looks for shell variables, so you
9 # have to mention them as if they were shell variables, not
10 # %Config entries. Thus you write
12 # to ensure Configure will look for $Config{startperl}.
14 # This forces PL files to create target in same directory as PL file.
15 # This is so that make depend always knows where to find PL derivatives.
18 $file = basename($0, '.PL');
19 $file .= '.com' if $^O eq 'VMS';
21 open OUT,">$file" or die "Can't create $file: $!";
23 print "Extracting $file (with variable substitutions)\n";
25 # In this section, perl variables will be expanded during extraction.
26 # You can use $Config{...} to use Configure variables.
28 print OUT <<"!GROK!THIS!";
30 eval 'exec $Config{perlpath} -S \$0 \${1+"\$@"}'
31 if \$running_under_some_shell;
34 # In the following, perl variables are not expanded during extraction.
36 print OUT <<'!NO!SUBS!';
40 h2xs - convert .h C header files to Perl extensions
44 B<h2xs> [B<-ACOPXcdf>] [B<-v> version] [B<-n> module_name] [B<-p> prefix] [B<-s> sub] [headerfile ... [extra_libraries]]
50 I<h2xs> builds a Perl extension from C header files. The extension
51 will include functions which can be used to retrieve the value of any
52 #define statement which was in the C header files.
54 The I<module_name> will be used for the name of the extension. If
55 module_name is not supplied then the name of the first header file
56 will be used, with the first character capitalized.
58 If the extension might need extra libraries, they should be included
59 here. The extension Makefile.PL will take care of checking whether
60 the libraries actually exist and how they should be loaded.
61 The extra libraries should be specified in the form -lm -lposix, etc,
62 just as on the cc command line. By default, the Makefile.PL will
63 search through the library path determined by Configure. That path
64 can be augmented by including arguments of the form B<-L/another/library/path>
65 in the extra-libraries argument.
73 Omit all autoload facilities. This is the same as B<-c> but also removes the
74 S<C<use AutoLoader>> statement from the .pm file.
78 Omits creation of the F<Changes> file, and adds a HISTORY section to
83 Additional flags to specify to C preprocessor when scanning header for
84 function declarations. Should not be used without B<-x>.
86 =item B<-M> I<regular expression>
88 selects functions/macros to process.
92 Allows a pre-existing extension directory to be overwritten.
96 Omit the autogenerated stub POD section.
100 Omit the XS portion. Used to generate templates for a module which is not
101 XS-based. C<-c> and C<-f> are implicitly enabled.
105 Omit C<constant()> from the .xs file and corresponding specialised
106 C<AUTOLOAD> from the .pm file.
110 Turn on debugging messages.
114 Allows an extension to be created for a header even if that header is
115 not found in standard include directories.
119 Print the usage, help and version for this h2xs and exit.
121 =item B<-n> I<module_name>
123 Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>
125 =item B<-o> I<regular expression>
127 Use "opaque" data type for the C types matched by the regular
128 expression, even if these types are C<typedef>-equivalent to types
129 from typemaps. Should not be used without B<-x>.
131 This may be useful since, say, types which are C<typedef>-equivalent
132 to integers may represent OS-related handles, and one may want to work
133 with these handles in OO-way, as in C<$handle-E<gt>do_something()>.
134 Use C<-o .> if you want to handle all the C<typedef>ed types as opaque types.
136 The type-to-match is whitewashed (except for commas, which have no
137 whitespace before them, and multiple C<*> which have no whitespace
140 =item B<-p> I<prefix>
142 Specify a prefix which should be removed from the Perl function names, e.g., S<-p sec_rgy_>
143 This sets up the XS B<PREFIX> keyword and removes the prefix from functions that are
144 autoloaded via the C<constant()> mechanism.
146 =item B<-s> I<sub1,sub2>
148 Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine.
149 These macros are assumed to have a return type of B<char *>, e.g., S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.
151 =item B<-v> I<version>
153 Specify a version number for this extension. This version number is added
154 to the templates. The default is 0.01.
158 Automatically generate XSUBs basing on function declarations in the
159 header file. The package C<C::Scan> should be installed. If this
160 option is specified, the name of the header file may look like
161 C<NAME1,NAME2>. In this case NAME1 is used instead of the specified string,
162 but XSUBs are emitted only for the declarations included from file NAME2.
164 Note that some types of arguments/return-values for functions may
165 result in XSUB-declarations/typemap-entries which need
166 hand-editing. Such may be objects which cannot be converted from/to a
167 pointer (like C<long long>), pointers to functions, or arrays. See
168 also the section on L<LIMITATIONS of B<-x>>.
175 # Default behavior, extension is Rusers
178 # Same, but extension is RUSERS
179 h2xs -n RUSERS rpcsvc/rusers
181 # Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
184 # Extension is ONC::RPC. Still finds <rpcsvc/rusers.h>
185 h2xs -n ONC::RPC rpcsvc/rusers
187 # Without constant() or AUTOLOAD
188 h2xs -c rpcsvc/rusers
190 # Creates templates for an extension named RPC
193 # Extension is ONC::RPC.
196 # Makefile.PL will look for library -lrpc in
197 # additional directory /opt/net/lib
198 h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
200 # Extension is DCE::rgynbase
201 # prefix "sec_rgy_" is dropped from perl function names
202 h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
204 # Extension is DCE::rgynbase
205 # prefix "sec_rgy_" is dropped from perl function names
206 # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
207 h2xs -n DCE::rgynbase -p sec_rgy_ \
208 -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
210 # Make XS without defines in perl.h, but with function declarations
211 # visible from perl.h. Name of the extension is perl1.
212 # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
213 # Extra backslashes below because the string is passed to shell.
214 # Note that a directory with perl header files would
215 # be added automatically to include path.
216 h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
218 # Same with function declaration in proto.h as visible from perl.h.
219 h2xs -xAn perl2 perl.h,proto.h
221 # Same but select only functions which match /^av_/
222 h2xs -M '^av_' -xAn perl2 perl.h,proto.h
224 # Same but treat SV* etc as "opaque" types
225 h2xs -o '^[S]V \*$' -M '^av_' -xAn perl2 perl.h,proto.h
229 No environment variables are used.
233 Larry Wall and others
237 L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.
241 The usual warnings if it cannot read or write the files involved.
243 =head1 LIMITATIONS of B<-x>
245 F<h2xs> would not distinguish whether an argument to a C function
246 which is of the form, say, C<int *>, is an input, output, or
247 input/output parameter. In particular, argument declarations of the
254 should be better rewritten as
260 if C<n> is an input parameter.
262 Additionally, F<h2xs> has no facilities to intuit that a function
269 takes a pair of address and length of data at this address, so it is better
270 to rewrite this function as
280 RETVAL = foo(s, len);
290 char *s = SvPV(sv,len);
295 MODULE = foo PACKAGE = foo PREFIX = my_
301 See L<perlxs> and L<perlxstut> for additional details.
305 my( $H2XS_VERSION ) = ' $Revision: 1.20 $ ' =~ /\$Revision:\s+([^\s]+)/;
306 my $TEMPLATE_VERSION = '0.01';
313 die "h2xs [-ACOPXcdfh] [-v version] [-n module_name] [-p prefix] [-s subs] [headerfile [extra_libraries]]
314 version: $H2XS_VERSION
315 -A Omit all autoloading facilities (implies -c).
316 -C Omit creating the Changes file, add HISTORY heading to stub POD.
317 -F Additional flags for C preprocessor (used with -x).
318 -M Mask to select C functions/macros (default is select all).
319 -O Allow overwriting of a pre-existing extension directory.
320 -P Omit the stub POD section.
321 -X Omit the XS portion (implies both -c and -f).
322 -c Omit the constant() function and specialised AUTOLOAD from the XS file.
323 -d Turn on debugging messages.
324 -f Force creation of the extension even if the C header does not exist.
325 -h Display this help message
326 -n Specify a name to use for the extension (recommended).
327 -o Regular expression for \"opaque\" types.
328 -p Specify a prefix which should be removed from the Perl function names.
329 -s Create subroutines for specified macros.
330 -v Specify a version number for this extension.
331 -x Autogenerate XSUBs using C::Scan.
333 are any libraries that might be needed for loading the
334 extension, e.g. -lm would try to link in the math library.
339 getopts("ACF:M:OPXcdfhn:o:p:s:v:x") || usage;
344 $TEMPLATE_VERSION = $opt_v;
348 $opt_c = 1 if $opt_A;
350 # -X implies -c and -f
351 $opt_c = $opt_f = 1 if $opt_X;
353 %const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s;
355 while (my $arg = shift) {
356 if ($arg =~ /^-l/i) {
357 $extralibs = "$arg @ARGV";
363 usage "Must supply header file or module name\n"
364 unless (@path_h or $opt_n);
369 $fmask = qr{$opt_M} if defined $opt_M;
370 $tmask = qr{$opt_o} if defined $opt_o;
371 my $tmask_all = $tmask && $opt_o eq '.';
374 eval {require C::Scan; 1}
376 C::Scan required if you use -x option.
377 To install C::Scan, execute
378 perl -MCPAN -e "install C::Scan"
380 unless ($tmask_all) {
381 $C::Scan::VERSION >= 0.70
383 C::Scan v. 0.70 or later required unless you use -o . option.
384 You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
385 To install C::Scan, execute
386 perl -MCPAN -e "install C::Scan"
389 } elsif ($opt_o or $opt_F) {
391 Options -o and -F do not make sense without -x.
402 if ($^O eq 'VMS') { # Consider overrides of default location
403 @paths = qw( Sys\$Library VAXC$Include );
404 push @paths, ($hadsys ? 'GNU_CC_Include[vms]' : 'GNU_CC_Include[000000]');
405 push @paths, qw( DECC$Library_Include DECC$System_Include );
407 @paths = (File::Spec->curdir(), $Config{usrinc},
408 (split ' ', $Config{locincpth}), '/usr/include');
410 foreach my $path_h (@path_h) {
412 if( $path_h =~ s#::#/#g && $opt_n ){
413 warn "Nesting of headerfile ignored with -n\n";
415 $path_h .= ".h" unless $path_h =~ /\.h$/;
417 $path_h =~ s/,.*$// if $opt_x;
419 if (not -f $path_h) {
420 my $tmp_path_h = $path_h;
421 for my $dir (@paths) {
422 last if -f ($path_h = File::Spec->catfile($dir, $tmp_path_h));
427 die "Can't find $path_h\n" if ( ! $opt_f && ! -f $path_h );
428 # Scan the header file (we should deal with nested header files)
429 # Record the names of simple #define constants into const_names
430 # Function prototypes are processed below.
431 open(CH, "<$path_h") || die "Can't open $path_h: $!\n";
434 if (/^#[ \t]*define\s+([\$\w]+)\b(?!\()\s*(?=[^" \t])(.*)/) {
437 $rest =~ s!/\*.*?(\*/|\n)|//.*!!g; # Remove comments
440 # Cannot do: (-1) and ((LHANDLE)3) are OK:
441 #print("Skip non-wordy $def => $rest\n"),
442 # next defines if $rest =~ /[^\w\$]/;
444 print("Skip stringy $def => $rest\n") if $opt_d;
447 print "Matched $_ ($def)\n" if $opt_d;
448 $seen_define{$def} = $rest;
450 next if /^_.*_h_*$/i; # special case, but for what?
451 if (defined $opt_p) {
452 if (!/^$opt_p(\d)/) {
453 ++$prefix{$_} if s/^$opt_p//;
456 warn "can't remove $opt_p prefix from '$_'!\n";
459 $prefixless{$def} = $_;
460 if (!$fmask or /$fmask/) {
461 print "... Passes mask of -M.\n" if $opt_d and $fmask;
472 $module = $opt_n || do {
481 (chdir 'ext', $ext = 'ext/') if -d 'ext';
483 if( $module =~ /::/ ){
485 @modparts = split(/::/,$module);
486 $modfname = $modparts[-1];
487 $modpname = join('/',@modparts);
492 $modfname = $modpname = $module;
497 warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
499 die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
504 mkdir("$modpath$_", 0777);
508 mkdir($modpname, 0777);
509 chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";
514 my $fdecls_parsed = [];
519 if( ! $opt_X ){ # use XS, unless it was disabled
520 open(XS, ">$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n";
522 require Config; # Run-time directive
523 warn "Scanning typemaps...\n";
527 foreach my $filename (@path_h) {
528 my $addflags = $opt_F || '';
529 if ($fullpath =~ /,/) {
533 warn "Scanning $filename for functions...\n";
534 $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
535 'add_cppflags' => $addflags;
536 $c->set('includeDirs' => ["$Config::Config{archlib}/CORE"]);
538 push @$fdecls_parsed, @{ $c->get('parsed_fdecls') };
539 push(@$fdecls, @{$c->get('fdecls')});
541 %known_fnames = map @$_[1,3], @$fdecls_parsed; # [1,3] is NAME, FULLTEXT
544 for my $i (0..$#$fdecls_parsed) {
545 next unless $fdecls_parsed->[$i][1] =~ /$fmask/; # [1] is NAME
547 print "... Function $fdecls_parsed->[$i][1] passes -M mask.\n"
550 $fdecls = [@$fdecls[@good]];
551 $fdecls_parsed = [@$fdecls_parsed[@good]];
553 unless ($tmask_all) {
554 warn "Scanning $filename for typedefs...\n";
555 my $td = $c->get('typedef_hash');
556 # eval {require 'dumpvar.pl'; ::dumpValue($td)} or warn $@ if $opt_d;
557 my @good_td = grep $td->{$_}[1] eq '', keys %$td;
558 @typedefs_pre{@good_td} = map $_->[0], @$td{@good_td};
560 $typedef_rex = qr(\b(?<!struct )(?:@good_td)\b);
563 # Remove macros which expand to typedefs
564 my @td = @{$c->get('typedefs_maybe')};
565 print "Typedefs are @td.\n" if $opt_d;
566 my %td = map {($_, $_)} @td;
567 # Add some other possible but meaningless values for macros
568 for my $k (qw(char double float int long short unsigned signed void)) {
569 $td{"$_$k"} = "$_$k" for ('', 'signed ', 'unsigned ');
571 # eval {require 'dumpvar.pl'; ::dumpValue( [\@td, \%td] ); 1} or warn $@;
574 while (keys %td > $n) {
577 while (($k, $v) = each %seen_define) {
578 # print("found '$k'=>'$v'\n"),
579 $bad_macs{$k} = $td{$k} = $td{$v} if exists $td{$v};
582 # Now %bad_macs contains names of bad macros
583 for my $k (keys %bad_macs) {
584 delete $const_names{$prefixless{$k}};
585 print "Ignoring macro $k which expands to a typedef name '$bad_macs{$k}'\n" if $opt_d;
589 @const_names = sort keys %const_names;
591 open(PM, ">$modfname.pm") || die "Can't create $ext$modpname/$modfname.pm: $!\n";
594 warn "Writing $ext$modpname/$modfname.pm\n";
602 if( $opt_X || $opt_c || $opt_A ){
603 # we won't have our own AUTOLOAD(), so won't have $AUTOLOAD
605 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
609 # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and
613 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $AUTOLOAD);
622 print PM <<"END" if ! $opt_X; # use DynaLoader, unless XS was disabled
627 # Are we using AutoLoader or not?
628 unless ($opt_A) { # no autoloader whatsoever.
629 unless ($opt_c) { # we're doing the AUTOLOAD
630 print PM "use AutoLoader;\n";
633 print PM "use AutoLoader qw(AUTOLOAD);\n"
638 my $myISA = '@ISA = qw(Exporter'; # We seem to always want this.
639 $myISA .= ' DynaLoader' unless $opt_X; # no XS
641 print PM "\n$myISA\n\n";
644 # Items to export into callers namespace by default. Note: do not export
645 # names by default without a very good reason. Use EXPORT_OK instead.
646 # Do not simply export all your public functions/methods/constants.
648 # This allows declaration use $module ':all';
649 # If you do not need this, moving things directly into \@EXPORT or \@EXPORT_OK
651 %EXPORT_TAGS = ( ':all' => [ qw(
655 \@EXPORT_OK = ( \@{ \$EXPORT_TAGS{':all'} } );
660 \$VERSION = '$TEMPLATE_VERSION';
664 print PM <<"END" unless $opt_c or $opt_X;
666 # This AUTOLOAD is used to 'autoload' constants from the constant()
667 # XS function. If a constant is not found then control is passed
668 # to the AUTOLOAD in AutoLoader.
671 (\$constname = \$AUTOLOAD) =~ s/.*:://;
672 croak "&$module::constant not defined" if \$constname eq 'constant';
673 my \$val = constant(\$constname, \@_ ? \$_[0] : 0);
675 if (\$! =~ /Invalid/ || \$!{EINVAL}) {
676 \$AutoLoader::AUTOLOAD = \$AUTOLOAD;
677 goto &AutoLoader::AUTOLOAD;
680 croak "Your vendor has not defined $module macro \$constname";
684 # Next line doesn't help with older Perls; in newers: no such warnings
685 # local \$^W = 0; # Prototype mismatch: sub XXX vs ()
686 *\$AUTOLOAD = sub () { \$val };
693 if( ! $opt_X ){ # print bootstrap, unless XS is disabled
695 bootstrap $module \$VERSION;
699 if( $opt_P ){ # if POD is disabled
708 # Preloaded methods go here.
711 print PM <<"END" unless $opt_A;
713 # Autoload methods go after $after, and are processed by the autosplit program.
722 $author = "A. U. Thor";
723 $email = 'a.u.thor@a.galaxy.far.far.away';
726 $revhist = <<EOT if $opt_C;
732 =item $TEMPLATE_VERSION
734 Original version; created by h2xs $H2XS_VERSION with options
749 if (@const_names and not $opt_P) {
751 =head2 Exportable constants
753 @{[join "\n ", @const_names]}
757 if (defined $fdecls and @$fdecls and not $opt_P) {
758 my @fnames = sort map $_->[1], @$fdecls_parsed; # 1 is NAME
761 =head2 Exportable functions
763 @{[join "\n ", @known_fnames{@fnames}]}
768 $pod = <<"END" unless $opt_P;
769 ## Below is the stub of documentation for your module. You better edit it!
773 #$module - Perl extension for blah blah blah
782 #Stub documentation for $module was created by h2xs. It looks like the
783 #author of the extension was negligent enough to leave the stub
799 $pod =~ s/^\#//gm unless $opt_P;
800 print PM $pod unless $opt_P;
805 if( ! $opt_X ){ # print XS, unless it is disabled
806 warn "Writing $ext$modpname/$modfname.xs\n";
815 foreach my $path_h (@path_h) {
817 $h =~ s#^/usr/include/##;
818 if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; }
819 print XS qq{#include <$h>\n};
824 my %pointer_typedefs;
829 my $out = $pointer_typedefs{$type};
830 return $out if defined $out;
832 $out = ($type =~ /\*$/);
833 # This converts only the guys which do not have trailing part in the typedef
835 and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
836 $type = normalize_type($type);
837 print "Is-Pointer: Type mutation via typedefs: $otype ==> $type\n"
839 $out = td_is_pointer($type);
841 return ($pointer_typedefs{$otype} = $out);
846 my $out = $struct_typedefs{$type};
847 return $out if defined $out;
849 $out = ($type =~ /^struct\b/) && !td_is_pointer($type);
850 # This converts only the guys which do not have trailing part in the typedef
852 and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
853 $type = normalize_type($type);
854 print "Is-Struct: Type mutation via typedefs: $otype ==> $type\n"
856 $out = td_is_struct($type);
858 return ($struct_typedefs{$otype} = $out);
861 # Some macros will bomb if you try to return them from a double-returning func.
862 # Say, ((char *)0), or strlen (if somebody #define STRLEN strlen).
863 # Fortunately, we can detect both these cases...
864 sub protect_convert_to_double {
867 return '' unless defined ($val = $seen_define{$in});
868 return '(IV)' if $known_fnames{$val};
869 # OUT_t of ((OUT_t)-1):
870 return '' unless $val =~ /^\s*(\(\s*)?\(\s*([^()]*?)\s*\)/;
871 td_is_pointer($2) ? '(IV)' : '';
874 # For each of the generated functions, length($pref) leading
875 # letters are already checked. Moreover, it is recommended that
876 # the generated functions uses switch on letter at offset at least
877 # $off + length($pref).
879 # The given list has length($pref) chars removed at front, it is
880 # guarantied that $off leading chars in the rest are the same for all
883 # Returns: how at which offset it was decided to make a switch, or -1 if none.
888 my ($fh, $pref, $off, $list) = (shift,shift,shift,shift);
890 my $offarg = length $pref;
892 if (@$list == 0) { # Can happen on the initial iteration only
895 constant(char *name, int arg)
904 if (@$list == 1) { # Can happen on the initial iteration only
905 my $protect = protect_convert_to_double("$pref$list->[0]");
909 constant(char *name, int arg)
911 if (strEQ(name + $offarg, "$list->[0]")) { /* $pref removed */
912 #ifdef $pref$list->[0]
913 return $protect$pref$list->[0];
927 my $c = substr $n, $off, 1;
928 $leading{$c} = [] unless exists $leading{$c};
929 push @{$leading{$c}}, substr $n, $off + 1;
932 if (keys(%leading) == 1) {
933 return 1 + write_const $fh, $pref, $off + 1, $list;
936 my $leader = substr $list->[0], 0, $off;
937 foreach $letter (keys %leading) {
938 write_const $fh, "$pref$leader$letter", 0, $leading{$letter}
939 if @{$leading{$letter}} > 1;
942 my $npref = "_$pref";
943 $npref = '' if $pref eq '';
947 constant$npref(char *name, int arg)
950 switch (name[$offarg + $off]) {
953 foreach $letter (sort keys %leading) {
955 $let = '\0' if $letter eq '';
960 if (@{$leading{$letter}} > 1) {
961 # It makes sense to call a function
964 if (!strnEQ(name + $offarg,"$leader", $off))
969 return constant_$pref$leader$letter(name, arg);
974 = protect_convert_to_double("$pref$leader$letter$leading{$letter}[0]");
977 if (strEQ(name + $offarg, "$leader$letter$leading{$letter}[0]")) { /* $pref removed */
978 #ifdef $pref$leader$letter$leading{$letter}[0]
979 return $protect$pref$leader$letter$leading{$letter}[0];
1006 croak("$module::%s not implemented on this architecture", s);
1012 write_const(\*XS, '', 0, \@const_names);
1015 $prefix = "PREFIX = $opt_p" if defined $opt_p;
1016 # Now switch from C to XS by issuing the first MODULE declaration:
1019 MODULE = $module PACKAGE = $module $prefix
1023 foreach (sort keys %const_xsub) {
1032 croak("Your vendor has not defined the $module macro $_");
1041 # If a constant() function was written then output a corresponding
1043 print XS <<"END" unless $opt_c;
1058 my ($type, $name, $args) = @$decl;
1059 return if $seen_decl{$name}++; # Need to do the same for docs as well?
1061 my @argnames = map {$_->[1]} @$args;
1062 my @argtypes = map { normalize_type( $_->[0], 1 ) } @$args;
1063 my @argarrays = map { $_->[4] || '' } @$args;
1064 my $numargs = @$args;
1065 if ($numargs and $argtypes[-1] eq '...') {
1067 $argnames[-1] = '...';
1070 $type = normalize_type($type, 1);
1078 for $arg (0 .. $numargs - 1) {
1080 $argtypes[$arg] $argnames[$arg]$argarrays[$arg]
1085 # Should be called before any actual call to normalize_type().
1087 # We do not want to read ./typemap by obvios reasons.
1088 my @tm = qw(../../../typemap ../../typemap ../typemap);
1089 my $stdtypemap = "$Config::Config{privlib}/ExtUtils/typemap";
1090 unshift @tm, $stdtypemap;
1091 my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
1094 # Start with useful default values
1095 $typemap{float} = 'T_DOUBLE';
1097 foreach $typemap (@tm) {
1098 next unless -e $typemap ;
1099 # skip directories, binary files etc.
1100 warn " Scanning $typemap\n";
1101 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
1102 unless -T $typemap ;
1103 open(TYPEMAP, $typemap)
1104 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
1105 my $mode = 'Typemap';
1108 if (/^INPUT\s*$/) { $mode = 'Input'; next; }
1109 elsif (/^OUTPUT\s*$/) { $mode = 'Output'; next; }
1110 elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; }
1111 elsif ($mode eq 'Typemap') {
1112 next if /^\s*($|\#)/ ;
1113 if ( ($type, $image) =
1114 /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o
1115 # This may reference undefined functions:
1116 and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) {
1117 $typemap{normalize_type($type)} = $image;
1121 close(TYPEMAP) or die "Cannot close $typemap: $!";
1123 %std_types = %types_seen;
1128 sub normalize_type { # Second arg: do not strip const's before \*
1130 # XXXX function-pointer declarations?
1131 my $keep_deep_const = shift() ? '\b(?![^(,)]*\*)' : '';
1133 = "(?:\b(?:(?:__const__|const)$keep_deep_const|static|inline|__inline__)\b\s*)*";
1134 $type =~ s/$ignore_mods//go;
1135 $type =~ s/([^\s\w])/ \1 /g;
1139 $type =~ s/\* (?=\*)/*/g;
1140 $type =~ s/\. \. \./.../g;
1142 $types_seen{$type}++
1143 unless $type eq '...' or $type eq 'void' or $std_types{$type};
1149 sub assign_typemap_entry {
1153 if ($tmask and $type =~ /$tmask/) {
1154 print "Type $type matches -o mask\n" if $opt_d;
1155 $entry = (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
1157 elsif ($typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
1158 $type = normalize_type $type;
1159 print "Type mutation via typedefs: $otype ==> $type\n" if $opt_d;
1160 $entry = assign_typemap_entry($type);
1162 $entry ||= $typemap{$otype}
1163 || (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
1164 $typemap{$otype} = $entry;
1165 $need_opaque = 1 if $entry eq "T_OPAQUE_STRUCT";
1170 for $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) }
1177 warn "Writing $ext$modpname/typemap\n";
1178 open TM, ">typemap" or die "Cannot open typemap file for write: $!";
1180 for $type (keys %types_seen) {
1181 my $entry = assign_typemap_entry $type;
1182 print TM $type, "\t" x (5 - int((length $type)/8)), "\t$entry\n"
1185 print TM <<'EOP' if $need_opaque; # Older Perls do not have correct entry
1186 #############################################################################
1189 if (sv_derived_from($arg, \"${ntype}\")) {
1191 char *s = SvPV((SV*)SvRV($arg), len);
1193 if (len != sizeof($var))
1194 croak(\"Size %d of packed data != expected %d\",
1199 croak(\"$var is not of type ${ntype}\")
1200 #############################################################################
1203 sv_setref_pvn($arg, \"${ntype}\", (char *)&$var, sizeof($var));
1206 close TM or die "Cannot close typemap file for write: $!";
1211 warn "Writing $ext$modpname/Makefile.PL\n";
1212 open(PL, ">Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n";
1215 use ExtUtils::MakeMaker;
1216 # See lib/ExtUtils/MakeMaker.pm for details of how to influence
1217 # the contents of the Makefile that is written.
1219 print PL "WriteMakefile(\n";
1220 print PL " 'NAME' => '$module',\n";
1221 print PL " 'VERSION_FROM' => '$modfname.pm', # finds \$VERSION\n";
1222 if( ! $opt_X ){ # print C stuff, unless XS is disabled
1223 $opt_F = '' unless defined $opt_F;
1224 print PL " 'LIBS' => ['$extralibs'], # e.g., '-lm' \n";
1225 print PL " 'DEFINE' => '$opt_F', # e.g., '-DHAVE_SOMETHING' \n";
1226 print PL " 'INC' => '', # e.g., '-I/usr/include/other' \n";
1229 close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n";
1231 warn "Writing $ext$modpname/test.pl\n";
1232 open(EX, ">test.pl") || die "Can't create $ext$modpname/test.pl: $!\n";
1234 # Before `make install' is performed this script should be runnable with
1235 # `make test'. After `make install' it should work as `perl test.pl'
1237 ######################### We start with some black magic to print on failure.
1239 # Change 1..1 below to 1..last_test_to_print .
1240 # (It may become useful if the test is moved to ./t subdirectory.)
1242 BEGIN { $| = 1; print "1..1\n"; }
1243 END {print "not ok 1\n" unless $loaded;}
1252 ######################### End of black magic.
1254 # Insert your test code below (better if it prints "ok 13"
1255 # (correspondingly "not ok 13") depending on the success of chunk 13
1256 # of the test code):
1259 close(EX) || die "Can't close $ext$modpname/test.pl: $!\n";
1262 warn "Writing $ext$modpname/Changes\n";
1264 open(EX, ">Changes") || die "Can't create $ext$modpname/Changes: $!\n";
1265 @ARGS = map {/[\s\"\'\`\$*?^|&<>\[\]\{\}\(\)]/ ? "'$_'" : $_} @ARGS;
1267 Revision history for Perl extension $module.
1269 $TEMPLATE_VERSION @{[scalar localtime]}
1270 \t- original version; created by h2xs $H2XS_VERSION with options
1274 close(EX) || die "Can't close $ext$modpname/Changes: $!\n";
1277 warn "Writing $ext$modpname/MANIFEST\n";
1278 open(MANI,'>MANIFEST') or die "Can't create MANIFEST: $!";
1281 eval {opendir(D,'.');};
1282 unless ($@) { @files = readdir(D); closedir(D); }
1284 if (!@files) { @files = map {chomp && $_} `ls`; }
1287 # Clip trailing '.' for portability -- non-VMS OSs don't expect it
1289 # Fix up for case-sensitive file systems
1290 s/$modfname/$modfname/i && next;
1291 $_ = "\U$_" if $_ eq 'manifest' or $_ eq 'changes';
1292 $_ = 'Makefile.PL' if $_ eq 'makefile.pl';
1295 print MANI join("\n",@files), "\n";
1299 close OUT or die "Can't close $file: $!";
1300 chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
1301 exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';