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