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