avoid loading both XSLoader and DynaLoader (avoids dl_error()
[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.
8a5546a1 16$origdir = cwd;
44a8e56a 17chdir dirname($0);
18$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!";
5f05dabc 29$Config{startperl}
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
3edbfbe5 38=head1 NAME
39
40h2xs - convert .h C header files to Perl extensions
41
42=head1 SYNOPSIS
43
c0f8b9cd 44B<h2xs> [B<-ACOPXcdf>] [B<-v> version] [B<-n> module_name] [B<-p> prefix] [B<-s> sub] [headerfile ... [extra_libraries]]
f508c652 45
46B<h2xs> B<-h>
3edbfbe5 47
48=head1 DESCRIPTION
49
a887ff11 50I<h2xs> builds a Perl extension from C header files. The extension
51will include functions which can be used to retrieve the value of any
52#define statement which was in the C header files.
3edbfbe5 53
54The I<module_name> will be used for the name of the extension. If
a887ff11 55module_name is not supplied then the name of the first header file
56will be used, with the first character capitalized.
3edbfbe5 57
58If the extension might need extra libraries, they should be included
59here. The extension Makefile.PL will take care of checking whether
60the libraries actually exist and how they should be loaded.
61The extra libraries should be specified in the form -lm -lposix, etc,
62just as on the cc command line. By default, the Makefile.PL will
63search through the library path determined by Configure. That path
64can be augmented by including arguments of the form B<-L/another/library/path>
65in the extra-libraries argument.
66
67=head1 OPTIONS
68
69=over 5
70
f508c652 71=item B<-A>
3edbfbe5 72
f508c652 73Omit all autoload facilities. This is the same as B<-c> but also removes the
9ef261b5 74S<C<use AutoLoader>> statement from the .pm file.
3edbfbe5 75
c0f8b9cd 76=item B<-C>
77
78Omits creation of the F<Changes> file, and adds a HISTORY section to
79the POD template.
80
b73edd97 81=item B<-F>
82
83Additional flags to specify to C preprocessor when scanning header for
ddf6bed1 84function declarations. Should not be used without B<-x>.
85
86=item B<-M> I<regular expression>
87
88selects functions/macros to process.
b73edd97 89
2920c5d2 90=item B<-O>
91
92Allows a pre-existing extension directory to be overwritten.
93
f508c652 94=item B<-P>
3edbfbe5 95
f508c652 96Omit the autogenerated stub POD section.
3edbfbe5 97
b73edd97 98=item B<-X>
99
100Omit the XS portion. Used to generate templates for a module which is not
9ef261b5 101XS-based. C<-c> and C<-f> are implicitly enabled.
b73edd97 102
7c1d48a5 103=item B<-a>
104
105Generate an accessor method for each element of structs and unions. The
106generated methods are named after the element name; will return the current
107value of the element if called without additional arguments; and will set
32fb2b78 108the element to the supplied value (and return the new value) if called with
109an additional argument. Embedded structures and unions are returned as a
110pointer rather than the complete structure, to facilitate chained calls.
111
112These methods all apply to the Ptr type for the structure; additionally
113two methods are constructed for the structure type itself, C<_to_ptr>
114which returns a Ptr type pointing to the same structure, and a C<new>
115method to construct and return a new structure, initialised to zeroes.
7c1d48a5 116
3edbfbe5 117=item B<-c>
118
119Omit C<constant()> from the .xs file and corresponding specialised
120C<AUTOLOAD> from the .pm file.
121
b73edd97 122=item B<-d>
123
124Turn on debugging messages.
125
f508c652 126=item B<-f>
3edbfbe5 127
f508c652 128Allows an extension to be created for a header even if that header is
ddf6bed1 129not found in standard include directories.
f508c652 130
131=item B<-h>
132
133Print the usage, help and version for this h2xs and exit.
134
32fb2b78 135=item B<-k>
136
137For function arguments declared as C<const>, omit the const attribute in the
138generated XS code.
139
140=item B<-m>
141
142B<Experimental>: for each variable declared in the header file(s), declare
143a perl variable of the same name magically tied to the C variable.
144
f508c652 145=item B<-n> I<module_name>
146
147Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>
148
ddf6bed1 149=item B<-o> I<regular expression>
150
151Use "opaque" data type for the C types matched by the regular
152expression, even if these types are C<typedef>-equivalent to types
153from typemaps. Should not be used without B<-x>.
154
155This may be useful since, say, types which are C<typedef>-equivalent
156to integers may represent OS-related handles, and one may want to work
157with these handles in OO-way, as in C<$handle-E<gt>do_something()>.
158Use C<-o .> if you want to handle all the C<typedef>ed types as opaque types.
159
160The type-to-match is whitewashed (except for commas, which have no
161whitespace before them, and multiple C<*> which have no whitespace
162between them).
163
ead2a595 164=item B<-p> I<prefix>
165
166Specify a prefix which should be removed from the Perl function names, e.g., S<-p sec_rgy_>
167This sets up the XS B<PREFIX> keyword and removes the prefix from functions that are
98a6f11e 168autoloaded via the C<constant()> mechanism.
ead2a595 169
170=item B<-s> I<sub1,sub2>
171
172Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine.
173These macros are assumed to have a return type of B<char *>, e.g., S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.
174
f508c652 175=item B<-v> I<version>
176
177Specify a version number for this extension. This version number is added
178to the templates. The default is 0.01.
3edbfbe5 179
760ac839 180=item B<-x>
181
182Automatically generate XSUBs basing on function declarations in the
183header file. The package C<C::Scan> should be installed. If this
184option is specified, the name of the header file may look like
185C<NAME1,NAME2>. In this case NAME1 is used instead of the specified string,
b73edd97 186but XSUBs are emitted only for the declarations included from file NAME2.
760ac839 187
5273d82d 188Note that some types of arguments/return-values for functions may
189result in XSUB-declarations/typemap-entries which need
190hand-editing. Such may be objects which cannot be converted from/to a
ddf6bed1 191pointer (like C<long long>), pointers to functions, or arrays. See
192also the section on L<LIMITATIONS of B<-x>>.
5273d82d 193
3edbfbe5 194=back
195
196=head1 EXAMPLES
197
198
199 # Default behavior, extension is Rusers
200 h2xs rpcsvc/rusers
201
202 # Same, but extension is RUSERS
203 h2xs -n RUSERS rpcsvc/rusers
204
205 # Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
206 h2xs rpcsvc::rusers
207
208 # Extension is ONC::RPC. Still finds <rpcsvc/rusers.h>
209 h2xs -n ONC::RPC rpcsvc/rusers
210
211 # Without constant() or AUTOLOAD
212 h2xs -c rpcsvc/rusers
213
214 # Creates templates for an extension named RPC
215 h2xs -cfn RPC
216
217 # Extension is ONC::RPC.
218 h2xs -cfn ONC::RPC
219
220 # Makefile.PL will look for library -lrpc in
221 # additional directory /opt/net/lib
222 h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
223
ead2a595 224 # Extension is DCE::rgynbase
225 # prefix "sec_rgy_" is dropped from perl function names
226 h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
227
228 # Extension is DCE::rgynbase
229 # prefix "sec_rgy_" is dropped from perl function names
230 # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
231 h2xs -n DCE::rgynbase -p sec_rgy_ \
232 -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
3edbfbe5 233
5273d82d 234 # Make XS without defines in perl.h, but with function declarations
760ac839 235 # visible from perl.h. Name of the extension is perl1.
236 # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
237 # Extra backslashes below because the string is passed to shell.
5273d82d 238 # Note that a directory with perl header files would
239 # be added automatically to include path.
240 h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
760ac839 241
242 # Same with function declaration in proto.h as visible from perl.h.
5273d82d 243 h2xs -xAn perl2 perl.h,proto.h
760ac839 244
ddf6bed1 245 # Same but select only functions which match /^av_/
246 h2xs -M '^av_' -xAn perl2 perl.h,proto.h
247
248 # Same but treat SV* etc as "opaque" types
249 h2xs -o '^[S]V \*$' -M '^av_' -xAn perl2 perl.h,proto.h
250
3edbfbe5 251=head1 ENVIRONMENT
252
253No environment variables are used.
254
255=head1 AUTHOR
256
257Larry Wall and others
258
259=head1 SEE ALSO
260
f508c652 261L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.
3edbfbe5 262
263=head1 DIAGNOSTICS
264
760ac839 265The usual warnings if it cannot read or write the files involved.
3edbfbe5 266
ddf6bed1 267=head1 LIMITATIONS of B<-x>
268
269F<h2xs> would not distinguish whether an argument to a C function
270which is of the form, say, C<int *>, is an input, output, or
271input/output parameter. In particular, argument declarations of the
272form
273
274 int
275 foo(n)
276 int *n
277
278should be better rewritten as
279
280 int
281 foo(n)
282 int &n
283
284if C<n> is an input parameter.
285
286Additionally, F<h2xs> has no facilities to intuit that a function
287
288 int
289 foo(addr,l)
290 char *addr
291 int l
292
293takes a pair of address and length of data at this address, so it is better
294to rewrite this function as
295
296 int
297 foo(sv)
7aff18a2 298 SV *addr
299 PREINIT:
300 STRLEN len;
301 char *s;
302 CODE:
303 s = SvPV(sv,len);
304 RETVAL = foo(s, len);
305 OUTPUT:
306 RETVAL
ddf6bed1 307
308or alternately
309
310 static int
311 my_foo(SV *sv)
312 {
313 STRLEN len;
314 char *s = SvPV(sv,len);
315
316 return foo(s, len);
317 }
318
319 MODULE = foo PACKAGE = foo PREFIX = my_
320
321 int
322 foo(sv)
323 SV *sv
324
325See L<perlxs> and L<perlxstut> for additional details.
326
3edbfbe5 327=cut
328
3cb4da91 329use strict;
330
331
ddf6bed1 332my( $H2XS_VERSION ) = ' $Revision: 1.20 $ ' =~ /\$Revision:\s+([^\s]+)/;
f508c652 333my $TEMPLATE_VERSION = '0.01';
ddf6bed1 334my @ARGS = @ARGV;
a0d0e21e 335
336use Getopt::Std;
337
e1666bf5 338sub usage{
339 warn "@_\n" if @_;
c0f8b9cd 340 die "h2xs [-ACOPXcdfh] [-v version] [-n module_name] [-p prefix] [-s subs] [headerfile [extra_libraries]]
f508c652 341version: $H2XS_VERSION
3edbfbe5 342 -A Omit all autoloading facilities (implies -c).
c0f8b9cd 343 -C Omit creating the Changes file, add HISTORY heading to stub POD.
b73edd97 344 -F Additional flags for C preprocessor (used with -x).
ddf6bed1 345 -M Mask to select C functions/macros (default is select all).
2920c5d2 346 -O Allow overwriting of a pre-existing extension directory.
f508c652 347 -P Omit the stub POD section.
9ef261b5 348 -X Omit the XS portion (implies both -c and -f).
7c1d48a5 349 -a Generate get/set accessors for struct and union members (used with -x).
b73edd97 350 -c Omit the constant() function and specialised AUTOLOAD from the XS file.
351 -d Turn on debugging messages.
352 -f Force creation of the extension even if the C header does not exist.
353 -h Display this help message
32fb2b78 354 -k Omit 'const' attribute on function arguments (used with -x).
355 -m Generate tied variables for access to declared variables.
b73edd97 356 -n Specify a name to use for the extension (recommended).
ddf6bed1 357 -o Regular expression for \"opaque\" types.
b73edd97 358 -p Specify a prefix which should be removed from the Perl function names.
359 -s Create subroutines for specified macros.
f508c652 360 -v Specify a version number for this extension.
760ac839 361 -x Autogenerate XSUBs using C::Scan.
e1666bf5 362extra_libraries
363 are any libraries that might be needed for loading the
364 extension, e.g. -lm would try to link in the math library.
f508c652 365";
e1666bf5 366}
a0d0e21e 367
a0d0e21e 368
32fb2b78 369getopts("ACF:M:OPXacdfhkmn:o:p:s:v:x") || usage;
370use vars qw($opt_A $opt_C $opt_F $opt_M $opt_O $opt_P $opt_X $opt_a $opt_c $opt_d
371 $opt_f $opt_h $opt_k $opt_m $opt_n $opt_o $opt_p $opt_s $opt_v $opt_x);
a0d0e21e 372
e1666bf5 373usage if $opt_h;
f508c652 374
375if( $opt_v ){
376 $TEMPLATE_VERSION = $opt_v;
377}
9ef261b5 378
379# -A implies -c.
e1666bf5 380$opt_c = 1 if $opt_A;
9ef261b5 381
382# -X implies -c and -f
383$opt_c = $opt_f = 1 if $opt_X;
384
3cb4da91 385my %const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s;
386my $extralibs;
387my @path_h;
a0d0e21e 388
a887ff11 389while (my $arg = shift) {
390 if ($arg =~ /^-l/i) {
391 $extralibs = "$arg @ARGV";
392 last;
393 }
394 push(@path_h, $arg);
395}
e1666bf5 396
397usage "Must supply header file or module name\n"
a887ff11 398 unless (@path_h or $opt_n);
e1666bf5 399
ddf6bed1 400my $fmask;
3cb4da91 401my $tmask;
ddf6bed1 402
403$fmask = qr{$opt_M} if defined $opt_M;
404$tmask = qr{$opt_o} if defined $opt_o;
405my $tmask_all = $tmask && $opt_o eq '.';
406
407if ($opt_x) {
408 eval {require C::Scan; 1}
409 or die <<EOD;
410C::Scan required if you use -x option.
411To install C::Scan, execute
412 perl -MCPAN -e "install C::Scan"
413EOD
414 unless ($tmask_all) {
415 $C::Scan::VERSION >= 0.70
416 or die <<EOD;
417C::Scan v. 0.70 or later required unless you use -o . option.
418You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
419To install C::Scan, execute
420 perl -MCPAN -e "install C::Scan"
421EOD
422 }
32fb2b78 423 if (($opt_m || $opt_a) && $C::Scan::VERSION < 0.73) {
424 die <<EOD;
425C::Scan v. 0.73 or later required to use -m or -a options.
426You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
427To install C::Scan, execute
428 perl -MCPAN -e "install C::Scan"
429EOD
430 }
7aff18a2 431}
432elsif ($opt_o or $opt_F) {
ddf6bed1 433 warn <<EOD;
434Options -o and -F do not make sense without -x.
435EOD
436}
437
3cb4da91 438my @path_h_ini = @path_h;
439my ($name, %fullpath, %prefix, %seen_define, %prefixless, %const_names);
a0d0e21e 440
a887ff11 441if( @path_h ){
ddf6bed1 442 use Config;
443 use File::Spec;
444 my @paths;
445 if ($^O eq 'VMS') { # Consider overrides of default location
3cb4da91 446 # XXXX This is not equivalent to what the older version did:
447 # it was looking at $hadsys header-file per header-file...
448 my($hadsys) = grep s!^sys/!!i , @path_h;
7aff18a2 449 @paths = qw( Sys$Library VAXC$Include );
ddf6bed1 450 push @paths, ($hadsys ? 'GNU_CC_Include[vms]' : 'GNU_CC_Include[000000]');
451 push @paths, qw( DECC$Library_Include DECC$System_Include );
7aff18a2 452 }
453 else {
ddf6bed1 454 @paths = (File::Spec->curdir(), $Config{usrinc},
455 (split ' ', $Config{locincpth}), '/usr/include');
456 }
a887ff11 457 foreach my $path_h (@path_h) {
458 $name ||= $path_h;
e1666bf5 459 if( $path_h =~ s#::#/#g && $opt_n ){
460 warn "Nesting of headerfile ignored with -n\n";
461 }
462 $path_h .= ".h" unless $path_h =~ /\.h$/;
3cb4da91 463 my $fullpath = $path_h;
760ac839 464 $path_h =~ s/,.*$// if $opt_x;
3cb4da91 465 $fullpath{$path_h} = $fullpath;
ddf6bed1 466
467 if (not -f $path_h) {
468 my $tmp_path_h = $path_h;
469 for my $dir (@paths) {
470 last if -f ($path_h = File::Spec->catfile($dir, $tmp_path_h));
471 }
ead2a595 472 }
5273d82d 473
474 if (!$opt_c) {
475 die "Can't find $path_h\n" if ( ! $opt_f && ! -f $path_h );
476 # Scan the header file (we should deal with nested header files)
477 # Record the names of simple #define constants into const_names
a887ff11 478 # Function prototypes are processed below.
5273d82d 479 open(CH, "<$path_h") || die "Can't open $path_h: $!\n";
ddf6bed1 480 defines:
5273d82d 481 while (<CH>) {
3cb4da91 482 if (/^[ \t]*#[ \t]*define\s+([\$\w]+)\b(?!\()\s*(?=[^" \t])(.*)/) {
ddf6bed1 483 my $def = $1;
484 my $rest = $2;
485 $rest =~ s!/\*.*?(\*/|\n)|//.*!!g; # Remove comments
486 $rest =~ s/^\s+//;
487 $rest =~ s/\s+$//;
488 # Cannot do: (-1) and ((LHANDLE)3) are OK:
489 #print("Skip non-wordy $def => $rest\n"),
490 # next defines if $rest =~ /[^\w\$]/;
491 if ($rest =~ /"/) {
492 print("Skip stringy $def => $rest\n") if $opt_d;
493 next defines;
494 }
495 print "Matched $_ ($def)\n" if $opt_d;
496 $seen_define{$def} = $rest;
497 $_ = $def;
e1666bf5 498 next if /^_.*_h_*$/i; # special case, but for what?
760ac839 499 if (defined $opt_p) {
5273d82d 500 if (!/^$opt_p(\d)/) {
501 ++$prefix{$_} if s/^$opt_p//;
502 }
503 else {
504 warn "can't remove $opt_p prefix from '$_'!\n";
505 }
ead2a595 506 }
ddf6bed1 507 $prefixless{$def} = $_;
508 if (!$fmask or /$fmask/) {
509 print "... Passes mask of -M.\n" if $opt_d and $fmask;
510 $const_names{$_}++;
511 }
5273d82d 512 }
513 }
514 close(CH);
e1666bf5 515 }
a887ff11 516 }
a0d0e21e 517}
518
e1666bf5 519
3cb4da91 520my $module = $opt_n || do {
a0d0e21e 521 $name =~ s/\.h$//;
522 if( $name !~ /::/ ){
523 $name =~ s#^.*/##;
524 $name = "\u$name";
525 }
526 $name;
527};
528
3cb4da91 529my ($ext, $nested, @modparts, $modfname, $modpname);
8e07c86e 530(chdir 'ext', $ext = 'ext/') if -d 'ext';
a0d0e21e 531
532if( $module =~ /::/ ){
533 $nested = 1;
534 @modparts = split(/::/,$module);
535 $modfname = $modparts[-1];
536 $modpname = join('/',@modparts);
537}
538else {
539 $nested = 0;
540 @modparts = ();
541 $modfname = $modpname = $module;
542}
543
544
2920c5d2 545if ($opt_O) {
546 warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
7aff18a2 547}
548else {
2920c5d2 549 die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
550}
c07a80fd 551if( $nested ){
3cb4da91 552 my $modpath = "";
c07a80fd 553 foreach (@modparts){
554 mkdir("$modpath$_", 0777);
555 $modpath .= "$_/";
556 }
557}
a0d0e21e 558mkdir($modpname, 0777);
8e07c86e 559chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";
a0d0e21e 560
5273d82d 561my %types_seen;
562my %std_types;
f4d63e4e 563my $fdecls = [];
564my $fdecls_parsed = [];
ddf6bed1 565my $typedef_rex;
566my %typedefs_pre;
567my %known_fnames;
7c1d48a5 568my %structs;
5273d82d 569
3cb4da91 570my @fnames;
571my @fnames_no_prefix;
32fb2b78 572my %vdecl_hash;
573my @vdecls;
5273d82d 574
2920c5d2 575if( ! $opt_X ){ # use XS, unless it was disabled
576 open(XS, ">$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n";
5273d82d 577 if ($opt_x) {
5273d82d 578 require Config; # Run-time directive
579 warn "Scanning typemaps...\n";
580 get_typemap();
3cb4da91 581 my @td;
582 my @good_td;
583 my $addflags = $opt_F || '';
584
f4d63e4e 585 foreach my $filename (@path_h) {
3cb4da91 586 my $c;
587 my $filter;
588
589 if ($fullpath{$filename} =~ /,/) {
f4d63e4e 590 $filename = $`;
591 $filter = $';
592 }
593 warn "Scanning $filename for functions...\n";
594 $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
7c1d48a5 595 'add_cppflags' => $addflags, 'c_styles' => [qw(C++ C9X)];
f4d63e4e 596 $c->set('includeDirs' => ["$Config::Config{archlib}/CORE"]);
ddf6bed1 597
f4d63e4e 598 push @$fdecls_parsed, @{ $c->get('parsed_fdecls') };
599 push(@$fdecls, @{$c->get('fdecls')});
3cb4da91 600
601 push @td, @{$c->get('typedefs_maybe')};
7c1d48a5 602 if ($opt_a) {
603 my $structs = $c->get('typedef_structs');
604 @structs{keys %$structs} = values %$structs;
605 }
3cb4da91 606
32fb2b78 607 if ($opt_m) {
608 %vdecl_hash = %{ $c->get('vdecl_hash') };
609 @vdecls = sort keys %vdecl_hash;
610 for (local $_ = 0; $_ < @vdecls; ++$_) {
611 my $var = $vdecls[$_];
612 my($type, $post) = @{ $vdecl_hash{$var} };
613 if (defined $post) {
614 warn "Can't handle variable '$type $var $post', skipping.\n";
615 splice @vdecls, $_, 1;
616 redo;
617 }
618 $type = normalize_type($type);
619 $vdecl_hash{$var} = $type;
620 }
621 }
622
3cb4da91 623 unless ($tmask_all) {
624 warn "Scanning $filename for typedefs...\n";
625 my $td = $c->get('typedef_hash');
626 # eval {require 'dumpvar.pl'; ::dumpValue($td)} or warn $@ if $opt_d;
627 my @f_good_td = grep $td->{$_}[1] eq '', keys %$td;
628 push @good_td, @f_good_td;
629 @typedefs_pre{@f_good_td} = map $_->[0], @$td{@f_good_td};
630 }
631 }
632 { local $" = '|';
6542b28e 633 $typedef_rex = qr(\b(?<!struct )(?:@good_td)\b) if @good_td;
5273d82d 634 }
ddf6bed1 635 %known_fnames = map @$_[1,3], @$fdecls_parsed; # [1,3] is NAME, FULLTEXT
636 if ($fmask) {
637 my @good;
638 for my $i (0..$#$fdecls_parsed) {
639 next unless $fdecls_parsed->[$i][1] =~ /$fmask/; # [1] is NAME
640 push @good, $i;
641 print "... Function $fdecls_parsed->[$i][1] passes -M mask.\n"
642 if $opt_d;
643 }
644 $fdecls = [@$fdecls[@good]];
645 $fdecls_parsed = [@$fdecls_parsed[@good]];
646 }
3cb4da91 647 @fnames = sort map $_->[1], @$fdecls_parsed; # 1 is NAME
648 # Sort declarations:
649 {
650 my %h = map( ($_->[1], $_), @$fdecls_parsed);
651 $fdecls_parsed = [ @h{@fnames} ];
ddf6bed1 652 }
3cb4da91 653 @fnames_no_prefix = @fnames;
654 @fnames_no_prefix
655 = sort map { ++$prefix{$_} if s/^$opt_p(?!\d)//; $_ } @fnames_no_prefix;
ddf6bed1 656 # Remove macros which expand to typedefs
ddf6bed1 657 print "Typedefs are @td.\n" if $opt_d;
658 my %td = map {($_, $_)} @td;
659 # Add some other possible but meaningless values for macros
660 for my $k (qw(char double float int long short unsigned signed void)) {
661 $td{"$_$k"} = "$_$k" for ('', 'signed ', 'unsigned ');
662 }
663 # eval {require 'dumpvar.pl'; ::dumpValue( [\@td, \%td] ); 1} or warn $@;
664 my $n = 0;
665 my %bad_macs;
666 while (keys %td > $n) {
667 $n = keys %td;
668 my ($k, $v);
669 while (($k, $v) = each %seen_define) {
670 # print("found '$k'=>'$v'\n"),
671 $bad_macs{$k} = $td{$k} = $td{$v} if exists $td{$v};
672 }
673 }
674 # Now %bad_macs contains names of bad macros
675 for my $k (keys %bad_macs) {
676 delete $const_names{$prefixless{$k}};
677 print "Ignoring macro $k which expands to a typedef name '$bad_macs{$k}'\n" if $opt_d;
5273d82d 678 }
5273d82d 679 }
2920c5d2 680}
3cb4da91 681my @const_names = sort keys %const_names;
5273d82d 682
8e07c86e 683open(PM, ">$modfname.pm") || die "Can't create $ext$modpname/$modfname.pm: $!\n";
a0d0e21e 684
a0d0e21e 685$" = "\n\t";
8e07c86e 686warn "Writing $ext$modpname/$modfname.pm\n";
a0d0e21e 687
a0d0e21e 688print PM <<"END";
689package $module;
690
51fac20b 691require 5.005_62;
2920c5d2 692use strict;
8cd79558 693use warnings;
2920c5d2 694END
695
aba05478 696unless( $opt_X || $opt_c || $opt_A ){
2920c5d2 697 # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and
698 # will want Carp.
699 print PM <<'END';
700use Carp;
2920c5d2 701END
702}
703
704print PM <<'END';
705
a0d0e21e 706require Exporter;
2920c5d2 707END
708
709print PM <<"END" if ! $opt_X; # use DynaLoader, unless XS was disabled
a0d0e21e 710require DynaLoader;
3edbfbe5 711END
712
e1666bf5 713
9ef261b5 714# Are we using AutoLoader or not?
715unless ($opt_A) { # no autoloader whatsoever.
716 unless ($opt_c) { # we're doing the AUTOLOAD
717 print PM "use AutoLoader;\n";
2920c5d2 718 }
9ef261b5 719 else {
720 print PM "use AutoLoader qw(AUTOLOAD);\n"
2920c5d2 721 }
3edbfbe5 722}
3edbfbe5 723
9ef261b5 724# Determine @ISA.
77ca0c92 725my $myISA = 'our @ISA = qw(Exporter'; # We seem to always want this.
9ef261b5 726$myISA .= ' DynaLoader' unless $opt_X; # no XS
727$myISA .= ');';
728print PM "\n$myISA\n\n";
e1666bf5 729
32fb2b78 730my @exported_names = (@const_names, @fnames_no_prefix, map '$'.$_, @vdecls);
3cb4da91 731
3edbfbe5 732print PM<<"END";
e1666bf5 733# Items to export into callers namespace by default. Note: do not export
734# names by default without a very good reason. Use EXPORT_OK instead.
735# Do not simply export all your public functions/methods/constants.
ddf6bed1 736
737# This allows declaration use $module ':all';
738# If you do not need this, moving things directly into \@EXPORT or \@EXPORT_OK
739# will save memory.
51fac20b 740our %EXPORT_TAGS = ( 'all' => [ qw(
3cb4da91 741 @exported_names
ddf6bed1 742) ] );
743
51fac20b 744our \@EXPORT_OK = ( \@{ \$EXPORT_TAGS{'all'} } );
ddf6bed1 745
77ca0c92 746our \@EXPORT = qw(
e1666bf5 747 @const_names
a0d0e21e 748);
77ca0c92 749our \$VERSION = '$TEMPLATE_VERSION';
f508c652 750
e1666bf5 751END
752
32fb2b78 753if (@vdecls) {
754 printf PM "our(@{[ join ', ', map '$'.$_, @vdecls ]});\n\n";
755}
756
2920c5d2 757print PM <<"END" unless $opt_c or $opt_X;
a0d0e21e 758sub AUTOLOAD {
3edbfbe5 759 # This AUTOLOAD is used to 'autoload' constants from the constant()
760 # XS function. If a constant is not found then control is passed
761 # to the AUTOLOAD in AutoLoader.
e1666bf5 762
2920c5d2 763 my \$constname;
65346fe1 764 our \$AUTOLOAD;
a0d0e21e 765 (\$constname = \$AUTOLOAD) =~ s/.*:://;
1d3434b8 766 croak "&$module::constant not defined" if \$constname eq 'constant';
2920c5d2 767 my \$val = constant(\$constname, \@_ ? \$_[0] : 0);
a0d0e21e 768 if (\$! != 0) {
265f5c4a 769 if (\$! =~ /Invalid/ || \$!{EINVAL}) {
a0d0e21e 770 \$AutoLoader::AUTOLOAD = \$AUTOLOAD;
771 goto &AutoLoader::AUTOLOAD;
772 }
773 else {
7aff18a2 774 croak "Your vendor has not defined $module macro \$constname";
a0d0e21e 775 }
776 }
7aff18a2 777 {
778 no strict 'refs';
779 # Fixed between 5.005_53 and 5.005_61
780 if (\$] >= 5.00561) {
781 *\$AUTOLOAD = sub () { \$val };
782 }
783 else {
784 *\$AUTOLOAD = sub { \$val };
785 }
ddf6bed1 786 }
a0d0e21e 787 goto &\$AUTOLOAD;
788}
789
a0d0e21e 790END
a0d0e21e 791
2920c5d2 792if( ! $opt_X ){ # print bootstrap, unless XS is disabled
793 print PM <<"END";
f508c652 794bootstrap $module \$VERSION;
2920c5d2 795END
796}
797
32fb2b78 798# tying the variables can happen only after bootstrap
799if (@vdecls) {
800 printf PM <<END;
801{
802@{[ join "\n", map " _tievar_$_(\$$_);", @vdecls ]}
803}
804
805END
806}
807
3cb4da91 808my $after;
2920c5d2 809if( $opt_P ){ # if POD is disabled
810 $after = '__END__';
811}
812else {
813 $after = '=cut';
814}
815
816print PM <<"END";
a0d0e21e 817
e1666bf5 818# Preloaded methods go here.
9ef261b5 819END
820
821print PM <<"END" unless $opt_A;
a0d0e21e 822
2920c5d2 823# Autoload methods go after $after, and are processed by the autosplit program.
9ef261b5 824END
825
826print PM <<"END";
a0d0e21e 827
8281;
e1666bf5 829__END__
a0d0e21e 830END
a0d0e21e 831
3cb4da91 832my $author = "A. U. Thor";
833my $email = 'a.u.thor@a.galaxy.far.far.away';
f508c652 834
c0f8b9cd 835my $revhist = '';
836$revhist = <<EOT if $opt_C;
837
838=head1 HISTORY
839
840=over 8
841
842=item $TEMPLATE_VERSION
843
ddf6bed1 844Original version; created by h2xs $H2XS_VERSION with options
845
846 @ARGS
c0f8b9cd 847
848=back
849
850EOT
851
ddf6bed1 852my $exp_doc = <<EOD;
853
854=head2 EXPORT
855
856None by default.
857
858EOD
5273d82d 859if (@const_names and not $opt_P) {
ddf6bed1 860 $exp_doc .= <<EOD;
861=head2 Exportable constants
5273d82d 862
863 @{[join "\n ", @const_names]}
864
865EOD
866}
867if (defined $fdecls and @$fdecls and not $opt_P) {
ddf6bed1 868 $exp_doc .= <<EOD;
869=head2 Exportable functions
5273d82d 870
3cb4da91 871EOD
872 $exp_doc .= <<EOD if $opt_p;
873When accessing these functions from Perl, prefix C<$opt_p> should be removed.
874
875EOD
876 $exp_doc .= <<EOD;
ddf6bed1 877 @{[join "\n ", @known_fnames{@fnames}]}
5273d82d 878
879EOD
880}
881
3cb4da91 882my $pod = <<"END" unless $opt_P;
7aff18a2 883## Below is stub documentation for your module. You better edit it!
f508c652 884#
885#=head1 NAME
886#
887#$module - Perl extension for blah blah blah
888#
889#=head1 SYNOPSIS
890#
891# use $module;
892# blah blah blah
893#
894#=head1 DESCRIPTION
895#
7aff18a2 896#Stub documentation for $module, created by h2xs. It looks like the
f508c652 897#author of the extension was negligent enough to leave the stub
898#unedited.
899#
900#Blah blah blah.
ddf6bed1 901#$exp_doc$revhist
f508c652 902#=head1 AUTHOR
903#
904#$author, $email
905#
906#=head1 SEE ALSO
907#
908#perl(1).
909#
910#=cut
911END
912
913$pod =~ s/^\#//gm unless $opt_P;
914print PM $pod unless $opt_P;
915
a0d0e21e 916close PM;
917
e1666bf5 918
2920c5d2 919if( ! $opt_X ){ # print XS, unless it is disabled
8e07c86e 920warn "Writing $ext$modpname/$modfname.xs\n";
e1666bf5 921
a0d0e21e 922print XS <<"END";
923#include "EXTERN.h"
924#include "perl.h"
925#include "XSUB.h"
926
927END
a887ff11 928if( @path_h ){
3cb4da91 929 foreach my $path_h (@path_h_ini) {
a0d0e21e 930 my($h) = $path_h;
931 $h =~ s#^/usr/include/##;
ead2a595 932 if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; }
a887ff11 933 print XS qq{#include <$h>\n};
934 }
935 print XS "\n";
a0d0e21e 936}
937
ddf6bed1 938my %pointer_typedefs;
939my %struct_typedefs;
940
941sub td_is_pointer {
942 my $type = shift;
943 my $out = $pointer_typedefs{$type};
944 return $out if defined $out;
945 my $otype = $type;
946 $out = ($type =~ /\*$/);
947 # This converts only the guys which do not have trailing part in the typedef
948 if (not $out
949 and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
950 $type = normalize_type($type);
951 print "Is-Pointer: Type mutation via typedefs: $otype ==> $type\n"
952 if $opt_d;
953 $out = td_is_pointer($type);
954 }
955 return ($pointer_typedefs{$otype} = $out);
956}
957
958sub td_is_struct {
959 my $type = shift;
960 my $out = $struct_typedefs{$type};
961 return $out if defined $out;
962 my $otype = $type;
32fb2b78 963 $out = ($type =~ /^(struct|union)\b/) && !td_is_pointer($type);
ddf6bed1 964 # This converts only the guys which do not have trailing part in the typedef
965 if (not $out
966 and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
967 $type = normalize_type($type);
968 print "Is-Struct: Type mutation via typedefs: $otype ==> $type\n"
969 if $opt_d;
970 $out = td_is_struct($type);
971 }
972 return ($struct_typedefs{$otype} = $out);
973}
974
975# Some macros will bomb if you try to return them from a double-returning func.
976# Say, ((char *)0), or strlen (if somebody #define STRLEN strlen).
977# Fortunately, we can detect both these cases...
978sub protect_convert_to_double {
979 my $in = shift;
980 my $val;
981 return '' unless defined ($val = $seen_define{$in});
982 return '(IV)' if $known_fnames{$val};
983 # OUT_t of ((OUT_t)-1):
984 return '' unless $val =~ /^\s*(\(\s*)?\(\s*([^()]*?)\s*\)/;
985 td_is_pointer($2) ? '(IV)' : '';
a0d0e21e 986}
987
ddf6bed1 988# For each of the generated functions, length($pref) leading
989# letters are already checked. Moreover, it is recommended that
990# the generated functions uses switch on letter at offset at least
991# $off + length($pref).
992#
993# The given list has length($pref) chars removed at front, it is
994# guarantied that $off leading chars in the rest are the same for all
995# elts of the list.
996#
997# Returns: how at which offset it was decided to make a switch, or -1 if none.
998
999sub write_const;
1000
1001sub write_const {
1002 my ($fh, $pref, $off, $list) = (shift,shift,shift,shift);
1003 my %leading;
1004 my $offarg = length $pref;
1005
1006 if (@$list == 0) { # Can happen on the initial iteration only
1007 print $fh <<"END";
a0d0e21e 1008static double
3cb4da91 1009constant(char *name, int len, int arg)
a0d0e21e 1010{
ddf6bed1 1011 errno = EINVAL;
1012 return 0;
1013}
a0d0e21e 1014END
a0d0e21e 1015 return -1;
ddf6bed1 1016 }
a0d0e21e 1017
ddf6bed1 1018 if (@$list == 1) { # Can happen on the initial iteration only
1019 my $protect = protect_convert_to_double("$pref$list->[0]");
e1666bf5 1020
ddf6bed1 1021 print $fh <<"END";
1022static double
3cb4da91 1023constant(char *name, int len, int arg)
ddf6bed1 1024{
daf40514 1025 errno = 0;
ddf6bed1 1026 if (strEQ(name + $offarg, "$list->[0]")) { /* $pref removed */
1027#ifdef $pref$list->[0]
1028 return $protect$pref$list->[0];
1029#else
1030 errno = ENOENT;
1031 return 0;
1032#endif
1033 }
1034 errno = EINVAL;
1035 return 0;
a0d0e21e 1036}
ddf6bed1 1037END
1038 return -1;
1039 }
a0d0e21e 1040
ddf6bed1 1041 for my $n (@$list) {
1042 my $c = substr $n, $off, 1;
1043 $leading{$c} = [] unless exists $leading{$c};
1044 push @{$leading{$c}}, substr $n, $off + 1;
1045 }
1046
1047 if (keys(%leading) == 1) {
1048 return 1 + write_const $fh, $pref, $off + 1, $list;
1049 }
1050
1051 my $leader = substr $list->[0], 0, $off;
3cb4da91 1052 foreach my $letter (keys %leading) {
ddf6bed1 1053 write_const $fh, "$pref$leader$letter", 0, $leading{$letter}
1054 if @{$leading{$letter}} > 1;
1055 }
a0d0e21e 1056
ddf6bed1 1057 my $npref = "_$pref";
1058 $npref = '' if $pref eq '';
a0d0e21e 1059
ddf6bed1 1060 print $fh <<"END";
a0d0e21e 1061static double
3cb4da91 1062constant$npref(char *name, int len, int arg)
a0d0e21e 1063{
daf40514 1064END
1065
1066 print $fh <<"END" if $npref eq '';
a0d0e21e 1067 errno = 0;
a0d0e21e 1068END
1069
3cb4da91 1070 print $fh <<"END" if $off;
1071 if ($offarg + $off >= len ) {
1072 errno = EINVAL;
1073 return 0;
1074 }
1075END
e1666bf5 1076
3cb4da91 1077 print $fh <<"END";
ddf6bed1 1078 switch (name[$offarg + $off]) {
1079END
a0d0e21e 1080
3cb4da91 1081 foreach my $letter (sort keys %leading) {
ddf6bed1 1082 my $let = $letter;
1083 $let = '\0' if $letter eq '';
a0d0e21e 1084
ddf6bed1 1085 print $fh <<EOP;
1086 case '$let':
1087EOP
1088 if (@{$leading{$letter}} > 1) {
1089 # It makes sense to call a function
1090 if ($off) {
1091 print $fh <<EOP;
1092 if (!strnEQ(name + $offarg,"$leader", $off))
1093 break;
1094EOP
1095 }
1096 print $fh <<EOP;
3cb4da91 1097 return constant_$pref$leader$letter(name, len, arg);
ddf6bed1 1098EOP
7aff18a2 1099 }
1100 else {
ddf6bed1 1101 # Do it ourselves
1102 my $protect
1103 = protect_convert_to_double("$pref$leader$letter$leading{$letter}[0]");
1104
1105 print $fh <<EOP;
1106 if (strEQ(name + $offarg, "$leader$letter$leading{$letter}[0]")) { /* $pref removed */
1107#ifdef $pref$leader$letter$leading{$letter}[0]
1108 return $protect$pref$leader$letter$leading{$letter}[0];
a0d0e21e 1109#else
1110 goto not_there;
1111#endif
ddf6bed1 1112 }
1113EOP
a0d0e21e 1114 }
ddf6bed1 1115 }
1116 print $fh <<"END";
a0d0e21e 1117 }
1118 errno = EINVAL;
1119 return 0;
1120
1121not_there:
1122 errno = ENOENT;
1123 return 0;
1124}
1125
e1666bf5 1126END
ddf6bed1 1127
e1666bf5 1128}
1129
ddf6bed1 1130if( ! $opt_c ) {
1131 print XS <<"END";
1132static int
1133not_here(char *s)
1134{
1135 croak("$module::%s not implemented on this architecture", s);
1136 return -1;
1137}
1138
1139END
1140
1141 write_const(\*XS, '', 0, \@const_names);
e1666bf5 1142}
1143
32fb2b78 1144print_tievar_subs(\*XS, $_, $vdecl_hash{$_}) for @vdecls;
1145
3cb4da91 1146my $prefix;
ead2a595 1147$prefix = "PREFIX = $opt_p" if defined $opt_p;
3cb4da91 1148
e1666bf5 1149# Now switch from C to XS by issuing the first MODULE declaration:
1150print XS <<"END";
a0d0e21e 1151
ead2a595 1152MODULE = $module PACKAGE = $module $prefix
1153
1154END
1155
1156foreach (sort keys %const_xsub) {
1157 print XS <<"END";
1158char *
1159$_()
1160
1161 CODE:
1162#ifdef $_
7aff18a2 1163 RETVAL = $_;
ead2a595 1164#else
7aff18a2 1165 croak("Your vendor has not defined the $module macro $_");
ead2a595 1166#endif
1167
1168 OUTPUT:
7aff18a2 1169 RETVAL
a0d0e21e 1170
e1666bf5 1171END
ead2a595 1172}
e1666bf5 1173
1174# If a constant() function was written then output a corresponding
1175# XS declaration:
1176print XS <<"END" unless $opt_c;
1177
a0d0e21e 1178double
3cb4da91 1179constant(sv,arg)
7aff18a2 1180 PREINIT:
3cb4da91 1181 STRLEN len;
7aff18a2 1182 INPUT:
3cb4da91 1183 SV * sv
1184 char * s = SvPV(sv, len);
a0d0e21e 1185 int arg
7aff18a2 1186 CODE:
3cb4da91 1187 RETVAL = constant(s,len,arg);
7aff18a2 1188 OUTPUT:
3cb4da91 1189 RETVAL
a0d0e21e 1190
1191END
a0d0e21e 1192
5273d82d 1193my %seen_decl;
ddf6bed1 1194my %typemap;
5273d82d 1195
ead2a595 1196sub print_decl {
1197 my $fh = shift;
1198 my $decl = shift;
1199 my ($type, $name, $args) = @$decl;
5273d82d 1200 return if $seen_decl{$name}++; # Need to do the same for docs as well?
1201
ead2a595 1202 my @argnames = map {$_->[1]} @$args;
ddf6bed1 1203 my @argtypes = map { normalize_type( $_->[0], 1 ) } @$args;
32fb2b78 1204 if ($opt_k) {
1205 s/^\s*const\b\s*// for @argtypes;
1206 }
5273d82d 1207 my @argarrays = map { $_->[4] || '' } @$args;
ead2a595 1208 my $numargs = @$args;
1209 if ($numargs and $argtypes[-1] eq '...') {
1210 $numargs--;
1211 $argnames[-1] = '...';
1212 }
1213 local $" = ', ';
ddf6bed1 1214 $type = normalize_type($type, 1);
1215
ead2a595 1216 print $fh <<"EOP";
1217
1218$type
1219$name(@argnames)
1220EOP
1221
3cb4da91 1222 for my $arg (0 .. $numargs - 1) {
ead2a595 1223 print $fh <<"EOP";
5273d82d 1224 $argtypes[$arg] $argnames[$arg]$argarrays[$arg]
ead2a595 1225EOP
1226 }
1227}
1228
32fb2b78 1229sub print_tievar_subs {
1230 my($fh, $name, $type) = @_;
1231 print $fh <<END;
1232I32
1233_get_$name(IV index, SV *sv) {
1234 dSP;
1235 PUSHMARK(SP);
1236 XPUSHs(sv);
1237 PUTBACK;
1238 (void)call_pv("$module\::_get_$name", G_DISCARD);
1239 return (I32)0;
1240}
1241
1242I32
1243_set_$name(IV index, SV *sv) {
1244 dSP;
1245 PUSHMARK(SP);
1246 XPUSHs(sv);
1247 PUTBACK;
1248 (void)call_pv("$module\::_set_$name", G_DISCARD);
1249 return (I32)0;
1250}
1251
1252END
1253}
1254
1255sub print_tievar_xsubs {
1256 my($fh, $name, $type) = @_;
1257 print $fh <<END;
1258void
1259_tievar_$name(sv)
1260 SV* sv
1261 PREINIT:
1262 struct ufuncs uf;
1263 CODE:
1264 uf.uf_val = &_get_$name;
1265 uf.uf_set = &_set_$name;
1266 uf.uf_index = (IV)&_get_$name;
1267 sv_magic(sv, 0, 'U', (char*)&uf, sizeof(uf));
1268
1269void
1270_get_$name(THIS)
1271 $type THIS = NO_INIT
1272 CODE:
1273 THIS = $name;
1274 OUTPUT:
1275 SETMAGIC: DISABLE
1276 THIS
1277
1278void
1279_set_$name(THIS)
1280 $type THIS
1281 CODE:
1282 $name = THIS;
1283
1284END
1285}
1286
7c1d48a5 1287sub print_accessors {
1288 my($fh, $name, $struct) = @_;
1289 return unless defined $struct && $name !~ /\s|_ANON/;
1290 $name = normalize_type($name);
1291 my $ptrname = normalize_type("$name *");
32fb2b78 1292 print $fh <<"EOF";
1293
1294MODULE = $module PACKAGE = ${name} $prefix
1295
1296$name *
1297_to_ptr(THIS)
1298 $name THIS = NO_INIT
1299 PROTOTYPE: \$
1300 CODE:
1301 if (sv_derived_from(ST(0), "$name")) {
1302 STRLEN len;
1303 char *s = SvPV((SV*)SvRV(ST(0)), len);
1304 if (len != sizeof(THIS))
1305 croak("Size \%d of packed data != expected \%d",
1306 len, sizeof(THIS));
1307 RETVAL = ($name *)s;
1308 }
1309 else
1310 croak("THIS is not of type $name");
1311 OUTPUT:
1312 RETVAL
1313
1314$name
1315new(CLASS)
1316 char *CLASS = NO_INIT
1317 PROTOTYPE: \$
1318 CODE:
1319 Zero((void*)&RETVAL, sizeof(RETVAL), char);
1320 OUTPUT:
1321 RETVAL
7c1d48a5 1322
1323MODULE = $module PACKAGE = ${name}Ptr $prefix
1324
1325EOF
1326 my @items = @$struct;
1327 while (@items) {
1328 my $item = shift @items;
1329 if ($item->[0] =~ /_ANON/) {
32fb2b78 1330 if (defined $item->[2]) {
7c1d48a5 1331 push @items, map [
32fb2b78 1332 @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]",
7c1d48a5 1333 ], @{ $structs{$item->[0]} };
1334 } else {
1335 push @items, @{ $structs{$item->[0]} };
1336 }
1337 } else {
1338 my $type = normalize_type($item->[0]);
32fb2b78 1339 my $ttype = $structs{$type} ? normalize_type("$type *") : $type;
7c1d48a5 1340 print $fh <<"EOF";
32fb2b78 1341$ttype
1342$item->[2](THIS, __value = NO_INIT)
7c1d48a5 1343 $ptrname THIS
1344 $type __value
1345 PROTOTYPE: \$;\$
1346 CODE:
7c1d48a5 1347 if (items > 1)
1348 THIS->$item->[-1] = __value;
32fb2b78 1349 RETVAL = @{[
1350 $type eq $ttype ? "THIS->$item->[-1]" : "&(THIS->$item->[-1])"
1351 ]};
7c1d48a5 1352 OUTPUT:
1353 RETVAL
1354
1355EOF
1356 }
1357 }
1358}
1359
5273d82d 1360# Should be called before any actual call to normalize_type().
1361sub get_typemap {
1362 # We do not want to read ./typemap by obvios reasons.
1363 my @tm = qw(../../../typemap ../../typemap ../typemap);
1364 my $stdtypemap = "$Config::Config{privlib}/ExtUtils/typemap";
1365 unshift @tm, $stdtypemap;
1366 my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
ddf6bed1 1367
1368 # Start with useful default values
1369 $typemap{float} = 'T_DOUBLE';
1370
3cb4da91 1371 foreach my $typemap (@tm) {
5273d82d 1372 next unless -e $typemap ;
1373 # skip directories, binary files etc.
1374 warn " Scanning $typemap\n";
1375 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
1376 unless -T $typemap ;
1377 open(TYPEMAP, $typemap)
1378 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
1379 my $mode = 'Typemap';
1380 while (<TYPEMAP>) {
1381 next if /^\s*\#/;
1382 if (/^INPUT\s*$/) { $mode = 'Input'; next; }
1383 elsif (/^OUTPUT\s*$/) { $mode = 'Output'; next; }
1384 elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; }
1385 elsif ($mode eq 'Typemap') {
1386 next if /^\s*($|\#)/ ;
3cb4da91 1387 my ($type, $image);
ddf6bed1 1388 if ( ($type, $image) =
5273d82d 1389 /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o
1390 # This may reference undefined functions:
1391 and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) {
ddf6bed1 1392 $typemap{normalize_type($type)} = $image;
5273d82d 1393 }
1394 }
1395 }
1396 close(TYPEMAP) or die "Cannot close $typemap: $!";
1397 }
1398 %std_types = %types_seen;
1399 %types_seen = ();
1400}
1401
ead2a595 1402
ddf6bed1 1403sub normalize_type { # Second arg: do not strip const's before \*
ead2a595 1404 my $type = shift;
3cb4da91 1405 my $do_keep_deep_const = shift;
1406 # If $do_keep_deep_const this is heuristical only
1407 my $keep_deep_const = ($do_keep_deep_const ? '\b(?![^(,)]*\*)' : '');
ddf6bed1 1408 my $ignore_mods
3cb4da91 1409 = "(?:\\b(?:(?:__const__|const)$keep_deep_const|static|inline|__inline__)\\b\\s*)*";
1410 if ($do_keep_deep_const) { # Keep different compiled /RExen/o separately!
1411 $type =~ s/$ignore_mods//go;
7aff18a2 1412 }
1413 else {
3cb4da91 1414 $type =~ s/$ignore_mods//go;
1415 }
ddf6bed1 1416 $type =~ s/([^\s\w])/ \1 /g;
ead2a595 1417 $type =~ s/\s+$//;
1418 $type =~ s/^\s+//;
ddf6bed1 1419 $type =~ s/\s+/ /g;
1420 $type =~ s/\* (?=\*)/*/g;
1421 $type =~ s/\. \. \./.../g;
1422 $type =~ s/ ,/,/g;
5273d82d 1423 $types_seen{$type}++
1424 unless $type eq '...' or $type eq 'void' or $std_types{$type};
ead2a595 1425 $type;
1426}
1427
ddf6bed1 1428my $need_opaque;
1429
1430sub assign_typemap_entry {
1431 my $type = shift;
1432 my $otype = $type;
1433 my $entry;
1434 if ($tmask and $type =~ /$tmask/) {
1435 print "Type $type matches -o mask\n" if $opt_d;
1436 $entry = (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
1437 }
1438 elsif ($typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
1439 $type = normalize_type $type;
1440 print "Type mutation via typedefs: $otype ==> $type\n" if $opt_d;
1441 $entry = assign_typemap_entry($type);
1442 }
1443 $entry ||= $typemap{$otype}
1444 || (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
1445 $typemap{$otype} = $entry;
1446 $need_opaque = 1 if $entry eq "T_OPAQUE_STRUCT";
1447 return $entry;
1448}
1449
32fb2b78 1450for (@vdecls) {
1451 print_tievar_xsubs(\*XS, $_, $vdecl_hash{$_});
1452}
1453
ead2a595 1454if ($opt_x) {
32fb2b78 1455 for my $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) }
1456 if ($opt_a) {
1457 while (my($name, $struct) = each %structs) {
1458 print_accessors(\*XS, $name, $struct);
7c1d48a5 1459 }
32fb2b78 1460 }
ead2a595 1461}
1462
a0d0e21e 1463close XS;
5273d82d 1464
1465if (%types_seen) {
1466 my $type;
1467 warn "Writing $ext$modpname/typemap\n";
1468 open TM, ">typemap" or die "Cannot open typemap file for write: $!";
1469
3cb4da91 1470 for $type (sort keys %types_seen) {
ddf6bed1 1471 my $entry = assign_typemap_entry $type;
1472 print TM $type, "\t" x (5 - int((length $type)/8)), "\t$entry\n"
5273d82d 1473 }
1474
ddf6bed1 1475 print TM <<'EOP' if $need_opaque; # Older Perls do not have correct entry
1476#############################################################################
1477INPUT
1478T_OPAQUE_STRUCT
1479 if (sv_derived_from($arg, \"${ntype}\")) {
1480 STRLEN len;
1481 char *s = SvPV((SV*)SvRV($arg), len);
1482
1483 if (len != sizeof($var))
1484 croak(\"Size %d of packed data != expected %d\",
1485 len, sizeof($var));
1486 $var = *($type *)s;
1487 }
1488 else
1489 croak(\"$var is not of type ${ntype}\")
1490#############################################################################
1491OUTPUT
1492T_OPAQUE_STRUCT
1493 sv_setref_pvn($arg, \"${ntype}\", (char *)&$var, sizeof($var));
1494EOP
1495
5273d82d 1496 close TM or die "Cannot close typemap file for write: $!";
1497}
1498
2920c5d2 1499} # if( ! $opt_X )
e1666bf5 1500
8e07c86e 1501warn "Writing $ext$modpname/Makefile.PL\n";
1502open(PL, ">Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n";
a0d0e21e 1503
8bc03d0d 1504print PL <<END;
a0d0e21e 1505use ExtUtils::MakeMaker;
1506# See lib/ExtUtils/MakeMaker.pm for details of how to influence
42793c05 1507# the contents of the Makefile that is written.
8bc03d0d 1508WriteMakefile(
1509 'NAME' => '$module',
1510 'VERSION_FROM' => '$modfname.pm', # finds \$VERSION
1511 'PREREQ_PM' => {}, # e.g., Module::Name => 1.1
a0d0e21e 1512END
8bc03d0d 1513if (!$opt_X) { # print C stuff, unless XS is disabled
ddf6bed1 1514 $opt_F = '' unless defined $opt_F;
8bc03d0d 1515 print PL <<END;
1516 'LIBS' => ['$extralibs'], # e.g., '-lm'
1517 'DEFINE' => '$opt_F', # e.g., '-DHAVE_SOMETHING'
1518 'INC' => '', # e.g., '-I/usr/include/other'
1519END
2920c5d2 1520}
a0d0e21e 1521print PL ");\n";
f508c652 1522close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n";
1523
1524warn "Writing $ext$modpname/test.pl\n";
1525open(EX, ">test.pl") || die "Can't create $ext$modpname/test.pl: $!\n";
1526print EX <<'_END_';
1527# Before `make install' is performed this script should be runnable with
1528# `make test'. After `make install' it should work as `perl test.pl'
1529
1530######################### We start with some black magic to print on failure.
1531
1532# Change 1..1 below to 1..last_test_to_print .
1533# (It may become useful if the test is moved to ./t subdirectory.)
1534
5ae7f1db 1535BEGIN { $| = 1; print "1..1\n"; }
f508c652 1536END {print "not ok 1\n" unless $loaded;}
1537_END_
1538print EX <<_END_;
1539use $module;
1540_END_
1541print EX <<'_END_';
1542$loaded = 1;
1543print "ok 1\n";
1544
1545######################### End of black magic.
1546
1547# Insert your test code below (better if it prints "ok 13"
1548# (correspondingly "not ok 13") depending on the success of chunk 13
1549# of the test code):
e1666bf5 1550
f508c652 1551_END_
1552close(EX) || die "Can't close $ext$modpname/test.pl: $!\n";
a0d0e21e 1553
c0f8b9cd 1554unless ($opt_C) {
ddf6bed1 1555 warn "Writing $ext$modpname/Changes\n";
1556 $" = ' ';
1557 open(EX, ">Changes") || die "Can't create $ext$modpname/Changes: $!\n";
1558 @ARGS = map {/[\s\"\'\`\$*?^|&<>\[\]\{\}\(\)]/ ? "'$_'" : $_} @ARGS;
1559 print EX <<EOP;
1560Revision history for Perl extension $module.
1561
1562$TEMPLATE_VERSION @{[scalar localtime]}
1563\t- original version; created by h2xs $H2XS_VERSION with options
1564\t\t@ARGS
1565
1566EOP
1567 close(EX) || die "Can't close $ext$modpname/Changes: $!\n";
c0f8b9cd 1568}
c07a80fd 1569
1570warn "Writing $ext$modpname/MANIFEST\n";
5ae7f1db 1571open(MANI,'>MANIFEST') or die "Can't create MANIFEST: $!";
3cb4da91 1572my @files = <*>;
5ae7f1db 1573if (!@files) {
1574 eval {opendir(D,'.');};
1575 unless ($@) { @files = readdir(D); closedir(D); }
1576}
1577if (!@files) { @files = map {chomp && $_} `ls`; }
55497cff 1578if ($^O eq 'VMS') {
1579 foreach (@files) {
1580 # Clip trailing '.' for portability -- non-VMS OSs don't expect it
1581 s%\.$%%;
1582 # Fix up for case-sensitive file systems
1583 s/$modfname/$modfname/i && next;
1584 $_ = "\U$_" if $_ eq 'manifest' or $_ eq 'changes';
bbce6d69 1585 $_ = 'Makefile.PL' if $_ eq 'makefile.pl';
55497cff 1586 }
1587}
3e3baf6d 1588print MANI join("\n",@files), "\n";
5ae7f1db 1589close MANI;
40000a8c 1590!NO!SUBS!
4633a7c4 1591
1592close OUT or die "Can't close $file: $!";
1593chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
1594exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
8a5546a1 1595chdir $origdir;