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