home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / Perl / bin / h2xs < prev    next >
Encoding:
Text File  |  1990-01-01  |  21.4 KB  |  867 lines

  1. #!/gg/bin/perl
  2.     eval 'exec /gg/bin/perl -S $0 ${1+"$@"}'
  3.     if $running_under_some_shell;
  4.  
  5. =head1 NAME
  6.  
  7. h2xs - convert .h C header files to Perl extensions
  8.  
  9. =head1 SYNOPSIS
  10.  
  11. B<h2xs> [B<-AOPXcdf>] [B<-v> version] [B<-n> module_name] [B<-p> prefix] [B<-s> sub] [headerfile ... [extra_libraries]]
  12.  
  13. B<h2xs> B<-h>
  14.  
  15. =head1 DESCRIPTION
  16.  
  17. I<h2xs> builds a Perl extension from C header files.  The extension
  18. will include functions which can be used to retrieve the value of any
  19. #define statement which was in the C header files.
  20.  
  21. The I<module_name> will be used for the name of the extension.  If
  22. module_name is not supplied then the name of the first header file
  23. will be used, with the first character capitalized.
  24.  
  25. If the extension might need extra libraries, they should be included
  26. here.  The extension Makefile.PL will take care of checking whether
  27. the libraries actually exist and how they should be loaded.
  28. The extra libraries should be specified in the form -lm -lposix, etc,
  29. just as on the cc command line.  By default, the Makefile.PL will
  30. search through the library path determined by Configure.  That path
  31. can be augmented by including arguments of the form B<-L/another/library/path>
  32. in the extra-libraries argument.
  33.  
  34. =head1 OPTIONS
  35.  
  36. =over 5
  37.  
  38. =item B<-A>
  39.  
  40. Omit all autoload facilities.  This is the same as B<-c> but also removes the
  41. S<C<require AutoLoader>> statement from the .pm file.
  42.  
  43. =item B<-F>
  44.  
  45. Additional flags to specify to C preprocessor when scanning header for
  46. function declarations. Should not be used without B<-x>.
  47.  
  48. =item B<-O>
  49.  
  50. Allows a pre-existing extension directory to be overwritten.
  51.  
  52. =item B<-P>
  53.  
  54. Omit the autogenerated stub POD section. 
  55.  
  56. =item B<-X>
  57.  
  58. Omit the XS portion.  Used to generate templates for a module which is not
  59. XS-based.
  60.  
  61. =item B<-c>
  62.  
  63. Omit C<constant()> from the .xs file and corresponding specialised
  64. C<AUTOLOAD> from the .pm file.
  65.  
  66. =item B<-d>
  67.  
  68. Turn on debugging messages.
  69.  
  70. =item B<-f>
  71.  
  72. Allows an extension to be created for a header even if that header is
  73. not found in /usr/include.
  74.  
  75. =item B<-h>
  76.  
  77. Print the usage, help and version for this h2xs and exit.
  78.  
  79. =item B<-n> I<module_name>
  80.  
  81. Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>
  82.  
  83. =item B<-p> I<prefix>
  84.  
  85. Specify a prefix which should be removed from the Perl function names, e.g., S<-p sec_rgy_> 
  86. This sets up the XS B<PREFIX> keyword and removes the prefix from functions that are
  87. autoloaded via the C<constant()> mechansim.
  88.  
  89. =item B<-s> I<sub1,sub2>
  90.  
  91. Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine.
  92. These macros are assumed to have a return type of B<char *>, e.g., S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.
  93.  
  94. =item B<-v> I<version>
  95.  
  96. Specify a version number for this extension.  This version number is added
  97. to the templates.  The default is 0.01.
  98.  
  99. =item B<-x>
  100.  
  101. Automatically generate XSUBs basing on function declarations in the
  102. header file.  The package C<C::Scan> should be installed. If this
  103. option is specified, the name of the header file may look like
  104. C<NAME1,NAME2>. In this case NAME1 is used instead of the specified string,
  105. but XSUBs are emitted only for the declarations included from file NAME2.
  106.  
  107. Note that some types of arguments/return-values for functions may
  108. result in XSUB-declarations/typemap-entries which need
  109. hand-editing. Such may be objects which cannot be converted from/to a
  110. pointer (like C<long long>), pointers to functions, or arrays.
  111.  
  112. =back
  113.  
  114. =head1 EXAMPLES
  115.  
  116.  
  117.     # Default behavior, extension is Rusers
  118.     h2xs rpcsvc/rusers
  119.  
  120.     # Same, but extension is RUSERS
  121.     h2xs -n RUSERS rpcsvc/rusers
  122.  
  123.     # Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
  124.     h2xs rpcsvc::rusers
  125.  
  126.     # Extension is ONC::RPC.  Still finds <rpcsvc/rusers.h>
  127.     h2xs -n ONC::RPC rpcsvc/rusers
  128.  
  129.     # Without constant() or AUTOLOAD
  130.     h2xs -c rpcsvc/rusers
  131.  
  132.     # Creates templates for an extension named RPC
  133.     h2xs -cfn RPC
  134.  
  135.     # Extension is ONC::RPC.
  136.     h2xs -cfn ONC::RPC
  137.  
  138.     # Makefile.PL will look for library -lrpc in 
  139.     # additional directory /opt/net/lib
  140.     h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
  141.  
  142.         # Extension is DCE::rgynbase
  143.         # prefix "sec_rgy_" is dropped from perl function names
  144.         h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
  145.  
  146.         # Extension is DCE::rgynbase
  147.         # prefix "sec_rgy_" is dropped from perl function names
  148.         # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
  149.         h2xs -n DCE::rgynbase -p sec_rgy_ \
  150.         -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
  151.  
  152.     # Make XS without defines in perl.h, but with function declarations
  153.     # visible from perl.h. Name of the extension is perl1.
  154.     # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
  155.     # Extra backslashes below because the string is passed to shell.
  156.     # Note that a directory with perl header files would 
  157.     #  be added automatically to include path.
  158.     h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
  159.  
  160.     # Same with function declaration in proto.h as visible from perl.h.
  161.     h2xs -xAn perl2 perl.h,proto.h
  162.  
  163. =head1 ENVIRONMENT
  164.  
  165. No environment variables are used.
  166.  
  167. =head1 AUTHOR
  168.  
  169. Larry Wall and others
  170.  
  171. =head1 SEE ALSO
  172.  
  173. L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.
  174.  
  175. =head1 DIAGNOSTICS
  176.  
  177. The usual warnings if it cannot read or write the files involved.
  178.  
  179. =cut
  180.  
  181. my( $H2XS_VERSION ) = ' $Revision: 1.18 $ ' =~ /\$Revision:\s+([^\s]+)/;
  182. my $TEMPLATE_VERSION = '0.01';
  183.  
  184. use Getopt::Std;
  185.  
  186. sub usage{
  187.     warn "@_\n" if @_;
  188.     die "h2xs [-AOPXcdfh] [-v version] [-n module_name] [-p prefix] [-s subs] [headerfile [extra_libraries]]
  189. version: $H2XS_VERSION
  190.     -A   Omit all autoloading facilities (implies -c).
  191.     -F   Additional flags for C preprocessor (used with -x).
  192.     -O   Allow overwriting of a pre-existing extension directory.
  193.     -P   Omit the stub POD section.
  194.     -X   Omit the XS portion.
  195.     -c   Omit the constant() function and specialised AUTOLOAD from the XS file.
  196.     -d   Turn on debugging messages.
  197.     -f   Force creation of the extension even if the C header does not exist.
  198.     -h   Display this help message
  199.     -n   Specify a name to use for the extension (recommended).
  200.     -p   Specify a prefix which should be removed from the Perl function names.
  201.     -s   Create subroutines for specified macros.
  202.     -v   Specify a version number for this extension.
  203.     -x   Autogenerate XSUBs using C::Scan.
  204. extra_libraries
  205.          are any libraries that might be needed for loading the
  206.          extension, e.g. -lm would try to link in the math library.
  207. ";
  208. }
  209.  
  210.  
  211. getopts("AF:OPXcdfhn:p:s:v:x") || usage;
  212.  
  213. usage if $opt_h;
  214.  
  215. if( $opt_v ){
  216.     $TEMPLATE_VERSION = $opt_v;
  217. }
  218. $opt_c = 1 if $opt_A;
  219. %const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s;
  220.  
  221. while (my $arg = shift) {
  222.     if ($arg =~ /^-l/i) {
  223.         $extralibs = "$arg @ARGV";
  224.         last;
  225.     }
  226.     push(@path_h, $arg);
  227. }
  228.  
  229. usage "Must supply header file or module name\n"
  230.         unless (@path_h or $opt_n);
  231.  
  232.  
  233. if( @path_h ){
  234.     foreach my $path_h (@path_h) {
  235.         $name ||= $path_h;
  236.     if( $path_h =~ s#::#/#g && $opt_n ){
  237.     warn "Nesting of headerfile ignored with -n\n";
  238.     }
  239.     $path_h .= ".h" unless $path_h =~ /\.h$/;
  240.     $fullpath = $path_h;
  241.     $path_h =~ s/,.*$// if $opt_x;
  242.     if ($^O eq 'VMS') {  # Consider overrides of default location
  243.     if ($path_h !~ m![:>\[]!) {
  244.         my($hadsys) = ($path_h =~ s!^sys/!!i);
  245.         if ($ENV{'DECC$System_Include'})     { $path_h = "DECC\$System_Include:$path_h";    }
  246.         elsif ($ENV{'DECC$Library_Include'}) { $path_h = "DECC\$Library_Include:$path_h";   }
  247.         elsif ($ENV{'GNU_CC_Include'})       { $path_h = 'GNU_CC_Include:' .
  248.                                                 ($hadsys ? '[vms]' : '[000000]') . $path_h; }
  249.         elsif ($ENV{'VAXC$Include'})         { $path_h = "VAXC\$_Include:$path_h";          }
  250.         else                                 { $path_h = "Sys\$Library:$path_h";            }
  251.     }
  252.     }
  253.     elsif ($^O eq 'os2') {
  254.     $path_h = "/usr/include/$path_h" 
  255.       if $path_h !~ m#^([a-z]:)?[./]#i and -r "/usr/include/$path_h"; 
  256.     }
  257.     else { 
  258.       $path_h = "/usr/include/$path_h" 
  259.     if $path_h !~ m#^[./]# and -r "/usr/include/$path_h"; 
  260.     }
  261.  
  262.     if (!$opt_c) {
  263.       die "Can't find $path_h\n" if ( ! $opt_f && ! -f $path_h );
  264.       # Scan the header file (we should deal with nested header files)
  265.       # Record the names of simple #define constants into const_names
  266.             # Function prototypes are processed below.
  267.       open(CH, "<$path_h") || die "Can't open $path_h: $!\n";
  268.       while (<CH>) {
  269.     if (/^#[ \t]*define\s+([\$\w]+)\b\s*[^("]/) {
  270.         print "Matched $_ ($1)\n" if $opt_d;
  271.         $_ = $1;
  272.         next if /^_.*_h_*$/i; # special case, but for what?
  273.         if (defined $opt_p) {
  274.           if (!/^$opt_p(\d)/) {
  275.         ++$prefix{$_} if s/^$opt_p//;
  276.           }
  277.           else {
  278.         warn "can't remove $opt_p prefix from '$_'!\n";
  279.           }
  280.         }
  281.         $const_names{$_}++;
  282.       }
  283.       }
  284.       close(CH);
  285.     }
  286.     }
  287.     @const_names = sort keys %const_names;
  288. }
  289.  
  290.  
  291. $module = $opt_n || do {
  292.     $name =~ s/\.h$//;
  293.     if( $name !~ /::/ ){
  294.         $name =~ s#^.*/##;
  295.         $name = "\u$name";
  296.     }
  297.     $name;
  298. };
  299.  
  300. (chdir 'ext', $ext = 'ext/') if -d 'ext';
  301.  
  302. if( $module =~ /::/ ){
  303.     $nested = 1;
  304.     @modparts = split(/::/,$module);
  305.     $modfname = $modparts[-1];
  306.     $modpname = join('/',@modparts);
  307. }
  308. else {
  309.     $nested = 0;
  310.     @modparts = ();
  311.     $modfname = $modpname = $module;
  312. }
  313.  
  314.  
  315. if ($opt_O) {
  316.     warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
  317. } else {
  318.     die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
  319. }
  320. if( $nested ){
  321.     $modpath = "";
  322.     foreach (@modparts){
  323.         mkdir("$modpath$_", 0777);
  324.         $modpath .= "$_/";
  325.     }
  326. }
  327. mkdir($modpname, 0777);
  328. chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";
  329.  
  330. my %types_seen;
  331. my %std_types;
  332. my $fdecls;
  333. my $fdecls_parsed;
  334.  
  335. if( ! $opt_X ){  # use XS, unless it was disabled
  336.   open(XS, ">$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n";
  337.   if ($opt_x) {
  338.     require C::Scan;        # Run-time directive
  339.     require Config;        # Run-time directive
  340.     warn "Scanning typemaps...\n";
  341.     get_typemap();
  342.     my $c;
  343.     my $filter;
  344.         my @fdecls;
  345.         foreach my $filename (@path_h) {
  346.     my $addflags = $opt_F || '';
  347.     if ($fullpath =~ /,/) {
  348.       $filename = $`;
  349.       $filter = $';
  350.     }
  351.     warn "Scanning $filename for functions...\n";
  352.     $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
  353.     'add_cppflags' => $addflags;
  354.     $c->set('includeDirs' => ["$Config::Config{archlib}/CORE"]);
  355.     
  356.     $fdecls_parsed = $c->get('parsed_fdecls');
  357.             push(@fdecls, @{$c->get('fdecls')});
  358.         }
  359.         $fdecls = [ @fdecls ];
  360.   }
  361. }
  362.  
  363. open(PM, ">$modfname.pm") || die "Can't create $ext$modpname/$modfname.pm: $!\n";
  364.  
  365. $" = "\n\t";
  366. warn "Writing $ext$modpname/$modfname.pm\n";
  367.  
  368. print PM <<"END";
  369. package $module;
  370.  
  371. use strict;
  372. END
  373.  
  374. if( $opt_X || $opt_c || $opt_A ){
  375.     # we won't have our own AUTOLOAD(), so won't have $AUTOLOAD
  376.     print PM <<'END';
  377. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
  378. END
  379. }
  380. else{
  381.     # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and
  382.     # will want Carp.
  383.     print PM <<'END';
  384. use Carp;
  385. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $AUTOLOAD);
  386. END
  387. }
  388.  
  389. print PM <<'END';
  390.  
  391. require Exporter;
  392. END
  393.  
  394. print PM <<"END" if ! $opt_X;  # use DynaLoader, unless XS was disabled
  395. require DynaLoader;
  396. END
  397.  
  398. # require autoloader if XS is disabled.
  399. # if XS is enabled, require autoloader unless autoloading is disabled.
  400. if( ($opt_X && (! $opt_A)) || (!$opt_X) ) {
  401.     print PM <<"END";
  402. require AutoLoader;
  403. END
  404. }
  405.  
  406. if( $opt_X || ($opt_c && ! $opt_A) ){
  407.     # we won't have our own AUTOLOAD(), so we'll inherit it.
  408.     if( ! $opt_X ) { # use DynaLoader, unless XS was disabled
  409.         print PM <<"END";
  410.  
  411. \@ISA = qw(Exporter AutoLoader DynaLoader);
  412. END
  413.     }
  414.     else{
  415.         print PM <<"END";
  416.  
  417. \@ISA = qw(Exporter AutoLoader);
  418. END
  419.     }
  420. }
  421. else{
  422.     # 1) we have our own AUTOLOAD(), so don't need to inherit it.
  423.     # or
  424.     # 2) we don't want autoloading mentioned.
  425.     if( ! $opt_X ){ # use DynaLoader, unless XS was disabled
  426.         print PM <<"END";
  427.  
  428. \@ISA = qw(Exporter DynaLoader);
  429. END
  430.     }
  431.     else{
  432.         print PM <<"END";
  433.  
  434. \@ISA = qw(Exporter);
  435. END
  436.     }
  437. }
  438.  
  439. print PM<<"END";
  440. # Items to export into callers namespace by default. Note: do not export
  441. # names by default without a very good reason. Use EXPORT_OK instead.
  442. # Do not simply export all your public functions/methods/constants.
  443. \@EXPORT = qw(
  444.     @const_names
  445. );
  446. \$VERSION = '$TEMPLATE_VERSION';
  447.  
  448. END
  449.  
  450. print PM <<"END" unless $opt_c or $opt_X;
  451. sub AUTOLOAD {
  452.     # This AUTOLOAD is used to 'autoload' constants from the constant()
  453.     # XS function.  If a constant is not found then control is passed
  454.     # to the AUTOLOAD in AutoLoader.
  455.  
  456.     my \$constname;
  457.     (\$constname = \$AUTOLOAD) =~ s/.*:://;
  458.     croak "&$module::constant not defined" if \$constname eq 'constant';
  459.     my \$val = constant(\$constname, \@_ ? \$_[0] : 0);
  460.     if (\$! != 0) {
  461.     if (\$! =~ /Invalid/) {
  462.         \$AutoLoader::AUTOLOAD = \$AUTOLOAD;
  463.         goto &AutoLoader::AUTOLOAD;
  464.     }
  465.     else {
  466.         croak "Your vendor has not defined $module macro \$constname";
  467.     }
  468.     }
  469.     *\$AUTOLOAD = sub () { \$val };
  470.     goto &\$AUTOLOAD;
  471. }
  472.  
  473. END
  474.  
  475. if( ! $opt_X ){ # print bootstrap, unless XS is disabled
  476.     print PM <<"END";
  477. bootstrap $module \$VERSION;
  478. END
  479. }
  480.  
  481. if( $opt_P ){ # if POD is disabled
  482.     $after = '__END__';
  483. }
  484. else {
  485.     $after = '=cut';
  486. }
  487.  
  488. print PM <<"END";
  489.  
  490. # Preloaded methods go here.
  491.  
  492. # Autoload methods go after $after, and are processed by the autosplit program.
  493.  
  494. 1;
  495. __END__
  496. END
  497.  
  498. $author = "A. U. Thor";
  499. $email = 'a.u.thor@a.galaxy.far.far.away';
  500.  
  501. my $const_doc = '';
  502. my $fdecl_doc = '';
  503. if (@const_names and not $opt_P) {
  504.   $const_doc = <<EOD;
  505. \n=head1 Exported constants
  506.  
  507.   @{[join "\n  ", @const_names]}
  508.  
  509. EOD
  510. }
  511. if (defined $fdecls and @$fdecls and not $opt_P) {
  512.   $fdecl_doc = <<EOD;
  513. \n=head1 Exported functions
  514.  
  515.   @{[join "\n  ", @$fdecls]}
  516.  
  517. EOD
  518. }
  519.  
  520. $pod = <<"END" unless $opt_P;
  521. ## Below is the stub of documentation for your module. You better edit it!
  522. #
  523. #=head1 NAME
  524. #
  525. #$module - Perl extension for blah blah blah
  526. #
  527. #=head1 SYNOPSIS
  528. #
  529. #  use $module;
  530. #  blah blah blah
  531. #
  532. #=head1 DESCRIPTION
  533. #
  534. #Stub documentation for $module was created by h2xs. It looks like the
  535. #author of the extension was negligent enough to leave the stub
  536. #unedited.
  537. #
  538. #Blah blah blah.
  539. #$const_doc$fdecl_doc
  540. #=head1 AUTHOR
  541. #
  542. #$author, $email
  543. #
  544. #=head1 SEE ALSO
  545. #
  546. #perl(1).
  547. #
  548. #=cut
  549. END
  550.  
  551. $pod =~ s/^\#//gm unless $opt_P;
  552. print PM $pod unless $opt_P;
  553.  
  554. close PM;
  555.  
  556.  
  557. if( ! $opt_X ){ # print XS, unless it is disabled
  558. warn "Writing $ext$modpname/$modfname.xs\n";
  559.  
  560. print XS <<"END";
  561. #ifdef __cplusplus
  562. extern "C" {
  563. #endif
  564. #include "EXTERN.h"
  565. #include "perl.h"
  566. #include "XSUB.h"
  567. #ifdef __cplusplus
  568. }
  569. #endif
  570.  
  571. END
  572. if( @path_h ){
  573.     foreach my $path_h (@path_h) {
  574.     my($h) = $path_h;
  575.     $h =~ s#^/usr/include/##;
  576.     if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; }
  577.         print XS qq{#include <$h>\n};
  578.     }
  579.     print XS "\n";
  580. }
  581.  
  582. if( ! $opt_c ){
  583. print XS <<"END";
  584. static int
  585. not_here(s)
  586. char *s;
  587. {
  588.     croak("$module::%s not implemented on this architecture", s);
  589.     return -1;
  590. }
  591.  
  592. static double
  593. constant(name, arg)
  594. char *name;
  595. int arg;
  596. {
  597.     errno = 0;
  598.     switch (*name) {
  599. END
  600.  
  601. my(@AZ, @az, @under);
  602.  
  603. foreach(@const_names){
  604.     @AZ = 'A' .. 'Z' if !@AZ && /^[A-Z]/;
  605.     @az = 'a' .. 'z' if !@az && /^[a-z]/;
  606.     @under = '_'  if !@under && /^_/;
  607. }
  608.  
  609. foreach $letter (@AZ, @az, @under) {
  610.  
  611.     last if $letter eq 'a' && !@const_names;
  612.  
  613.     print XS "    case '$letter':\n";
  614.     my($name);
  615.     while (substr($const_names[0],0,1) eq $letter) {
  616.     $name = shift(@const_names);
  617.     $macro = $prefix{$name} ? "$opt_p$name" : $name;
  618.     next if $const_xsub{$macro};
  619.     print XS <<"END";
  620.     if (strEQ(name, "$name"))
  621. #ifdef $macro
  622.         return $macro;
  623. #else
  624.         goto not_there;
  625. #endif
  626. END
  627.     }
  628.     print XS <<"END";
  629.     break;
  630. END
  631. }
  632. print XS <<"END";
  633.     }
  634.     errno = EINVAL;
  635.     return 0;
  636.  
  637. not_there:
  638.     errno = ENOENT;
  639.     return 0;
  640. }
  641.  
  642. END
  643. }
  644.  
  645. $prefix = "PREFIX = $opt_p" if defined $opt_p;
  646. # Now switch from C to XS by issuing the first MODULE declaration:
  647. print XS <<"END";
  648.  
  649. MODULE = $module        PACKAGE = $module        $prefix
  650.  
  651. END
  652.  
  653. foreach (sort keys %const_xsub) {
  654.     print XS <<"END";
  655. char *
  656. $_()
  657.  
  658.     CODE:
  659. #ifdef $_
  660.     RETVAL = $_;
  661. #else
  662.     croak("Your vendor has not defined the $module macro $_");
  663. #endif
  664.  
  665.     OUTPUT:
  666.     RETVAL
  667.  
  668. END
  669. }
  670.  
  671. # If a constant() function was written then output a corresponding
  672. # XS declaration:
  673. print XS <<"END" unless $opt_c;
  674.  
  675. double
  676. constant(name,arg)
  677.     char *        name
  678.     int        arg
  679.  
  680. END
  681.  
  682. my %seen_decl;
  683.  
  684.  
  685. sub print_decl {
  686.   my $fh = shift;
  687.   my $decl = shift;
  688.   my ($type, $name, $args) = @$decl;
  689.   return if $seen_decl{$name}++; # Need to do the same for docs as well?
  690.  
  691.   my @argnames = map {$_->[1]} @$args;
  692.   my @argtypes = map { normalize_type( $_->[0] ) } @$args;
  693.   my @argarrays = map { $_->[4] || '' } @$args;
  694.   my $numargs = @$args;
  695.   if ($numargs and $argtypes[-1] eq '...') {
  696.     $numargs--;
  697.     $argnames[-1] = '...';
  698.   }
  699.   local $" = ', ';
  700.   $type = normalize_type($type);
  701.   
  702.   print $fh <<"EOP";
  703.  
  704. $type
  705. $name(@argnames)
  706. EOP
  707.  
  708.   for $arg (0 .. $numargs - 1) {
  709.     print $fh <<"EOP";
  710.     $argtypes[$arg]    $argnames[$arg]$argarrays[$arg]
  711. EOP
  712.   }
  713. }
  714.  
  715. # Should be called before any actual call to normalize_type().
  716. sub get_typemap {
  717.   # We do not want to read ./typemap by obvios reasons.
  718.   my @tm =  qw(../../../typemap ../../typemap ../typemap);
  719.   my $stdtypemap =  "$Config::Config{privlib}/ExtUtils/typemap";
  720.   unshift @tm, $stdtypemap;
  721.   my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
  722.   my $image;
  723.   
  724.   foreach $typemap (@tm) {
  725.     next unless -e $typemap ;
  726.     # skip directories, binary files etc.
  727.     warn " Scanning $typemap\n";
  728.     warn("Warning: ignoring non-text typemap file '$typemap'\n"), next 
  729.       unless -T $typemap ;
  730.     open(TYPEMAP, $typemap) 
  731.       or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
  732.     my $mode = 'Typemap';
  733.     while (<TYPEMAP>) {
  734.       next if /^\s*\#/;
  735.       if (/^INPUT\s*$/)   { $mode = 'Input'; next; }
  736.       elsif (/^OUTPUT\s*$/)  { $mode = 'Output'; next; }
  737.       elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; }
  738.       elsif ($mode eq 'Typemap') {
  739.     next if /^\s*($|\#)/ ;
  740.     if ( ($type, $image) = 
  741.          /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o
  742.          # This may reference undefined functions:
  743.          and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) {
  744.       normalize_type($type);
  745.     }
  746.       }
  747.     }
  748.     close(TYPEMAP) or die "Cannot close $typemap: $!";
  749.   }
  750.   %std_types = %types_seen;
  751.   %types_seen = ();
  752. }
  753.  
  754.  
  755. sub normalize_type {
  756.   my $ignore_mods = '(?:\b(?:__const__|static|inline|__inline__)\b\s*)*';
  757.   my $type = shift;
  758.   $type =~ s/$ignore_mods//go;
  759.   $type =~ s/([\]\[()])/ \1 /g;
  760.   $type =~ s/\s+/ /g;
  761.   $type =~ s/\s+$//;
  762.   $type =~ s/^\s+//;
  763.   $type =~ s/\b\*/ */g;
  764.   $type =~ s/\*\b/* /g;
  765.   $type =~ s/\*\s+(?=\*)/*/g;
  766.   $types_seen{$type}++ 
  767.     unless $type eq '...' or $type eq 'void' or $std_types{$type};
  768.   $type;
  769. }
  770.  
  771. if ($opt_x) {
  772.     for $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) }
  773. }
  774.  
  775. close XS;
  776.  
  777. if (%types_seen) {
  778.   my $type;
  779.   warn "Writing $ext$modpname/typemap\n";
  780.   open TM, ">typemap" or die "Cannot open typemap file for write: $!";
  781.  
  782.   for $type (keys %types_seen) {
  783.     print TM $type, "\t" x (6 - int((length $type)/8)), "T_PTROBJ\n"
  784.   }
  785.  
  786.   close TM or die "Cannot close typemap file for write: $!";
  787. }
  788.  
  789. } # if( ! $opt_X )
  790.  
  791. warn "Writing $ext$modpname/Makefile.PL\n";
  792. open(PL, ">Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n";
  793.  
  794. print PL <<'END';
  795. use ExtUtils::MakeMaker;
  796. # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  797. # the contents of the Makefile that is written.
  798. END
  799. print PL "WriteMakefile(\n";
  800. print PL "    'NAME'    => '$module',\n";
  801. print PL "    'VERSION_FROM' => '$modfname.pm', # finds \$VERSION\n"; 
  802. if( ! $opt_X ){ # print C stuff, unless XS is disabled
  803.   print PL "    'LIBS'    => ['$extralibs'],   # e.g., '-lm' \n";
  804.   print PL "    'DEFINE'    => '',     # e.g., '-DHAVE_SOMETHING' \n";
  805.   print PL "    'INC'    => '',     # e.g., '-I/usr/include/other' \n";
  806. }
  807. print PL ");\n";
  808. close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n";
  809.  
  810. warn "Writing $ext$modpname/test.pl\n";
  811. open(EX, ">test.pl") || die "Can't create $ext$modpname/test.pl: $!\n";
  812. print EX <<'_END_';
  813. # Before `make install' is performed this script should be runnable with
  814. # `make test'. After `make install' it should work as `perl test.pl'
  815.  
  816. ######################### We start with some black magic to print on failure.
  817.  
  818. # Change 1..1 below to 1..last_test_to_print .
  819. # (It may become useful if the test is moved to ./t subdirectory.)
  820.  
  821. BEGIN { $| = 1; print "1..1\n"; }
  822. END {print "not ok 1\n" unless $loaded;}
  823. _END_
  824. print EX <<_END_;
  825. use $module;
  826. _END_
  827. print EX <<'_END_';
  828. $loaded = 1;
  829. print "ok 1\n";
  830.  
  831. ######################### End of black magic.
  832.  
  833. # Insert your test code below (better if it prints "ok 13"
  834. # (correspondingly "not ok 13") depending on the success of chunk 13
  835. # of the test code):
  836.  
  837. _END_
  838. close(EX) || die "Can't close $ext$modpname/test.pl: $!\n";
  839.  
  840. warn "Writing $ext$modpname/Changes\n";
  841. open(EX, ">Changes") || die "Can't create $ext$modpname/Changes: $!\n";
  842. print EX "Revision history for Perl extension $module.\n\n";
  843. print EX "$TEMPLATE_VERSION  ",scalar localtime,"\n";
  844. print EX "\t- original version; created by h2xs $H2XS_VERSION\n\n";
  845. close(EX) || die "Can't close $ext$modpname/Changes: $!\n";
  846.  
  847. warn "Writing $ext$modpname/MANIFEST\n";
  848. open(MANI,'>MANIFEST') or die "Can't create MANIFEST: $!";
  849. @files = <*>;
  850. if (!@files) {
  851.   eval {opendir(D,'.');};
  852.   unless ($@) { @files = readdir(D); closedir(D); }
  853. }
  854. if (!@files) { @files = map {chomp && $_} `ls`; }
  855. if ($^O eq 'VMS') {
  856.   foreach (@files) {
  857.     # Clip trailing '.' for portability -- non-VMS OSs don't expect it
  858.     s%\.$%%;
  859.     # Fix up for case-sensitive file systems
  860.     s/$modfname/$modfname/i && next;
  861.     $_ = "\U$_" if $_ eq 'manifest' or $_ eq 'changes';
  862.     $_ = 'Makefile.PL' if $_ eq 'makefile.pl';
  863.   }
  864. }
  865. print MANI join("\n",@files), "\n";
  866. close MANI;
  867.