home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / bin / h2xs.bat < prev    next >
Encoding:
DOS Batch File  |  2002-12-01  |  58.3 KB  |  2,130 lines

  1. @rem = '--*-Perl-*--
  2. @echo off
  3. if "%OS%" == "Windows_NT" goto WinNT
  4. perl -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
  5. goto endofperl
  6. :WinNT
  7. perl -x -S %0 %*
  8. if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofperl
  9. if %errorlevel% == 9009 echo You do not have Perl in your PATH.
  10. if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul
  11. goto endofperl
  12. @rem ';
  13. #!perl
  14. #line 15
  15.     eval 'exec D:\p4\Apps\Gecko\MSI\data\ActivePerl\Perl\bin\perl.exe -S $0 ${1+"$@"}'
  16.     if $running_under_some_shell;
  17.  
  18. use warnings;
  19.  
  20. =head1 NAME
  21.  
  22. h2xs - convert .h C header files to Perl extensions
  23.  
  24. =head1 SYNOPSIS
  25.  
  26. B<h2xs> [B<OPTIONS> ...] [headerfile ... [extra_libraries]]
  27.  
  28. B<h2xs> B<-h>|B<-?>|B<--help>
  29.  
  30. =head1 DESCRIPTION
  31.  
  32. I<h2xs> builds a Perl extension from C header files.  The extension
  33. will include functions which can be used to retrieve the value of any
  34. #define statement which was in the C header files.
  35.  
  36. The I<module_name> will be used for the name of the extension.  If
  37. module_name is not supplied then the name of the first header file
  38. will be used, with the first character capitalized.
  39.  
  40. If the extension might need extra libraries, they should be included
  41. here.  The extension Makefile.PL will take care of checking whether
  42. the libraries actually exist and how they should be loaded.  The extra
  43. libraries should be specified in the form -lm -lposix, etc, just as on
  44. the cc command line.  By default, the Makefile.PL will search through
  45. the library path determined by Configure.  That path can be augmented
  46. by including arguments of the form B<-L/another/library/path> in the
  47. extra-libraries argument.
  48.  
  49. =head1 OPTIONS
  50.  
  51. =over 5
  52.  
  53. =item B<-A>, B<--omit-autoload>
  54.  
  55. Omit all autoload facilities.  This is the same as B<-c> but also
  56. removes the S<C<use AutoLoader>> statement from the .pm file.
  57.  
  58. =item B<-B>, B<--beta-version>
  59.  
  60. Use an alpha/beta style version number.  Causes version number to
  61. be "0.00_01" unless B<-v> is specified.
  62.  
  63. =item B<-C>, B<--omit-changes>
  64.  
  65. Omits creation of the F<Changes> file, and adds a HISTORY section to
  66. the POD template.
  67.  
  68. =item B<-F>, B<--cpp-flags>=I<addflags>
  69.  
  70. Additional flags to specify to C preprocessor when scanning header for
  71. function declarations.  Writes these options in the generated F<Makefile.PL>
  72. too.
  73.  
  74. =item B<-M>, B<--func-mask>=I<regular expression>
  75.  
  76. selects functions/macros to process.
  77.  
  78. =item B<-O>, B<--overwrite-ok>
  79.  
  80. Allows a pre-existing extension directory to be overwritten.
  81.  
  82. =item B<-P>, B<--omit-pod>
  83.  
  84. Omit the autogenerated stub POD section. 
  85.  
  86. =item B<-X>, B<--omit-XS>
  87.  
  88. Omit the XS portion.  Used to generate templates for a module which is not
  89. XS-based.  C<-c> and C<-f> are implicitly enabled.
  90.  
  91. =item B<-a>, B<--gen-accessors>
  92.  
  93. Generate an accessor method for each element of structs and unions. The
  94. generated methods are named after the element name; will return the current
  95. value of the element if called without additional arguments; and will set
  96. the element to the supplied value (and return the new value) if called with
  97. an additional argument. Embedded structures and unions are returned as a
  98. pointer rather than the complete structure, to facilitate chained calls.
  99.  
  100. These methods all apply to the Ptr type for the structure; additionally
  101. two methods are constructed for the structure type itself, C<_to_ptr>
  102. which returns a Ptr type pointing to the same structure, and a C<new>
  103. method to construct and return a new structure, initialised to zeroes.
  104.  
  105. =item B<-b>, B<--compat-version>=I<version>
  106.  
  107. Generates a .pm file which is backwards compatible with the specified
  108. perl version.
  109.  
  110. For versions < 5.6.0, the changes are.
  111.     - no use of 'our' (uses 'use vars' instead)
  112.     - no 'use warnings'
  113.  
  114. Specifying a compatibility version higher than the version of perl you
  115. are using to run h2xs will have no effect.  If unspecified h2xs will default
  116. to compatibility with the version of perl you are using to run h2xs.
  117.  
  118. =item B<-c>, B<--omit-constant>
  119.  
  120. Omit C<constant()> from the .xs file and corresponding specialised
  121. C<AUTOLOAD> from the .pm file.
  122.  
  123. =item B<-d>, B<--debugging>
  124.  
  125. Turn on debugging messages.
  126.  
  127. =item B<-f>, B<--force>
  128.  
  129. Allows an extension to be created for a header even if that header is
  130. not found in standard include directories.
  131.  
  132. =item B<-g>, B<--global>
  133.  
  134. Include code for safely storing static data in the .xs file. 
  135. Extensions that do no make use of static data can ignore this option.
  136.  
  137. =item B<-h>, B<-?>, B<--help>
  138.  
  139. Print the usage, help and version for this h2xs and exit.
  140.  
  141. =item B<-k>, B<--omit-const-func>
  142.  
  143. For function arguments declared as C<const>, omit the const attribute in the
  144. generated XS code.
  145.  
  146. =item B<-m>, B<--gen-tied-var>
  147.  
  148. B<Experimental>: for each variable declared in the header file(s), declare
  149. a perl variable of the same name magically tied to the C variable.
  150.  
  151. =item B<-n>, B<--name>=I<module_name>
  152.  
  153. Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>
  154.  
  155. =item B<-o>, B<--opaque-re>=I<regular expression>
  156.  
  157. Use "opaque" data type for the C types matched by the regular
  158. expression, even if these types are C<typedef>-equivalent to types
  159. from typemaps.  Should not be used without B<-x>.
  160.  
  161. This may be useful since, say, types which are C<typedef>-equivalent
  162. to integers may represent OS-related handles, and one may want to work
  163. with these handles in OO-way, as in C<$handle-E<gt>do_something()>.
  164. Use C<-o .> if you want to handle all the C<typedef>ed types as opaque
  165. types.
  166.  
  167. The type-to-match is whitewashed (except for commas, which have no
  168. whitespace before them, and multiple C<*> which have no whitespace
  169. between them).
  170.  
  171. =item B<-p>, B<--remove-prefix>=I<prefix>
  172.  
  173. Specify a prefix which should be removed from the Perl function names,
  174. e.g., S<-p sec_rgy_> This sets up the XS B<PREFIX> keyword and removes
  175. the prefix from functions that are autoloaded via the C<constant()>
  176. mechanism.
  177.  
  178. =item B<-s>, B<--const-subs>=I<sub1,sub2>
  179.  
  180. Create a perl subroutine for the specified macros rather than autoload
  181. with the constant() subroutine.  These macros are assumed to have a
  182. return type of B<char *>, e.g.,
  183. S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.
  184.  
  185. =item B<-t>, B<--default-type>=I<type>
  186.  
  187. Specify the internal type that the constant() mechanism uses for macros.
  188. The default is IV (signed integer).  Currently all macros found during the
  189. header scanning process will be assumed to have this type.  Future versions
  190. of C<h2xs> may gain the ability to make educated guesses.
  191.  
  192. =item B<--use-new-tests>
  193.  
  194. When B<--compat-version> (B<-b>) is present the generated tests will use
  195. C<Test::More> rather than C<Test> which is the default for versions before
  196. 5.7.2 .   C<Test::More> will be added to PREREQ_PM in the generated
  197. C<Makefile.PL>.
  198.  
  199. =item B<--use-old-tests>
  200.  
  201. Will force the generation of test code that uses the older C<Test> module.
  202.  
  203. =item B<--skip-exporter>
  204.  
  205. Do not use C<Exporter> and/or export any symbol.
  206.  
  207. =item B<--skip-ppport>
  208.  
  209. Do not use C<Devel::PPPort>: no portability to older version.
  210.  
  211. =item B<--skip-autoloader>
  212.  
  213. Do not use the module C<AutoLoader>; but keep the constant() function
  214. and C<sub AUTOLOAD> for constants.
  215.  
  216. =item B<--skip-strict>
  217.  
  218. Do not use the pragma C<strict>.
  219.  
  220. =item B<--skip-warnings>
  221.  
  222. Do not use the pragma C<warnings>.
  223.  
  224. =item B<-v>, B<--version>=I<version>
  225.  
  226. Specify a version number for this extension.  This version number is added
  227. to the templates.  The default is 0.01, or 0.00_01 if C<-B> is specified.
  228. The version specified should be numeric.
  229.  
  230. =item B<-x>, B<--autogen-xsubs>
  231.  
  232. Automatically generate XSUBs basing on function declarations in the
  233. header file.  The package C<C::Scan> should be installed. If this
  234. option is specified, the name of the header file may look like
  235. C<NAME1,NAME2>. In this case NAME1 is used instead of the specified
  236. string, but XSUBs are emitted only for the declarations included from
  237. file NAME2.
  238.  
  239. Note that some types of arguments/return-values for functions may
  240. result in XSUB-declarations/typemap-entries which need
  241. hand-editing. Such may be objects which cannot be converted from/to a
  242. pointer (like C<long long>), pointers to functions, or arrays.  See
  243. also the section on L<LIMITATIONS of B<-x>>.
  244.  
  245. =back
  246.  
  247. =head1 EXAMPLES
  248.  
  249.  
  250.     # Default behavior, extension is Rusers
  251.     h2xs rpcsvc/rusers
  252.  
  253.     # Same, but extension is RUSERS
  254.     h2xs -n RUSERS rpcsvc/rusers
  255.  
  256.     # Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
  257.     h2xs rpcsvc::rusers
  258.  
  259.     # Extension is ONC::RPC.  Still finds <rpcsvc/rusers.h>
  260.     h2xs -n ONC::RPC rpcsvc/rusers
  261.  
  262.     # Without constant() or AUTOLOAD
  263.     h2xs -c rpcsvc/rusers
  264.  
  265.     # Creates templates for an extension named RPC
  266.     h2xs -cfn RPC
  267.  
  268.     # Extension is ONC::RPC.
  269.     h2xs -cfn ONC::RPC
  270.  
  271.     # Makefile.PL will look for library -lrpc in 
  272.     # additional directory /opt/net/lib
  273.     h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
  274.  
  275.         # Extension is DCE::rgynbase
  276.         # prefix "sec_rgy_" is dropped from perl function names
  277.         h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
  278.  
  279.         # Extension is DCE::rgynbase
  280.         # prefix "sec_rgy_" is dropped from perl function names
  281.         # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
  282.         h2xs -n DCE::rgynbase -p sec_rgy_ \
  283.         -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
  284.  
  285.     # Make XS without defines in perl.h, but with function declarations
  286.     # visible from perl.h. Name of the extension is perl1.
  287.     # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
  288.     # Extra backslashes below because the string is passed to shell.
  289.     # Note that a directory with perl header files would 
  290.     #  be added automatically to include path.
  291.     h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
  292.  
  293.     # Same with function declaration in proto.h as visible from perl.h.
  294.     h2xs -xAn perl2 perl.h,proto.h
  295.  
  296.     # Same but select only functions which match /^av_/
  297.     h2xs -M '^av_' -xAn perl2 perl.h,proto.h
  298.  
  299.     # Same but treat SV* etc as "opaque" types
  300.     h2xs -o '^[S]V \*$' -M '^av_' -xAn perl2 perl.h,proto.h
  301.  
  302. =head2 Extension based on F<.h> and F<.c> files
  303.  
  304. Suppose that you have some C files implementing some functionality,
  305. and the corresponding header files.  How to create an extension which
  306. makes this functionality accessable in Perl?  The example below
  307. assumes that the header files are F<interface_simple.h> and
  308. I<interface_hairy.h>, and you want the perl module be named as
  309. C<Ext::Ension>.  If you need some preprocessor directives and/or
  310. linking with external libraries, see the flags C<-F>, C<-L> and C<-l>
  311. in L<"OPTIONS">.
  312.  
  313. =over
  314.  
  315. =item Find the directory name
  316.  
  317. Start with a dummy run of h2xs:
  318.  
  319.   h2xs -Afn Ext::Ension
  320.  
  321. The only purpose of this step is to create the needed directories, and
  322. let you know the names of these directories.  From the output you can
  323. see that the directory for the extension is F<Ext/Ension>.
  324.  
  325. =item Copy C files
  326.  
  327. Copy your header files and C files to this directory F<Ext/Ension>.
  328.  
  329. =item Create the extension
  330.  
  331. Run h2xs, overwriting older autogenerated files:
  332.  
  333.   h2xs -Oxan Ext::Ension interface_simple.h interface_hairy.h
  334.  
  335. h2xs looks for header files I<after> changing to the extension
  336. directory, so it will find your header files OK.
  337.  
  338. =item Archive and test
  339.  
  340. As usual, run
  341.  
  342.   cd Ext/Ension
  343.   perl Makefile.PL
  344.   make dist
  345.   make
  346.   make test
  347.  
  348. =item Hints
  349.  
  350. It is important to do C<make dist> as early as possible.  This way you
  351. can easily merge(1) your changes to autogenerated files if you decide
  352. to edit your C<.h> files and rerun h2xs.
  353.  
  354. Do not forget to edit the documentation in the generated F<.pm> file.
  355.  
  356. Consider the autogenerated files as skeletons only, you may invent
  357. better interfaces than what h2xs could guess.
  358.  
  359. Consider this section as a guideline only, some other options of h2xs
  360. may better suit your needs.
  361.  
  362. =back
  363.  
  364. =head1 ENVIRONMENT
  365.  
  366. No environment variables are used.
  367.  
  368. =head1 AUTHOR
  369.  
  370. Larry Wall and others
  371.  
  372. =head1 SEE ALSO
  373.  
  374. L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.
  375.  
  376. =head1 DIAGNOSTICS
  377.  
  378. The usual warnings if it cannot read or write the files involved.
  379.  
  380. =head1 LIMITATIONS of B<-x>
  381.  
  382. F<h2xs> would not distinguish whether an argument to a C function
  383. which is of the form, say, C<int *>, is an input, output, or
  384. input/output parameter.  In particular, argument declarations of the
  385. form
  386.  
  387.     int
  388.     foo(n)
  389.     int *n
  390.  
  391. should be better rewritten as
  392.  
  393.     int
  394.     foo(n)
  395.     int &n
  396.  
  397. if C<n> is an input parameter.
  398.  
  399. Additionally, F<h2xs> has no facilities to intuit that a function
  400.  
  401.    int
  402.    foo(addr,l)
  403.     char *addr
  404.     int   l
  405.  
  406. takes a pair of address and length of data at this address, so it is better
  407. to rewrite this function as
  408.  
  409.     int
  410.     foo(sv)
  411.         SV *addr
  412.     PREINIT:
  413.         STRLEN len;
  414.         char *s;
  415.     CODE:
  416.         s = SvPV(sv,len);
  417.         RETVAL = foo(s, len);
  418.     OUTPUT:
  419.         RETVAL
  420.  
  421. or alternately
  422.  
  423.     static int
  424.     my_foo(SV *sv)
  425.     {
  426.     STRLEN len;
  427.     char *s = SvPV(sv,len);
  428.  
  429.     return foo(s, len);
  430.     }
  431.  
  432.     MODULE = foo    PACKAGE = foo    PREFIX = my_
  433.  
  434.     int
  435.     foo(sv)
  436.     SV *sv
  437.  
  438. See L<perlxs> and L<perlxstut> for additional details.
  439.  
  440. =cut
  441.  
  442. # ' # Grr
  443. use strict;
  444.  
  445.  
  446. my( $H2XS_VERSION ) = ' $Revision: 1.22 $ ' =~ /\$Revision:\s+([^\s]+)/;
  447. my $TEMPLATE_VERSION = '0.01';
  448. my @ARGS = @ARGV;
  449. my $compat_version = $];
  450.  
  451. use Getopt::Long;
  452. use Config;
  453. use Text::Wrap;
  454. $Text::Wrap::huge = 'overflow';
  455. $Text::Wrap::columns = 80;
  456. use ExtUtils::Constant qw (WriteConstants WriteMakefileSnippet autoload);
  457. use File::Compare;
  458.  
  459. sub usage {
  460.     warn "@_\n" if @_;
  461.     die <<EOFUSAGE;
  462. h2xs [OPTIONS ... ] [headerfile [extra_libraries]]
  463. version: $H2XS_VERSION
  464. OPTIONS:
  465.     -A, --omit-autoload   Omit all autoloading facilities (implies -c).
  466.     -B, --beta-version    Use beta \$VERSION of 0.00_01 (ignored if -v).
  467.     -C, --omit-changes    Omit creating the Changes file, add HISTORY heading
  468.                           to stub POD.
  469.     -F, --cpp-flags       Additional flags for C preprocessor/compile.
  470.     -M, --func-mask       Mask to select C functions/macros
  471.                           (default is select all).
  472.     -O, --overwrite-ok    Allow overwriting of a pre-existing extension directory.
  473.     -P, --omit-pod        Omit the stub POD section.
  474.     -X, --omit-XS         Omit the XS portion (implies both -c and -f).
  475.     -a, --gen-accessors   Generate get/set accessors for struct and union members                           (used with -x).
  476.     -b, --compat-version  Specify a perl version to be backwards compatibile with
  477.     -c, --omit-constant   Omit the constant() function and specialised AUTOLOAD
  478.                           from the XS file.
  479.     -d, --debugging       Turn on debugging messages.
  480.     -f, --force           Force creation of the extension even if the C header
  481.                           does not exist.
  482.     -g, --global          Include code for safely storing static data in the .xs file. 
  483.     -h, -?, --help        Display this help message
  484.     -k, --omit-const-func Omit 'const' attribute on function arguments
  485.                           (used with -x).
  486.     -m, --gen-tied-var    Generate tied variables for access to declared
  487.                           variables.
  488.     -n, --name            Specify a name to use for the extension (recommended).
  489.     -o, --opaque-re       Regular expression for \"opaque\" types.
  490.     -p, --remove-prefix   Specify a prefix which should be removed from the
  491.                           Perl function names.
  492.     -s, --const-subs      Create subroutines for specified macros.
  493.     -t, --default-type    Default type for autoloaded constants (default is IV)
  494.         --use-new-tests   Use Test::More in backward compatible modules
  495.         --use-old-tests   Use the module Test rather than Test::More
  496.         --skip-exporter   Do not export symbols
  497.         --skip-ppport     Do not use portability layer
  498.         --skip-autoloader Do not use the module C<AutoLoader>
  499.         --skip-strict     Do not use the pragma C<strict>
  500.         --skip-warnings   Do not use the pragma C<warnings>
  501.     -v, --version         Specify a version number for this extension.
  502.     -x, --autogen-xsubs   Autogenerate XSUBs using C::Scan.
  503.  
  504. extra_libraries
  505.          are any libraries that might be needed for loading the
  506.          extension, e.g. -lm would try to link in the math library.
  507. EOFUSAGE
  508. }
  509.  
  510. my ($opt_A,
  511.     $opt_B,
  512.     $opt_C,
  513.     $opt_F,
  514.     $opt_M,
  515.     $opt_O,
  516.     $opt_P,
  517.     $opt_X,
  518.     $opt_a,
  519.     $opt_c,
  520.     $opt_d,
  521.     $opt_f,
  522.     $opt_g,
  523.     $opt_h,
  524.     $opt_k,
  525.     $opt_m,
  526.     $opt_n,
  527.     $opt_o,
  528.     $opt_p,
  529.     $opt_s,
  530.     $opt_v,
  531.     $opt_x,
  532.     $opt_b,
  533.     $opt_t,
  534.     $new_test,
  535.     $old_test,
  536.     $skip_exporter,
  537.     $skip_ppport,
  538.     $skip_autoloader,
  539.     $skip_strict,
  540.     $skip_warnings,
  541.    );
  542.  
  543. Getopt::Long::Configure('bundling');
  544.  
  545. my %options = (
  546.                 'omit-autoload|A'    => \$opt_A,
  547.                 'beta-version|B'     => \$opt_B,
  548.                 'omit-changes|C'     => \$opt_C,
  549.                 'cpp-flags|F=s'      => \$opt_F,
  550.                 'func-mask|M=s'      => \$opt_M,
  551.                 'overwrite_ok|O'     => \$opt_O,
  552.                 'omit-pod|P'         => \$opt_P,
  553.                 'omit-XS|X'          => \$opt_X,
  554.                 'gen-accessors|a'    => \$opt_a,
  555.                 'compat-version|b=s' => \$opt_b,
  556.                 'omit-constant|c'    => \$opt_c,
  557.                 'debugging|d'        => \$opt_d,
  558.                 'force|f'            => \$opt_f,
  559.                 'global|g'           => \$opt_g,
  560.                 'help|h|?'           => \$opt_h,
  561.                 'omit-const-func|k'  => \$opt_k,
  562.                 'gen-tied-var|m'     => \$opt_m,
  563.                 'name|n=s'           => \$opt_n,
  564.                 'opaque-re|o=s'      => \$opt_o,
  565.                 'remove-prefix|p=s'  => \$opt_p,
  566.                 'const-subs|s=s'     => \$opt_s,
  567.                 'default-type|t=s'   => \$opt_t,
  568.                 'version|v=s'        => \$opt_v,
  569.                 'autogen-xsubs|x'    => \$opt_x,
  570.                 'use-new-tests'      => \$new_test,
  571.                 'use-old-tests'      => \$old_test,
  572.                 'skip-exporter'      => \$skip_exporter,
  573.                 'skip-ppport'        => \$skip_ppport,
  574.                 'skip-autoloader'    => \$skip_autoloader,
  575.                 'skip-warnings'      => \$skip_warnings,
  576.                 'skip-strict'        => \$skip_strict,
  577.               );
  578.  
  579. GetOptions(%options) || usage;
  580.  
  581. usage if $opt_h;
  582.  
  583. if( $opt_b ){
  584.     usage "You cannot use -b and -m at the same time.\n" if ($opt_b && $opt_m);
  585.     $opt_b =~ /^\d+\.\d+\.\d+/ ||
  586.     usage "You must provide the backwards compatibility version in X.Y.Z form. "
  587.           .  "(i.e. 5.5.0)\n";
  588.     my ($maj,$min,$sub) = split(/\./,$opt_b,3);
  589.     if ($maj < 5 || ($maj == 5 && $min < 6)) {
  590.         $compat_version =
  591.         $sub ? sprintf("%d.%03d%02d",$maj,$min,$sub) :
  592.                sprintf("%d.%03d",    $maj,$min);
  593.     } else {
  594.         $compat_version =
  595.         $sub ? sprintf("%d.%03d%03d",$maj,$min,$sub) :
  596.            sprintf("%d.%03d",    $maj,$min);
  597.     }
  598. } else {
  599.     my ($maj,$min,$sub) = $compat_version =~ /(\d+)\.(\d\d\d)(\d*)/;
  600.     $sub ||= 0;
  601.     warn sprintf <<'EOF', $maj,$min,$sub;
  602. Defaulting to backwards compatibility with perl %d.%d.%d
  603. If you intend this module to be compatible with earlier perl versions, please
  604. specify a minimum perl version with the -b option.
  605.  
  606. EOF
  607. }
  608.  
  609. if( $opt_B ){
  610.     $TEMPLATE_VERSION = '0.00_01';
  611. }
  612.  
  613. if( $opt_v ){
  614.     $TEMPLATE_VERSION = $opt_v;
  615.  
  616.     # check if it is numeric
  617.     my $temp_version = $TEMPLATE_VERSION;
  618.     my $beta_version = $temp_version =~ s/(\d)_(\d\d)/$1$2/;
  619.     my $notnum;
  620.     {
  621.         local $SIG{__WARN__} = sub { $notnum = 1 };
  622.         use warnings 'numeric';
  623.         $temp_version = 0+$temp_version;
  624.     }
  625.  
  626.     if ($notnum) {
  627.         my $module = $opt_n || 'Your::Module';
  628.         warn <<"EOF";
  629. You have specified a non-numeric version.  Unless you supply an
  630. appropriate VERSION class method, users may not be able to specify a
  631. minimum required version with C<use $module versionnum>.
  632.  
  633. EOF
  634.     }
  635.     else {
  636.         $opt_B = $beta_version;
  637.     }
  638. }
  639.  
  640. # -A implies -c.
  641. $skip_autoloader = $opt_c = 1 if $opt_A;
  642.  
  643. # -X implies -c and -f
  644. $opt_c = $opt_f = 1 if $opt_X;
  645.  
  646. $opt_t ||= 'IV';
  647.  
  648. my %const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s;
  649.  
  650. my $extralibs = '';
  651.  
  652. my @path_h;
  653.  
  654. while (my $arg = shift) {
  655.     if ($arg =~ /^-l/i) {
  656.         $extralibs = "$arg @ARGV";
  657.         last;
  658.     }
  659.     push(@path_h, $arg);
  660. }
  661.  
  662. usage "Must supply header file or module name\n"
  663.         unless (@path_h or $opt_n);
  664.  
  665. my $fmask;
  666. my $tmask;
  667.  
  668. $fmask = qr{$opt_M} if defined $opt_M;
  669. $tmask = qr{$opt_o} if defined $opt_o;
  670. my $tmask_all = $tmask && $opt_o eq '.';
  671.  
  672. if ($opt_x) {
  673.   eval {require C::Scan; 1}
  674.     or die <<EOD;
  675. C::Scan required if you use -x option.
  676. To install C::Scan, execute
  677.    perl -MCPAN -e "install C::Scan"
  678. EOD
  679.   unless ($tmask_all) {
  680.     $C::Scan::VERSION >= 0.70
  681.       or die <<EOD;
  682. C::Scan v. 0.70 or later required unless you use -o . option.
  683. You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
  684. To install C::Scan, execute
  685.    perl -MCPAN -e "install C::Scan"
  686. EOD
  687.   }
  688.   if (($opt_m || $opt_a) && $C::Scan::VERSION < 0.73) {
  689.     die <<EOD;
  690. C::Scan v. 0.73 or later required to use -m or -a options.
  691. You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
  692. To install C::Scan, execute
  693.    perl -MCPAN -e "install C::Scan"
  694. EOD
  695.   }
  696. }
  697. elsif ($opt_o or $opt_F) {
  698.   warn <<EOD if $opt_o;
  699. Option -o does not make sense without -x.
  700. EOD
  701.   warn <<EOD if $opt_F and $opt_X ;
  702. Option -F does not make sense with -X.
  703. EOD
  704. }
  705.  
  706. my @path_h_ini = @path_h;
  707. my ($name, %fullpath, %prefix, %seen_define, %prefixless, %const_names);
  708.  
  709. my $module = $opt_n;
  710.  
  711. if( @path_h ){
  712.     use File::Spec;
  713.     my @paths;
  714.     my $pre_sub_tri_graphs = 1;
  715.     if ($^O eq 'VMS') {  # Consider overrides of default location
  716.       # XXXX This is not equivalent to what the older version did:
  717.       #        it was looking at $hadsys header-file per header-file...
  718.       my($hadsys) = grep s!^sys/!!i , @path_h;
  719.       @paths = qw( Sys$Library VAXC$Include );
  720.       push @paths, ($hadsys ? 'GNU_CC_Include[vms]' : 'GNU_CC_Include[000000]');
  721.       push @paths, qw( DECC$Library_Include DECC$System_Include );
  722.     }
  723.     else {
  724.       @paths = (File::Spec->curdir(), $Config{usrinc},
  725.         (split ' ', $Config{locincpth}), '/usr/include');
  726.     }
  727.     foreach my $path_h (@path_h) {
  728.         $name ||= $path_h;
  729.     $module ||= do {
  730.       $name =~ s/\.h$//;
  731.       if ( $name !~ /::/ ) {
  732.     $name =~ s#^.*/##;
  733.     $name = "\u$name";
  734.       }
  735.       $name;
  736.     };
  737.  
  738.     if( $path_h =~ s#::#/#g && $opt_n ){
  739.     warn "Nesting of headerfile ignored with -n\n";
  740.     }
  741.     $path_h .= ".h" unless $path_h =~ /\.h$/;
  742.     my $fullpath = $path_h;
  743.     $path_h =~ s/,.*$// if $opt_x;
  744.     $fullpath{$path_h} = $fullpath;
  745.  
  746.     # Minor trickery: we can't chdir() before we processed the headers
  747.     # (so know the name of the extension), but the header may be in the
  748.     # extension directory...
  749.     my $tmp_path_h = $path_h;
  750.     my $rel_path_h = $path_h;
  751.     my @dirs = @paths;
  752.     if (not -f $path_h) {
  753.       my $found;
  754.       for my $dir (@paths) {
  755.     $found++, last
  756.       if -f ($path_h = File::Spec->catfile($dir, $tmp_path_h));
  757.       }
  758.       if ($found) {
  759.     $rel_path_h = $path_h;
  760.     $fullpath{$path_h} = $fullpath;
  761.       } else {
  762.     (my $epath = $module) =~ s,::,/,g;
  763.     $epath = File::Spec->catdir('ext', $epath) if -d 'ext';
  764.     $rel_path_h = File::Spec->catfile($epath, $tmp_path_h);
  765.     $path_h = $tmp_path_h;    # Used during -x
  766.     push @dirs, $epath;
  767.       }
  768.     }
  769.  
  770.     if (!$opt_c) {
  771.       die "Can't find $tmp_path_h in @dirs\n" 
  772.     if ( ! $opt_f && ! -f "$rel_path_h" );
  773.       # Scan the header file (we should deal with nested header files)
  774.       # Record the names of simple #define constants into const_names
  775.             # Function prototypes are processed below.
  776.       open(CH, "<$rel_path_h") || die "Can't open $rel_path_h: $!\n";
  777.     defines:
  778.       while (<CH>) {
  779.     if ($pre_sub_tri_graphs) {
  780.         # Preprocess all tri-graphs 
  781.         # including things stuck in quoted string constants.
  782.         s/\?\?=/#/g;                         # | ??=|  #|
  783.         s/\?\?\!/|/g;                        # | ??!|  ||
  784.         s/\?\?'/^/g;                         # | ??'|  ^|
  785.         s/\?\?\(/[/g;                        # | ??(|  [|
  786.         s/\?\?\)/]/g;                        # | ??)|  ]|
  787.         s/\?\?\-/~/g;                        # | ??-|  ~|
  788.         s/\?\?\//\\/g;                       # | ??/|  \|
  789.         s/\?\?</{/g;                         # | ??<|  {|
  790.         s/\?\?>/}/g;                         # | ??>|  }|
  791.     }
  792.     if (/^[ \t]*#[ \t]*define\s+([\$\w]+)\b(?!\()\s*(?=[^"\s])(.*)/) {
  793.         my $def = $1;
  794.         my $rest = $2;
  795.         $rest =~ s!/\*.*?(\*/|\n)|//.*!!g; # Remove comments
  796.         $rest =~ s/^\s+//;
  797.         $rest =~ s/\s+$//;
  798.         # Cannot do: (-1) and ((LHANDLE)3) are OK:
  799.         #print("Skip non-wordy $def => $rest\n"),
  800.         #  next defines if $rest =~ /[^\w\$]/;
  801.         if ($rest =~ /"/) {
  802.           print("Skip stringy $def => $rest\n") if $opt_d;
  803.           next defines;
  804.         }
  805.         print "Matched $_ ($def)\n" if $opt_d;
  806.         $seen_define{$def} = $rest;
  807.         $_ = $def;
  808.         next if /^_.*_h_*$/i; # special case, but for what?
  809.         if (defined $opt_p) {
  810.           if (!/^$opt_p(\d)/) {
  811.         ++$prefix{$_} if s/^$opt_p//;
  812.           }
  813.           else {
  814.         warn "can't remove $opt_p prefix from '$_'!\n";
  815.           }
  816.         }
  817.         $prefixless{$def} = $_;
  818.         if (!$fmask or /$fmask/) {
  819.         print "... Passes mask of -M.\n" if $opt_d and $fmask;
  820.         $const_names{$_}++;
  821.         }
  822.       }
  823.       }
  824.       close(CH);
  825.     }
  826.     }
  827. }
  828.  
  829. # Save current directory so that C::Scan can use it
  830. my $cwd = File::Spec->rel2abs( File::Spec->curdir );
  831.  
  832. my ($ext, $nested, @modparts, $modfname, $modpname);
  833. # As Ilya suggested, use a name that contains - and then it can't clash with
  834. # the names of any packages. A directory 'fallback' will clash with any
  835. # new pragmata down the fallback:: tree, but that seems unlikely.
  836. my $constscfname = 'const-c.inc';
  837. my $constsxsfname = 'const-xs.inc';
  838. my $fallbackdirname = 'fallback';
  839.  
  840. $ext = chdir 'ext' ? 'ext/' : '';
  841.  
  842. if( $module =~ /::/ ){
  843.     $nested = 1;
  844.     @modparts = split(/::/,$module);
  845.     $modfname = $modparts[-1];
  846.     $modpname = join('/',@modparts);
  847. }
  848. else {
  849.     $nested = 0;
  850.     @modparts = ();
  851.     $modfname = $modpname = $module;
  852. }
  853.  
  854.  
  855. if ($opt_O) {
  856.     warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
  857. }
  858. else {
  859.     die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
  860. }
  861. if( $nested ){
  862.     my $modpath = "";
  863.     foreach (@modparts){
  864.         -d "$modpath$_" || mkdir("$modpath$_", 0777);
  865.         $modpath .= "$_/";
  866.     }
  867. }
  868. -d "$modpname"   || mkdir($modpname, 0777);
  869. chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";
  870.  
  871. my %types_seen;
  872. my %std_types;
  873. my $fdecls = [];
  874. my $fdecls_parsed = [];
  875. my $typedef_rex;
  876. my %typedefs_pre;
  877. my %known_fnames;
  878. my %structs;
  879.  
  880. my @fnames;
  881. my @fnames_no_prefix;
  882. my %vdecl_hash;
  883. my @vdecls;
  884.  
  885. if( ! $opt_X ){  # use XS, unless it was disabled
  886.   unless ($skip_ppport) {
  887.     require Devel::PPPort;
  888.     warn "Writing $ext$modpname/ppport.h\n";
  889.     Devel::PPPort::WriteFile('ppport.h')
  890.         || die "Can't create $ext$modpname/ppport.h: $!\n";
  891.   }
  892.   open(XS, ">$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n";
  893.   if ($opt_x) {
  894.     warn "Scanning typemaps...\n";
  895.     get_typemap();
  896.     my @td;
  897.     my @good_td;
  898.     my $addflags = $opt_F || '';
  899.  
  900.     foreach my $filename (@path_h) {
  901.       my $c;
  902.       my $filter;
  903.  
  904.       if ($fullpath{$filename} =~ /,/) {
  905.     $filename = $`;
  906.     $filter = $';
  907.       }
  908.       warn "Scanning $filename for functions...\n";
  909.       my @styles = $Config{gccversion} ? qw(C++ C9X GNU) : qw(C++ C9X);
  910.       $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
  911.     'add_cppflags' => $addflags, 'c_styles' => \@styles;
  912.       $c->set('includeDirs' => ["$Config::Config{archlib}/CORE", $cwd]);
  913.  
  914.       push @$fdecls_parsed, @{ $c->get('parsed_fdecls') };
  915.       push(@$fdecls, @{$c->get('fdecls')});
  916.  
  917.       push @td, @{$c->get('typedefs_maybe')};
  918.       if ($opt_a) {
  919.     my $structs = $c->get('typedef_structs');
  920.     @structs{keys %$structs} = values %$structs;
  921.       }
  922.  
  923.       if ($opt_m) {
  924.     %vdecl_hash = %{ $c->get('vdecl_hash') };
  925.     @vdecls = sort keys %vdecl_hash;
  926.     for (local $_ = 0; $_ < @vdecls; ++$_) {
  927.       my $var = $vdecls[$_];
  928.       my($type, $post) = @{ $vdecl_hash{$var} };
  929.       if (defined $post) {
  930.         warn "Can't handle variable '$type $var $post', skipping.\n";
  931.         splice @vdecls, $_, 1;
  932.         redo;
  933.       }
  934.       $type = normalize_type($type);
  935.       $vdecl_hash{$var} = $type;
  936.     }
  937.       }
  938.  
  939.       unless ($tmask_all) {
  940.     warn "Scanning $filename for typedefs...\n";
  941.     my $td = $c->get('typedef_hash');
  942.     # eval {require 'dumpvar.pl'; ::dumpValue($td)} or warn $@ if $opt_d;
  943.     my @f_good_td = grep $td->{$_}[1] eq '', keys %$td;
  944.     push @good_td, @f_good_td;
  945.     @typedefs_pre{@f_good_td}  = map $_->[0], @$td{@f_good_td};
  946.       }
  947.     }
  948.     { local $" = '|';
  949.       $typedef_rex = qr(\b(?<!struct )(?:@good_td)\b) if @good_td;
  950.     }
  951.     %known_fnames = map @$_[1,3], @$fdecls_parsed; # [1,3] is NAME, FULLTEXT
  952.     if ($fmask) {
  953.       my @good;
  954.       for my $i (0..$#$fdecls_parsed) {
  955.     next unless $fdecls_parsed->[$i][1] =~ /$fmask/; # [1] is NAME
  956.     push @good, $i;
  957.     print "... Function $fdecls_parsed->[$i][1] passes -M mask.\n"
  958.       if $opt_d;
  959.       }
  960.       $fdecls = [@$fdecls[@good]];
  961.       $fdecls_parsed = [@$fdecls_parsed[@good]];
  962.     }
  963.     @fnames = sort map $_->[1], @$fdecls_parsed; # 1 is NAME
  964.     # Sort declarations:
  965.     {
  966.       my %h = map( ($_->[1], $_), @$fdecls_parsed);
  967.       $fdecls_parsed = [ @h{@fnames} ];
  968.     }
  969.     @fnames_no_prefix = @fnames;
  970.     @fnames_no_prefix
  971.       = sort map { ++$prefix{$_} if s/^$opt_p(?!\d)//; $_ } @fnames_no_prefix
  972.          if defined $opt_p;
  973.     # Remove macros which expand to typedefs
  974.     print "Typedefs are @td.\n" if $opt_d;
  975.     my %td = map {($_, $_)} @td;
  976.     # Add some other possible but meaningless values for macros
  977.     for my $k (qw(char double float int long short unsigned signed void)) {
  978.       $td{"$_$k"} = "$_$k" for ('', 'signed ', 'unsigned ');
  979.     }
  980.     # eval {require 'dumpvar.pl'; ::dumpValue( [\@td, \%td] ); 1} or warn $@;
  981.     my $n = 0;
  982.     my %bad_macs;
  983.     while (keys %td > $n) {
  984.       $n = keys %td;
  985.       my ($k, $v);
  986.       while (($k, $v) = each %seen_define) {
  987.     # print("found '$k'=>'$v'\n"), 
  988.     $bad_macs{$k} = $td{$k} = $td{$v} if exists $td{$v};
  989.       }
  990.     }
  991.     # Now %bad_macs contains names of bad macros
  992.     for my $k (keys %bad_macs) {
  993.       delete $const_names{$prefixless{$k}};
  994.       print "Ignoring macro $k which expands to a typedef name '$bad_macs{$k}'\n" if $opt_d;
  995.     }
  996.   }
  997. }
  998. my @const_names = sort keys %const_names;
  999.  
  1000. open(PM, ">$modfname.pm") || die "Can't create $ext$modpname/$modfname.pm: $!\n";
  1001.  
  1002. $" = "\n\t";
  1003. warn "Writing $ext$modpname/$modfname.pm\n";
  1004.  
  1005. print PM <<"END";
  1006. package $module;
  1007.  
  1008. use $compat_version;
  1009. END
  1010.  
  1011. print PM <<"END" unless $skip_strict;
  1012. use strict;
  1013. END
  1014.  
  1015. print PM "use warnings;\n" unless $skip_warnings or $compat_version < 5.006;
  1016.  
  1017. unless( $opt_X || $opt_c || $opt_A ){
  1018.     # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and
  1019.     # will want Carp.
  1020.     print PM <<'END';
  1021. use Carp;
  1022. END
  1023. }
  1024.  
  1025. print PM <<'END' unless $skip_exporter;
  1026.  
  1027. require Exporter;
  1028. END
  1029.  
  1030. my $use_Dyna = (not $opt_X and $compat_version < 5.006);
  1031. print PM <<"END" if $use_Dyna;  # use DynaLoader, unless XS was disabled
  1032. require DynaLoader;
  1033. END
  1034.  
  1035.  
  1036. # Are we using AutoLoader or not?
  1037. unless ($skip_autoloader) { # no autoloader whatsoever.
  1038.     unless ($opt_c) { # we're doing the AUTOLOAD
  1039.         print PM "use AutoLoader;\n";
  1040.     }
  1041.     else {
  1042.         print PM "use AutoLoader qw(AUTOLOAD);\n"
  1043.     }
  1044. }
  1045.  
  1046. if ( $compat_version < 5.006 ) {
  1047.     my $vars = '$VERSION @ISA';
  1048.     $vars .= ' @EXPORT @EXPORT_OK %EXPORT_TAGS' unless $skip_exporter;
  1049.     $vars .= ' $AUTOLOAD' unless $opt_X || $opt_c || $opt_A;
  1050.     $vars .= ' $XS_VERSION' if $opt_B && !$opt_X;
  1051.     print PM "use vars qw($vars);";
  1052. }
  1053.  
  1054. # Determine @ISA.
  1055. my @modISA;
  1056. push @modISA, 'Exporter'    unless $skip_exporter; 
  1057. push @modISA, 'DynaLoader'     if $use_Dyna;  # no XS
  1058. my $myISA = "our \@ISA = qw(@modISA);";
  1059. $myISA =~ s/^our // if $compat_version < 5.006;
  1060.  
  1061. print PM "\n$myISA\n\n";
  1062.  
  1063. my @exported_names = (@const_names, @fnames_no_prefix, map '$'.$_, @vdecls);
  1064.  
  1065. my $tmp='';
  1066. $tmp .= <<"END" unless $skip_exporter;
  1067. # Items to export into callers namespace by default. Note: do not export
  1068. # names by default without a very good reason. Use EXPORT_OK instead.
  1069. # Do not simply export all your public functions/methods/constants.
  1070.  
  1071. # This allows declaration    use $module ':all';
  1072. # If you do not need this, moving things directly into \@EXPORT or \@EXPORT_OK
  1073. # will save memory.
  1074. our %EXPORT_TAGS = ( 'all' => [ qw(
  1075.     @exported_names
  1076. ) ] );
  1077.  
  1078. our \@EXPORT_OK = ( \@{ \$EXPORT_TAGS{'all'} } );
  1079.  
  1080. our \@EXPORT = qw(
  1081.     @const_names
  1082. );
  1083.  
  1084. END
  1085.  
  1086. $tmp .= "our \$VERSION = '$TEMPLATE_VERSION';\n";
  1087. if ($opt_B) {
  1088.     $tmp .= "our \$XS_VERSION = \$VERSION;\n" unless $opt_X;
  1089.     $tmp .= "\$VERSION = eval \$VERSION;  # see L<perlmodstyle>\n";
  1090. }
  1091. $tmp .= "\n";
  1092.  
  1093. $tmp =~ s/^our //mg if $compat_version < 5.006;
  1094. print PM $tmp;
  1095.  
  1096. if (@vdecls) {
  1097.     printf PM "our(@{[ join ', ', map '$'.$_, @vdecls ]});\n\n";
  1098. }
  1099.  
  1100.  
  1101. print PM autoload ($module, $compat_version) unless $opt_c or $opt_X;
  1102.  
  1103. if( ! $opt_X ){ # print bootstrap, unless XS is disabled
  1104.   if ($use_Dyna) {
  1105.     $tmp = <<"END";
  1106. bootstrap $module \$VERSION;
  1107. END
  1108.   } else {
  1109.     $tmp = <<"END";
  1110. require XSLoader;
  1111. XSLoader::load('$module', \$VERSION);
  1112. END
  1113.   }
  1114.   $tmp =~ s:\$VERSION:\$XS_VERSION:g if $opt_B;
  1115.   print PM $tmp;
  1116. }
  1117.  
  1118. # tying the variables can happen only after bootstrap
  1119. if (@vdecls) {
  1120.     printf PM <<END;
  1121. {
  1122. @{[ join "\n", map "    _tievar_$_(\$$_);", @vdecls ]}
  1123. }
  1124.  
  1125. END
  1126. }
  1127.  
  1128. my $after;
  1129. if( $opt_P ){ # if POD is disabled
  1130.     $after = '__END__';
  1131. }
  1132. else {
  1133.     $after = '=cut';
  1134. }
  1135.  
  1136. print PM <<"END";
  1137.  
  1138. # Preloaded methods go here.
  1139. END
  1140.  
  1141. print PM <<"END" unless $opt_A;
  1142.  
  1143. # Autoload methods go after $after, and are processed by the autosplit program.
  1144. END
  1145.  
  1146. print PM <<"END";
  1147.  
  1148. 1;
  1149. __END__
  1150. END
  1151.  
  1152. my ($email,$author);
  1153.  
  1154. eval {
  1155.        my $username;
  1156.        ($username,$author) = (getpwuid($>))[0,6];
  1157.        if (defined $username && defined $author) {
  1158.        $author =~ s/,.*$//; # in case of sub fields
  1159.        my $domain = $Config{'mydomain'};
  1160.        $domain =~ s/^\.//;
  1161.        $email = "$username\@$domain";
  1162.        }
  1163.      };
  1164.  
  1165. $author ||= "A. U. Thor";
  1166. $email  ||= 'a.u.thor@a.galaxy.far.far.away';
  1167.  
  1168. my $revhist = '';
  1169. $revhist = <<EOT if $opt_C;
  1170. #
  1171. #=head1 HISTORY
  1172. #
  1173. #=over 8
  1174. #
  1175. #=item $TEMPLATE_VERSION
  1176. #
  1177. #Original version; created by h2xs $H2XS_VERSION with options
  1178. #
  1179. #  @ARGS
  1180. #
  1181. #=back
  1182. #
  1183. EOT
  1184.  
  1185. my $exp_doc = $skip_exporter ? '' : <<EOD;
  1186. #
  1187. #=head2 EXPORT
  1188. #
  1189. #None by default.
  1190. #
  1191. EOD
  1192.  
  1193. if (@const_names and not $opt_P) {
  1194.   $exp_doc .= <<EOD unless $skip_exporter;
  1195. #=head2 Exportable constants
  1196. #
  1197. #  @{[join "\n  ", @const_names]}
  1198. #
  1199. EOD
  1200. }
  1201.  
  1202. if (defined $fdecls and @$fdecls and not $opt_P) {
  1203.   $exp_doc .= <<EOD unless $skip_exporter;
  1204. #=head2 Exportable functions
  1205. #
  1206. EOD
  1207.  
  1208. #  $exp_doc .= <<EOD if $opt_p;
  1209. #When accessing these functions from Perl, prefix C<$opt_p> should be removed.
  1210. #
  1211. #EOD
  1212.   $exp_doc .= <<EOD unless $skip_exporter;
  1213. #  @{[join "\n  ", @known_fnames{@fnames}]}
  1214. #
  1215. EOD
  1216. }
  1217.  
  1218. my $meth_doc = '';
  1219.  
  1220. if ($opt_x && $opt_a) {
  1221.   my($name, $struct);
  1222.   $meth_doc .= accessor_docs($name, $struct)
  1223.     while ($name, $struct) = each %structs;
  1224. }
  1225.  
  1226. my $pod = <<"END" unless $opt_P;
  1227. ## Below is stub documentation for your module. You'd better edit it!
  1228. #
  1229. #=head1 NAME
  1230. #
  1231. #$module - Perl extension for blah blah blah
  1232. #
  1233. #=head1 SYNOPSIS
  1234. #
  1235. #  use $module;
  1236. #  blah blah blah
  1237. #
  1238. #=head1 ABSTRACT
  1239. #
  1240. #  This should be the abstract for $module.
  1241. #  The abstract is used when making PPD (Perl Package Description) files.
  1242. #  If you don't want an ABSTRACT you should also edit Makefile.PL to
  1243. #  remove the ABSTRACT_FROM option.
  1244. #
  1245. #=head1 DESCRIPTION
  1246. #
  1247. #Stub documentation for $module, created by h2xs. It looks like the
  1248. #author of the extension was negligent enough to leave the stub
  1249. #unedited.
  1250. #
  1251. #Blah blah blah.
  1252. $exp_doc$meth_doc$revhist
  1253. #
  1254. #=head1 SEE ALSO
  1255. #
  1256. #Mention other useful documentation such as the documentation of
  1257. #related modules or operating system documentation (such as man pages
  1258. #in UNIX), or any relevant external documentation such as RFCs or
  1259. #standards.
  1260. #
  1261. #If you have a mailing list set up for your module, mention it here.
  1262. #
  1263. #If you have a web site set up for your module, mention it here.
  1264. #
  1265. #=head1 AUTHOR
  1266. #
  1267. #$author, E<lt>${email}E<gt>
  1268. #
  1269. #=head1 COPYRIGHT AND LICENSE
  1270. #
  1271. #Copyright ${\(1900 + (localtime) [5])} by $author
  1272. #
  1273. #This library is free software; you can redistribute it and/or modify
  1274. #it under the same terms as Perl itself. 
  1275. #
  1276. #=cut
  1277. END
  1278.  
  1279. $pod =~ s/^\#//gm unless $opt_P;
  1280. print PM $pod unless $opt_P;
  1281.  
  1282. close PM;
  1283.  
  1284.  
  1285. if( ! $opt_X ){ # print XS, unless it is disabled
  1286. warn "Writing $ext$modpname/$modfname.xs\n";
  1287.  
  1288. print XS <<"END";
  1289. #include "EXTERN.h"
  1290. #include "perl.h"
  1291. #include "XSUB.h"
  1292.  
  1293. END
  1294.  
  1295. print XS <<"END" unless $skip_ppport;
  1296. #include "ppport.h"
  1297.  
  1298. END
  1299.  
  1300. if( @path_h ){
  1301.     foreach my $path_h (@path_h_ini) {
  1302.     my($h) = $path_h;
  1303.     $h =~ s#^/usr/include/##;
  1304.     if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; }
  1305.         print XS qq{#include <$h>\n};
  1306.     }
  1307.     print XS "\n";
  1308. }
  1309.  
  1310. print XS <<"END" if $opt_g;
  1311.  
  1312. /* Global Data */
  1313.  
  1314. #define MY_CXT_KEY "${module}::_guts" XS_VERSION
  1315.  
  1316. typedef struct {
  1317.     /* Put Global Data in here */
  1318.     int dummy;        /* you can access this elsewhere as MY_CXT.dummy */
  1319. } my_cxt_t;
  1320.  
  1321. START_MY_CXT
  1322.  
  1323. END
  1324.  
  1325. my %pointer_typedefs;
  1326. my %struct_typedefs;
  1327.  
  1328. sub td_is_pointer {
  1329.   my $type = shift;
  1330.   my $out = $pointer_typedefs{$type};
  1331.   return $out if defined $out;
  1332.   my $otype = $type;
  1333.   $out = ($type =~ /\*$/);
  1334.   # This converts only the guys which do not have trailing part in the typedef
  1335.   if (not $out
  1336.       and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  1337.     $type = normalize_type($type);
  1338.     print "Is-Pointer: Type mutation via typedefs: $otype ==> $type\n"
  1339.       if $opt_d;
  1340.     $out = td_is_pointer($type);
  1341.   }
  1342.   return ($pointer_typedefs{$otype} = $out);
  1343. }
  1344.  
  1345. sub td_is_struct {
  1346.   my $type = shift;
  1347.   my $out = $struct_typedefs{$type};
  1348.   return $out if defined $out;
  1349.   my $otype = $type;
  1350.   $out = ($type =~ /^(struct|union)\b/) && !td_is_pointer($type);
  1351.   # This converts only the guys which do not have trailing part in the typedef
  1352.   if (not $out
  1353.       and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  1354.     $type = normalize_type($type);
  1355.     print "Is-Struct: Type mutation via typedefs: $otype ==> $type\n"
  1356.       if $opt_d;
  1357.     $out = td_is_struct($type);
  1358.   }
  1359.   return ($struct_typedefs{$otype} = $out);
  1360. }
  1361.  
  1362. print_tievar_subs(\*XS, $_, $vdecl_hash{$_}) for @vdecls;
  1363.  
  1364. if( ! $opt_c ) {
  1365.   # We write the "sample" files used when this module is built by perl without
  1366.   # ExtUtils::Constant.
  1367.   # h2xs will later check that these are the same as those generated by the
  1368.   # code embedded into Makefile.PL
  1369.   unless (-d $fallbackdirname) {
  1370.     mkdir "$fallbackdirname" or die "Cannot mkdir $fallbackdirname: $!\n";
  1371.   }
  1372.   warn "Writing $ext$modpname/$fallbackdirname/$constscfname\n";
  1373.   warn "Writing $ext$modpname/$fallbackdirname/$constsxsfname\n";
  1374.   my $cfallback = File::Spec->catfile($fallbackdirname, $constscfname);
  1375.   my $xsfallback = File::Spec->catfile($fallbackdirname, $constsxsfname);
  1376.   WriteConstants ( C_FILE =>       $cfallback,
  1377.                    XS_FILE =>      $xsfallback,
  1378.                    DEFAULT_TYPE => $opt_t,
  1379.                    NAME =>         $module,
  1380.                    NAMES =>        \@const_names,
  1381.                  );
  1382.   print XS "#include \"$constscfname\"\n";
  1383. }
  1384.  
  1385.  
  1386. my $prefix = defined $opt_p ? "PREFIX = $opt_p" : '';
  1387.  
  1388. # Now switch from C to XS by issuing the first MODULE declaration:
  1389. print XS <<"END";
  1390.  
  1391. MODULE = $module        PACKAGE = $module        $prefix
  1392.  
  1393. END
  1394.  
  1395. # If a constant() function was #included then output a corresponding
  1396. # XS declaration:
  1397. print XS "INCLUDE: $constsxsfname\n" unless $opt_c;
  1398.  
  1399. print XS <<"END" if $opt_g;
  1400.  
  1401. BOOT:
  1402. {
  1403.     MY_CXT_INIT;
  1404.     /* If any of the fields in the my_cxt_t struct need
  1405.        to be initialised, do it here.
  1406.      */
  1407. }
  1408.  
  1409. END
  1410.  
  1411. foreach (sort keys %const_xsub) {
  1412.     print XS <<"END";
  1413. char *
  1414. $_()
  1415.  
  1416.     CODE:
  1417. #ifdef $_
  1418.     RETVAL = $_;
  1419. #else
  1420.     croak("Your vendor has not defined the $module macro $_");
  1421. #endif
  1422.  
  1423.     OUTPUT:
  1424.     RETVAL
  1425.  
  1426. END
  1427. }
  1428.  
  1429. my %seen_decl;
  1430. my %typemap;
  1431.  
  1432. sub print_decl {
  1433.   my $fh = shift;
  1434.   my $decl = shift;
  1435.   my ($type, $name, $args) = @$decl;
  1436.   return if $seen_decl{$name}++; # Need to do the same for docs as well?
  1437.  
  1438.   my @argnames = map {$_->[1]} @$args;
  1439.   my @argtypes = map { normalize_type( $_->[0], 1 ) } @$args;
  1440.   if ($opt_k) {
  1441.     s/^\s*const\b\s*// for @argtypes;
  1442.   }
  1443.   my @argarrays = map { $_->[4] || '' } @$args;
  1444.   my $numargs = @$args;
  1445.   if ($numargs and $argtypes[-1] eq '...') {
  1446.     $numargs--;
  1447.     $argnames[-1] = '...';
  1448.   }
  1449.   local $" = ', ';
  1450.   $type = normalize_type($type, 1);
  1451.  
  1452.   print $fh <<"EOP";
  1453.  
  1454. $type
  1455. $name(@argnames)
  1456. EOP
  1457.  
  1458.   for my $arg (0 .. $numargs - 1) {
  1459.     print $fh <<"EOP";
  1460.     $argtypes[$arg]    $argnames[$arg]$argarrays[$arg]
  1461. EOP
  1462.   }
  1463. }
  1464.  
  1465. sub print_tievar_subs {
  1466.   my($fh, $name, $type) = @_;
  1467.   print $fh <<END;
  1468. I32
  1469. _get_$name(IV index, SV *sv) {
  1470.     dSP;
  1471.     PUSHMARK(SP);
  1472.     XPUSHs(sv);
  1473.     PUTBACK;
  1474.     (void)call_pv("$module\::_get_$name", G_DISCARD);
  1475.     return (I32)0;
  1476. }
  1477.  
  1478. I32
  1479. _set_$name(IV index, SV *sv) {
  1480.     dSP;
  1481.     PUSHMARK(SP);
  1482.     XPUSHs(sv);
  1483.     PUTBACK;
  1484.     (void)call_pv("$module\::_set_$name", G_DISCARD);
  1485.     return (I32)0;
  1486. }
  1487.  
  1488. END
  1489. }
  1490.  
  1491. sub print_tievar_xsubs {
  1492.   my($fh, $name, $type) = @_;
  1493.   print $fh <<END;
  1494. void
  1495. _tievar_$name(sv)
  1496.     SV* sv
  1497.     PREINIT:
  1498.     struct ufuncs uf;
  1499.     CODE:
  1500.     uf.uf_val = &_get_$name;
  1501.     uf.uf_set = &_set_$name;
  1502.     uf.uf_index = (IV)&_get_$name;
  1503.     sv_magic(sv, 0, 'U', (char*)&uf, sizeof(uf));
  1504.  
  1505. void
  1506. _get_$name(THIS)
  1507.     $type THIS = NO_INIT
  1508.     CODE:
  1509.     THIS = $name;
  1510.     OUTPUT:
  1511.     SETMAGIC: DISABLE
  1512.     THIS
  1513.  
  1514. void
  1515. _set_$name(THIS)
  1516.     $type THIS
  1517.     CODE:
  1518.     $name = THIS;
  1519.  
  1520. END
  1521. }
  1522.  
  1523. sub print_accessors {
  1524.   my($fh, $name, $struct) = @_;
  1525.   return unless defined $struct && $name !~ /\s|_ANON/;
  1526.   $name = normalize_type($name);
  1527.   my $ptrname = normalize_type("$name *");
  1528.   print $fh <<"EOF";
  1529.  
  1530. MODULE = $module        PACKAGE = ${name}        $prefix
  1531.  
  1532. $name *
  1533. _to_ptr(THIS)
  1534.     $name THIS = NO_INIT
  1535.     PROTOTYPE: \$
  1536.     CODE:
  1537.     if (sv_derived_from(ST(0), "$name")) {
  1538.         STRLEN len;
  1539.         char *s = SvPV((SV*)SvRV(ST(0)), len);
  1540.         if (len != sizeof(THIS))
  1541.         croak("Size \%d of packed data != expected \%d",
  1542.             len, sizeof(THIS));
  1543.         RETVAL = ($name *)s;
  1544.     }   
  1545.     else
  1546.         croak("THIS is not of type $name");
  1547.     OUTPUT:
  1548.     RETVAL
  1549.  
  1550. $name
  1551. new(CLASS)
  1552.     char *CLASS = NO_INIT
  1553.     PROTOTYPE: \$
  1554.     CODE:
  1555.     Zero((void*)&RETVAL, sizeof(RETVAL), char);
  1556.     OUTPUT:
  1557.     RETVAL
  1558.  
  1559. MODULE = $module        PACKAGE = ${name}Ptr        $prefix
  1560.  
  1561. EOF
  1562.   my @items = @$struct;
  1563.   while (@items) {
  1564.     my $item = shift @items;
  1565.     if ($item->[0] =~ /_ANON/) {
  1566.       if (defined $item->[2]) {
  1567.     push @items, map [
  1568.       @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]",
  1569.     ], @{ $structs{$item->[0]} };
  1570.       } else {
  1571.     push @items, @{ $structs{$item->[0]} };
  1572.       }
  1573.     } else {
  1574.       my $type = normalize_type($item->[0]);
  1575.       my $ttype = $structs{$type} ? normalize_type("$type *") : $type;
  1576.       print $fh <<"EOF";
  1577. $ttype
  1578. $item->[2](THIS, __value = NO_INIT)
  1579.     $ptrname THIS
  1580.     $type __value
  1581.     PROTOTYPE: \$;\$
  1582.     CODE:
  1583.     if (items > 1)
  1584.         THIS->$item->[-1] = __value;
  1585.     RETVAL = @{[
  1586.         $type eq $ttype ? "THIS->$item->[-1]" : "&(THIS->$item->[-1])"
  1587.     ]};
  1588.     OUTPUT:
  1589.     RETVAL
  1590.  
  1591. EOF
  1592.     }
  1593.   }
  1594. }
  1595.  
  1596. sub accessor_docs {
  1597.   my($name, $struct) = @_;
  1598.   return unless defined $struct && $name !~ /\s|_ANON/;
  1599.   $name = normalize_type($name);
  1600.   my $ptrname = $name . 'Ptr';
  1601.   my @items = @$struct;
  1602.   my @list;
  1603.   while (@items) {
  1604.     my $item = shift @items;
  1605.     if ($item->[0] =~ /_ANON/) {
  1606.       if (defined $item->[2]) {
  1607.     push @items, map [
  1608.       @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]",
  1609.     ], @{ $structs{$item->[0]} };
  1610.       } else {
  1611.     push @items, @{ $structs{$item->[0]} };
  1612.       }
  1613.     } else {
  1614.       push @list, $item->[2];
  1615.     }
  1616.   }
  1617.   my $methods = (join '(...)>, C<', @list) . '(...)';
  1618.  
  1619.   my $pod = <<"EOF";
  1620. #
  1621. #=head2 Object and class methods for C<$name>/C<$ptrname>
  1622. #
  1623. #The principal Perl representation of a C object of type C<$name> is an
  1624. #object of class C<$ptrname> which is a reference to an integer
  1625. #representation of a C pointer.  To create such an object, one may use
  1626. #a combination
  1627. #
  1628. #  my \$buffer = $name->new();
  1629. #  my \$obj = \$buffer->_to_ptr();
  1630. #
  1631. #This exersizes the following two methods, and an additional class
  1632. #C<$name>, the internal representation of which is a reference to a
  1633. #packed string with the C structure.  Keep in mind that \$buffer should
  1634. #better survive longer than \$obj.
  1635. #
  1636. #=over
  1637. #
  1638. #=item C<\$object_of_type_$name-E<gt>_to_ptr()>
  1639. #
  1640. #Converts an object of type C<$name> to an object of type C<$ptrname>.
  1641. #
  1642. #=item C<$name-E<gt>new()>
  1643. #
  1644. #Creates an empty object of type C<$name>.  The corresponding packed
  1645. #string is zeroed out.
  1646. #
  1647. #=item C<$methods>
  1648. #
  1649. #return the current value of the corresponding element if called
  1650. #without additional arguments.  Set the element to the supplied value
  1651. #(and return the new value) if called with an additional argument.
  1652. #
  1653. #Applicable to objects of type C<$ptrname>.
  1654. #
  1655. #=back
  1656. #
  1657. EOF
  1658.   $pod =~ s/^\#//gm;
  1659.   return $pod;
  1660. }
  1661.  
  1662. # Should be called before any actual call to normalize_type().
  1663. sub get_typemap {
  1664.   # We do not want to read ./typemap by obvios reasons.
  1665.   my @tm =  qw(../../../typemap ../../typemap ../typemap);
  1666.   my $stdtypemap =  "$Config::Config{privlib}/ExtUtils/typemap";
  1667.   unshift @tm, $stdtypemap;
  1668.   my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
  1669.  
  1670.   # Start with useful default values
  1671.   $typemap{float} = 'T_NV';
  1672.  
  1673.   foreach my $typemap (@tm) {
  1674.     next unless -e $typemap ;
  1675.     # skip directories, binary files etc.
  1676.     warn " Scanning $typemap\n";
  1677.     warn("Warning: ignoring non-text typemap file '$typemap'\n"), next 
  1678.       unless -T $typemap ;
  1679.     open(TYPEMAP, $typemap) 
  1680.       or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
  1681.     my $mode = 'Typemap';
  1682.     while (<TYPEMAP>) {
  1683.       next if /^\s*\#/;
  1684.       if (/^INPUT\s*$/)   { $mode = 'Input'; next; }
  1685.       elsif (/^OUTPUT\s*$/)  { $mode = 'Output'; next; }
  1686.       elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; }
  1687.       elsif ($mode eq 'Typemap') {
  1688.     next if /^\s*($|\#)/ ;
  1689.     my ($type, $image);
  1690.     if ( ($type, $image) =
  1691.          /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o
  1692.          # This may reference undefined functions:
  1693.          and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) {
  1694.       $typemap{normalize_type($type)} = $image;
  1695.     }
  1696.       }
  1697.     }
  1698.     close(TYPEMAP) or die "Cannot close $typemap: $!";
  1699.   }
  1700.   %std_types = %types_seen;
  1701.   %types_seen = ();
  1702. }
  1703.  
  1704.  
  1705. sub normalize_type {        # Second arg: do not strip const's before \*
  1706.   my $type = shift;
  1707.   my $do_keep_deep_const = shift;
  1708.   # If $do_keep_deep_const this is heuristical only
  1709.   my $keep_deep_const = ($do_keep_deep_const ? '\b(?![^(,)]*\*)' : '');
  1710.   my $ignore_mods 
  1711.     = "(?:\\b(?:(?:__const__|const)$keep_deep_const|static|inline|__inline__)\\b\\s*)*";
  1712.   if ($do_keep_deep_const) {    # Keep different compiled /RExen/o separately!
  1713.     $type =~ s/$ignore_mods//go;
  1714.   }
  1715.   else {
  1716.     $type =~ s/$ignore_mods//go;
  1717.   }
  1718.   $type =~ s/([^\s\w])/ $1 /g;
  1719.   $type =~ s/\s+$//;
  1720.   $type =~ s/^\s+//;
  1721.   $type =~ s/\s+/ /g;
  1722.   $type =~ s/\* (?=\*)/*/g;
  1723.   $type =~ s/\. \. \./.../g;
  1724.   $type =~ s/ ,/,/g;
  1725.   $types_seen{$type}++ 
  1726.     unless $type eq '...' or $type eq 'void' or $std_types{$type};
  1727.   $type;
  1728. }
  1729.  
  1730. my $need_opaque;
  1731.  
  1732. sub assign_typemap_entry {
  1733.   my $type = shift;
  1734.   my $otype = $type;
  1735.   my $entry;
  1736.   if ($tmask and $type =~ /$tmask/) {
  1737.     print "Type $type matches -o mask\n" if $opt_d;
  1738.     $entry = (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
  1739.   }
  1740.   elsif ($typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  1741.     $type = normalize_type $type;
  1742.     print "Type mutation via typedefs: $otype ==> $type\n" if $opt_d;
  1743.     $entry = assign_typemap_entry($type);
  1744.   }
  1745.   # XXX good do better if our UV happens to be long long
  1746.   return "T_NV" if $type =~ /^(unsigned\s+)?long\s+(long|double)\z/;
  1747.   $entry ||= $typemap{$otype}
  1748.     || (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
  1749.   $typemap{$otype} = $entry;
  1750.   $need_opaque = 1 if $entry eq "T_OPAQUE_STRUCT";
  1751.   return $entry;
  1752. }
  1753.  
  1754. for (@vdecls) {
  1755.   print_tievar_xsubs(\*XS, $_, $vdecl_hash{$_});
  1756. }
  1757.  
  1758. if ($opt_x) {
  1759.   for my $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) }
  1760.   if ($opt_a) {
  1761.     while (my($name, $struct) = each %structs) {
  1762.       print_accessors(\*XS, $name, $struct);
  1763.     }
  1764.   }
  1765. }
  1766.  
  1767. close XS;
  1768.  
  1769. if (%types_seen) {
  1770.   my $type;
  1771.   warn "Writing $ext$modpname/typemap\n";
  1772.   open TM, ">typemap" or die "Cannot open typemap file for write: $!";
  1773.  
  1774.   for $type (sort keys %types_seen) {
  1775.     my $entry = assign_typemap_entry $type;
  1776.     print TM $type, "\t" x (5 - int((length $type)/8)), "\t$entry\n"
  1777.   }
  1778.  
  1779.   print TM <<'EOP' if $need_opaque; # Older Perls do not have correct entry
  1780. #############################################################################
  1781. INPUT
  1782. T_OPAQUE_STRUCT
  1783.     if (sv_derived_from($arg, \"${ntype}\")) {
  1784.         STRLEN len;
  1785.         char  *s = SvPV((SV*)SvRV($arg), len);
  1786.  
  1787.         if (len != sizeof($var))
  1788.         croak(\"Size %d of packed data != expected %d\",
  1789.             len, sizeof($var));
  1790.         $var = *($type *)s;
  1791.     }
  1792.     else
  1793.         croak(\"$var is not of type ${ntype}\")
  1794. #############################################################################
  1795. OUTPUT
  1796. T_OPAQUE_STRUCT
  1797.     sv_setref_pvn($arg, \"${ntype}\", (char *)&$var, sizeof($var));
  1798. EOP
  1799.  
  1800.   close TM or die "Cannot close typemap file for write: $!";
  1801. }
  1802.  
  1803. } # if( ! $opt_X )
  1804.  
  1805. warn "Writing $ext$modpname/Makefile.PL\n";
  1806. open(PL, ">Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n";
  1807.  
  1808. my $prereq_pm;
  1809.  
  1810. if ( $compat_version < 5.00702 and $new_test )
  1811. {
  1812.   $prereq_pm = q%'Test::More'  =>  0%;
  1813. }
  1814. else
  1815. {
  1816.   $prereq_pm = '';
  1817. }
  1818.  
  1819. print PL <<"END";
  1820. use $compat_version;
  1821. use ExtUtils::MakeMaker;
  1822. # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  1823. # the contents of the Makefile that is written.
  1824. WriteMakefile(
  1825.     'NAME'        => '$module',
  1826.     'VERSION_FROM'    => '$modfname.pm', # finds \$VERSION
  1827.     'PREREQ_PM'        => {$prereq_pm}, # e.g., Module::Name => 1.1
  1828.     (\$] >= 5.005 ?    ## Add these new keywords supported since 5.005
  1829.       (ABSTRACT_FROM => '$modfname.pm', # retrieve abstract from module
  1830.        AUTHOR     => '$author <$email>') : ()),
  1831. END
  1832. if (!$opt_X) { # print C stuff, unless XS is disabled
  1833.   $opt_F = '' unless defined $opt_F;
  1834.   my $I = (((glob '*.h') || (glob '*.hh')) ? '-I.' : '');
  1835.   my $Ihelp = ($I ? '-I. ' : '');
  1836.   my $Icomment = ($I ? '' : <<EOC);
  1837.     # Insert -I. if you add *.h files later:
  1838. EOC
  1839.  
  1840.   print PL <<END;
  1841.     'LIBS'        => ['$extralibs'], # e.g., '-lm'
  1842.     'DEFINE'        => '$opt_F', # e.g., '-DHAVE_SOMETHING'
  1843. $Icomment    'INC'        => '$I', # e.g., '${Ihelp}-I/usr/include/other'
  1844. END
  1845.  
  1846.   my $C = grep {$_ ne "$modfname.c"}
  1847.     (glob '*.c'), (glob '*.cc'), (glob '*.C');
  1848.   my $Cpre = ($C ? '' : '# ');
  1849.   my $Ccomment = ($C ? '' : <<EOC);
  1850.     # Un-comment this if you add C files to link with later:
  1851. EOC
  1852.  
  1853.   print PL <<END;
  1854. $Ccomment    $Cpre\'OBJECT'        => '\$(O_FILES)', # link all the C files too
  1855. END
  1856. } # ' # Grr
  1857. print PL ");\n";
  1858. if (!$opt_c) {
  1859.   my $generate_code =
  1860.     WriteMakefileSnippet ( C_FILE =>       $constscfname,
  1861.                            XS_FILE =>      $constsxsfname,
  1862.                            DEFAULT_TYPE => $opt_t,
  1863.                            NAME =>         $module,
  1864.                            NAMES =>        \@const_names,
  1865.                  );
  1866.   print PL <<"END";
  1867. if  (eval {require ExtUtils::Constant; 1}) {
  1868.   # If you edit these definitions to change the constants used by this module,
  1869.   # you will need to use the generated $constscfname and $constsxsfname
  1870.   # files to replace their "fallback" counterparts before distributing your
  1871.   # changes.
  1872. $generate_code
  1873. }
  1874. else {
  1875.   use File::Copy;
  1876.   use File::Spec;
  1877.   foreach my \$file ('$constscfname', '$constsxsfname') {
  1878.     my \$fallback = File::Spec->catfile('$fallbackdirname', \$file);
  1879.     copy (\$fallback, \$file) or die "Can't copy \$fallback to \$file: \$!";
  1880.   }
  1881. }
  1882. END
  1883.  
  1884.   eval $generate_code;
  1885.   if ($@) {
  1886.     warn <<"EOM";
  1887. Attempting to test constant code in $ext$modpname/Makefile.PL:
  1888. $generate_code
  1889. __END__
  1890. gave unexpected error $@
  1891. Please report the circumstances of this bug in h2xs version $H2XS_VERSION
  1892. using the perlbug script.
  1893. EOM
  1894.   } else {
  1895.     my $fail;
  1896.  
  1897.     foreach my $file ($constscfname, $constsxsfname) {
  1898.       my $fallback = File::Spec->catfile($fallbackdirname, $file);
  1899.       if (compare($file, $fallback)) {
  1900.         warn << "EOM";
  1901. Files "$ext$modpname/$fallbackdirname/$file" and "$ext$modpname/$file" differ.
  1902. EOM
  1903.         $fail++;
  1904.       }
  1905.     }
  1906.     if ($fail) {
  1907.       warn fill ('','', <<"EOM") . "\n";
  1908. It appears that the code in $ext$modpname/Makefile.PL does not autogenerate
  1909. the files $ext$modpname/$constscfname and $ext$modpname/$constsxsfname
  1910. correctly.
  1911.  
  1912. Please report the circumstances of this bug in h2xs version $H2XS_VERSION
  1913. using the perlbug script.
  1914. EOM
  1915.     } else {
  1916.       unlink $constscfname, $constsxsfname;
  1917.     }
  1918.   }
  1919. }
  1920. close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n";
  1921.  
  1922. # Create a simple README since this is a CPAN requirement
  1923. # and it doesnt hurt to have one
  1924. warn "Writing $ext$modpname/README\n";
  1925. open(RM, ">README") || die "Can't create $ext$modpname/README:$!\n";
  1926. my $thisyear = (gmtime)[5] + 1900;
  1927. my $rmhead = "$modpname version $TEMPLATE_VERSION";
  1928. my $rmheadeq = "=" x length($rmhead);
  1929.  
  1930. my $rm_prereq;
  1931.  
  1932. if ( $compat_version < 5.00702 and $new_test )
  1933. {
  1934.    $rm_prereq = 'Test::More';
  1935. }
  1936. else
  1937. {
  1938.    $rm_prereq = 'blah blah blah';
  1939. }
  1940.  
  1941. print RM <<_RMEND_;
  1942. $rmhead
  1943. $rmheadeq
  1944.  
  1945. The README is used to introduce the module and provide instructions on
  1946. how to install the module, any machine dependencies it may have (for
  1947. example C compilers and installed libraries) and any other information
  1948. that should be provided before the module is installed.
  1949.  
  1950. A README file is required for CPAN modules since CPAN extracts the
  1951. README file from a module distribution so that people browsing the
  1952. archive can use it get an idea of the modules uses. It is usually a
  1953. good idea to provide version information here so that people can
  1954. decide whether fixes for the module are worth downloading.
  1955.  
  1956. INSTALLATION
  1957.  
  1958. To install this module type the following:
  1959.  
  1960.    perl Makefile.PL
  1961.    make
  1962.    make test
  1963.    make install
  1964.  
  1965. DEPENDENCIES
  1966.  
  1967. This module requires these other modules and libraries:
  1968.  
  1969.   $rm_prereq
  1970.  
  1971. COPYRIGHT AND LICENCE
  1972.  
  1973. Put the correct copyright and licence information here.
  1974.  
  1975. Copyright (C) $thisyear $author
  1976.  
  1977. This library is free software; you can redistribute it and/or modify
  1978. it under the same terms as Perl itself. 
  1979.  
  1980. _RMEND_
  1981. close(RM) || die "Can't close $ext$modpname/README: $!\n";
  1982.  
  1983. my $testdir  = "t";
  1984. my $testfile = "$testdir/1.t";
  1985. unless (-d "$testdir") {
  1986.   mkdir "$testdir" or die "Cannot mkdir $testdir: $!\n";
  1987. }
  1988. warn "Writing $ext$modpname/$testfile\n";
  1989. my $tests = @const_names ? 2 : 1;
  1990.  
  1991. open EX, ">$testfile" or die "Can't create $ext$modpname/$testfile: $!\n";
  1992.  
  1993. print EX <<_END_;
  1994. # Before `make install' is performed this script should be runnable with
  1995. # `make test'. After `make install' it should work as `perl 1.t'
  1996.  
  1997. #########################
  1998.  
  1999. # change 'tests => $tests' to 'tests => last_test_to_print';
  2000.  
  2001. _END_
  2002.  
  2003. my $test_mod = 'Test::More';
  2004.  
  2005. if ( $old_test or ($compat_version < 5.007 and not $new_test ))
  2006. {
  2007.   my $test_mod = 'Test';
  2008.  
  2009.   print EX <<_END_;
  2010. use Test;
  2011. BEGIN { plan tests => $tests };
  2012. use $module;
  2013. ok(1); # If we made it this far, we're ok.
  2014.  
  2015. _END_
  2016.  
  2017.    if (@const_names) {
  2018.      my $const_names = join " ", @const_names;
  2019.      print EX <<'_END_';
  2020.  
  2021. my $fail;
  2022. foreach my $constname (qw(
  2023. _END_
  2024.  
  2025.      print EX wrap ("\t", "\t", $const_names);
  2026.      print EX (")) {\n");
  2027.  
  2028.      print EX <<_END_;
  2029.   next if (eval "my \\\$a = \$constname; 1");
  2030.   if (\$\@ =~ /^Your vendor has not defined $module macro \$constname/) {
  2031.     print "# pass: \$\@";
  2032.   } else {
  2033.     print "# fail: \$\@";
  2034.     \$fail = 1;    
  2035.   }
  2036. }
  2037. if (\$fail) {
  2038.   print "not ok 2\\n";
  2039. } else {
  2040.   print "ok 2\\n";
  2041. }
  2042.  
  2043. _END_
  2044.   }
  2045. }
  2046. else
  2047. {
  2048.   print EX <<_END_;
  2049. use Test::More tests => $tests;
  2050. BEGIN { use_ok('$module') };
  2051.  
  2052. _END_
  2053.  
  2054.    if (@const_names) {
  2055.      my $const_names = join " ", @const_names;
  2056.      print EX <<'_END_';
  2057.  
  2058. my $fail = 0;
  2059. foreach my $constname (qw(
  2060. _END_
  2061.  
  2062.      print EX wrap ("\t", "\t", $const_names);
  2063.      print EX (")) {\n");
  2064.  
  2065.      print EX <<_END_;
  2066.   next if (eval "my \\\$a = \$constname; 1");
  2067.   if (\$\@ =~ /^Your vendor has not defined $module macro \$constname/) {
  2068.     print "# pass: \$\@";
  2069.   } else {
  2070.     print "# fail: \$\@";
  2071.     \$fail = 1;
  2072.   }
  2073.  
  2074. }
  2075.  
  2076. ok( \$fail == 0 , 'Constants' );
  2077. _END_
  2078.   }
  2079. }
  2080.  
  2081. print EX <<_END_;
  2082. #########################
  2083.  
  2084. # Insert your test code below, the $test_mod module is use()ed here so read
  2085. # its man page ( perldoc $test_mod ) for help writing this test script.
  2086.  
  2087. _END_
  2088.  
  2089. close(EX) || die "Can't close $ext$modpname/$testfile: $!\n";
  2090.  
  2091. unless ($opt_C) {
  2092.   warn "Writing $ext$modpname/Changes\n";
  2093.   $" = ' ';
  2094.   open(EX, ">Changes") || die "Can't create $ext$modpname/Changes: $!\n";
  2095.   @ARGS = map {/[\s\"\'\`\$*?^|&<>\[\]\{\}\(\)]/ ? "'$_'" : $_} @ARGS;
  2096.   print EX <<EOP;
  2097. Revision history for Perl extension $module.
  2098.  
  2099. $TEMPLATE_VERSION  @{[scalar localtime]}
  2100. \t- original version; created by h2xs $H2XS_VERSION with options
  2101. \t\t@ARGS
  2102.  
  2103. EOP
  2104.   close(EX) || die "Can't close $ext$modpname/Changes: $!\n";
  2105. }
  2106.  
  2107. warn "Writing $ext$modpname/MANIFEST\n";
  2108. open(MANI,'>MANIFEST') or die "Can't create MANIFEST: $!";
  2109. my @files = grep { -f } (<*>, <t/*>, <$fallbackdirname/*>);
  2110. if (!@files) {
  2111.   eval {opendir(D,'.');};
  2112.   unless ($@) { @files = readdir(D); closedir(D); }
  2113. }
  2114. if (!@files) { @files = map {chomp && $_} `ls`; }
  2115. if ($^O eq 'VMS') {
  2116.   foreach (@files) {
  2117.     # Clip trailing '.' for portability -- non-VMS OSs don't expect it
  2118.     s%\.$%%;
  2119.     # Fix up for case-sensitive file systems
  2120.     s/$modfname/$modfname/i && next;
  2121.     $_ = "\U$_" if $_ eq 'manifest' or $_ eq 'changes';
  2122.     $_ = 'Makefile.PL' if $_ eq 'makefile.pl';
  2123.   }
  2124. }
  2125. print MANI join("\n",@files), "\n";
  2126. close MANI;
  2127.  
  2128. __END__
  2129. :endofperl
  2130.