This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Apply NetBSD patch-ae: another gcc sparc64 bug.
[perl5.git] / lib / ExtUtils / xsubpp
1 #!./miniperl
2
3 =head1 NAME
4
5 xsubpp - compiler to convert Perl XS code into C code
6
7 =head1 SYNOPSIS
8
9 B<xsubpp> [B<-v>] [B<-C++>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-nolinenumbers>] [B<-nooptimize>] [B<-typemap typemap>] ... file.xs
10
11 =head1 DESCRIPTION
12
13 This compiler is typically run by the makefiles created by L<ExtUtils::MakeMaker>.
14
15 I<xsubpp> will compile XS code into C code by embedding the constructs
16 necessary to let C functions manipulate Perl values and creates the glue
17 necessary to let Perl access those functions.  The compiler uses typemaps to
18 determine how to map C function parameters and variables to Perl values.
19
20 The compiler will search for typemap files called I<typemap>.  It will use
21 the following search path to find default typemaps, with the rightmost
22 typemap taking precedence.
23
24         ../../../typemap:../../typemap:../typemap:typemap
25
26 =head1 OPTIONS
27
28 Note that the C<XSOPT> MakeMaker option may be used to add these options to
29 any makefiles generated by MakeMaker.
30
31 =over 5
32
33 =item B<-C++>
34
35 Adds ``extern "C"'' to the C code.
36
37 =item B<-except>
38
39 Adds exception handling stubs to the C code.
40
41 =item B<-typemap typemap>
42
43 Indicates that a user-supplied typemap should take precedence over the
44 default typemaps.  This option may be used multiple times, with the last
45 typemap having the highest precedence.
46
47 =item B<-v>
48
49 Prints the I<xsubpp> version number to standard output, then exits.
50
51 =item B<-prototypes>
52
53 By default I<xsubpp> will not automatically generate prototype code for
54 all xsubs. This flag will enable prototypes.
55
56 =item B<-noversioncheck>
57
58 Disables the run time test that determines if the object file (derived
59 from the C<.xs> file) and the C<.pm> files have the same version
60 number.
61
62 =item B<-nolinenumbers>
63
64 Prevents the inclusion of `#line' directives in the output.
65
66 =item B<-nooptimize>
67
68 Disables certain optimizations.  The only optimization that is currently
69 affected is the use of I<target>s by the output C code (see L<perlguts>).
70 This may significantly slow down the generated code, but this is the way
71 B<xsubpp> of 5.005 and earlier operated.
72
73 =item B<-noinout>
74
75 Disable recognition of C<IN>, C<OUT_LIST> and C<INOUT_LIST> declarations.
76
77 =item B<-noargtypes>
78
79 Disable recognition of ANSI-like descriptions of function signature.
80
81 =back
82
83 =head1 ENVIRONMENT
84
85 No environment variables are used.
86
87 =head1 AUTHOR
88
89 Larry Wall
90
91 =head1 MODIFICATION HISTORY
92
93 See the file F<changes.pod>.
94
95 =head1 SEE ALSO
96
97 perl(1), perlxs(1), perlxstut(1)
98
99 =cut
100
101 require 5.002;
102 use Cwd;
103 use vars '$cplusplus';
104 use vars '%v';
105
106 use Config;
107
108 sub Q ;
109
110 # Global Constants
111
112 $XSUBPP_version = "1.9508";
113
114 my ($Is_VMS, $SymSet);
115 if ($^O eq 'VMS') {
116     $Is_VMS = 1;
117     # Establish set of global symbols with max length 28, since xsubpp
118     # will later add the 'XS_' prefix.
119     require ExtUtils::XSSymSet;
120     $SymSet = new ExtUtils::XSSymSet 28;
121 }
122
123 $FH = 'File0000' ;
124
125 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-noinout] [-noargtypes] [-s pattern] [-typemap typemap]... file.xs\n";
126
127 $proto_re = "[" . quotemeta('\$%&*@;[]') . "]" ;
128
129 $except = "";
130 $WantPrototypes = -1 ;
131 $WantVersionChk = 1 ;
132 $ProtoUsed = 0 ;
133 $WantLineNumbers = 1 ;
134 $WantOptimize = 1 ;
135
136 my $process_inout = 1;
137 my $process_argtypes = 1;
138
139 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
140     $flag = shift @ARGV;
141     $flag =~ s/^-// ;
142     $spat = quotemeta shift,    next SWITCH     if $flag eq 's';
143     $cplusplus = 1,     next SWITCH     if $flag eq 'C++';
144     $WantPrototypes = 0, next SWITCH    if $flag eq 'noprototypes';
145     $WantPrototypes = 1, next SWITCH    if $flag eq 'prototypes';
146     $WantVersionChk = 0, next SWITCH    if $flag eq 'noversioncheck';
147     $WantVersionChk = 1, next SWITCH    if $flag eq 'versioncheck';
148     # XXX left this in for compat
149     next SWITCH                         if $flag eq 'object_capi';
150     $except = " TRY",   next SWITCH     if $flag eq 'except';
151     push(@tm,shift),    next SWITCH     if $flag eq 'typemap';
152     $WantLineNumbers = 0, next SWITCH   if $flag eq 'nolinenumbers';
153     $WantLineNumbers = 1, next SWITCH   if $flag eq 'linenumbers';
154     $WantOptimize = 0, next SWITCH      if $flag eq 'nooptimize';
155     $WantOptimize = 1, next SWITCH      if $flag eq 'optimize';
156     $process_inout = 0, next SWITCH     if $flag eq 'noinout';
157     $process_inout = 1, next SWITCH     if $flag eq 'inout';
158     $process_argtypes = 0, next SWITCH  if $flag eq 'noargtypes';
159     $process_argtypes = 1, next SWITCH  if $flag eq 'argtypes';
160     (print "xsubpp version $XSUBPP_version\n"), exit
161         if $flag eq 'v';
162     die $usage;
163 }
164 if ($WantPrototypes == -1)
165   { $WantPrototypes = 0}
166 else
167   { $ProtoUsed = 1 }
168
169
170 @ARGV == 1 or die $usage;
171 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
172         or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
173         or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
174         or ($dir, $filename) = ('.', $ARGV[0]);
175 chdir($dir);
176 $pwd = cwd();
177
178 ++ $IncludedFiles{$ARGV[0]} ;
179
180 my(@XSStack) = ({type => 'none'});      # Stack of conditionals and INCLUDEs
181 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
182
183
184 sub TrimWhitespace
185 {
186     $_[0] =~ s/^\s+|\s+$//go ;
187 }
188
189 sub TidyType
190 {
191     local ($_) = @_ ;
192
193     # rationalise any '*' by joining them into bunches and removing whitespace
194     s#\s*(\*+)\s*#$1#g;
195     s#(\*+)# $1 #g ;
196
197     # change multiple whitespace into a single space
198     s/\s+/ /g ;
199     
200     # trim leading & trailing whitespace
201     TrimWhitespace($_) ;
202
203     $_ ;
204 }
205
206 $typemap = shift @ARGV;
207 foreach $typemap (@tm) {
208     die "Can't find $typemap in $pwd\n" unless -r $typemap;
209 }
210 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
211                 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
212                 ../typemap typemap);
213 foreach $typemap (@tm) {
214     next unless -f $typemap ;
215     # skip directories, binary files etc.
216     warn("Warning: ignoring non-text typemap file '$typemap'\n"), next 
217         unless -T $typemap ;
218     open(TYPEMAP, $typemap) 
219         or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
220     $mode = 'Typemap';
221     $junk = "" ;
222     $current = \$junk;
223     while (<TYPEMAP>) {
224         next if /^\s*#/;
225         my $line_no = $. + 1; 
226         if (/^INPUT\s*$/)   { $mode = 'Input';   $current = \$junk;  next; }
227         if (/^OUTPUT\s*$/)  { $mode = 'Output';  $current = \$junk;  next; }
228         if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk;  next; }
229         if ($mode eq 'Typemap') {
230             chomp;
231             my $line = $_ ;
232             TrimWhitespace($_) ;
233             # skip blank lines and comment lines
234             next if /^$/ or /^#/ ;
235             my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
236                 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
237             $type = TidyType($type) ;
238             $type_kind{$type} = $kind ;
239             # prototype defaults to '$'
240             $proto = "\$" unless $proto ;
241             warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n") 
242                 unless ValidProtoString($proto) ;
243             $proto_letter{$type} = C_string($proto) ;
244         }
245         elsif (/^\s/) {
246             $$current .= $_;
247         }
248         elsif ($mode eq 'Input') {
249             s/\s+$//;
250             $input_expr{$_} = '';
251             $current = \$input_expr{$_};
252         }
253         else {
254             s/\s+$//;
255             $output_expr{$_} = '';
256             $current = \$output_expr{$_};
257         }
258     }
259     close(TYPEMAP);
260 }
261
262 foreach $key (keys %input_expr) {
263     $input_expr{$key} =~ s/\n+$//;
264 }
265
266 $bal = qr[(?:(?>[^()]+)|\((??{ $bal })\))*];    # ()-balanced
267 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?];          # Optional (SV*) cast
268 $size = qr[,\s* (??{ $bal }) ]x;                # Third arg (to setpvn)
269
270 foreach $key (keys %output_expr) {
271     use re 'eval';
272
273     my ($t, $with_size, $arg, $sarg) =
274       ($output_expr{$key} =~
275          m[^ \s+ sv_set ( [iunp] ) v (n)?       # Type, is_setpvn
276              \s* \( \s* $cast \$arg \s* ,
277              \s* ( (??{ $bal }) )               # Set from
278              ( (??{ $size }) )?                 # Possible sizeof set-from
279              \) \s* ; \s* $
280           ]x);
281     $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
282 }
283
284 $END = "!End!\n\n";             # "impossible" keyword (multiple newline)
285
286 # Match an XS keyword
287 $BLOCK_re= '\s*(' . join('|', qw(
288         REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT 
289         CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
290         SCOPE INTERFACE INTERFACE_MACRO C_ARGS POSTCALL
291         )) . "|$END)\\s*:";
292
293 # Input:  ($_, @line) == unparsed input.
294 # Output: ($_, @line) == (rest of line, following lines).
295 # Return: the matched keyword if found, otherwise 0
296 sub check_keyword {
297         $_ = shift(@line) while !/\S/ && @line;
298         s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
299 }
300
301 my ($C_group_rex, $C_arg);
302 # Group in C (no support for comments or literals)
303 $C_group_rex = qr/ [({\[]
304                    (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
305                    [)}\]] /x ;
306 # Chunk in C without comma at toplevel (no comments):
307 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
308              |   (??{ $C_group_rex })
309              |   " (?: (?> [^\\"]+ )
310                    |   \\.
311                    )* "         # String literal
312              |   ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
313              )* /xs;
314
315 if ($WantLineNumbers) {
316     {
317         package xsubpp::counter;
318         sub TIEHANDLE {
319             my ($class, $cfile) = @_;
320             my $buf = "";
321             $SECTION_END_MARKER = "#line --- \"$cfile\"";
322             $line_no = 1;
323             bless \$buf;
324         }
325
326         sub PRINT {
327             my $self = shift;
328             for (@_) {
329                 $$self .= $_;
330                 while ($$self =~ s/^([^\n]*\n)//) {
331                     my $line = $1;
332                     ++ $line_no;
333                     $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
334                     print STDOUT $line;
335                 }
336             }
337         }
338
339         sub PRINTF {
340             my $self = shift;
341             my $fmt = shift;
342             $self->PRINT(sprintf($fmt, @_));
343         }
344
345         sub DESTROY {
346             # Not necessary if we're careful to end with a "\n"
347             my $self = shift;
348             print STDOUT $$self;
349         }
350     }
351
352     my $cfile = $filename;
353     $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
354     tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
355     select PSEUDO_STDOUT;
356 }
357
358 sub print_section {
359     # the "do" is required for right semantics
360     do { $_ = shift(@line) } while !/\S/ && @line;
361     
362     print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
363         if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
364     for (;  defined($_) && !/^$BLOCK_re/o;  $_ = shift(@line)) {
365         print "$_\n";
366     }
367     print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
368 }
369
370 sub merge_section {
371     my $in = '';
372   
373     while (!/\S/ && @line) {
374         $_ = shift(@line);
375     }
376     
377     for (;  defined($_) && !/^$BLOCK_re/o;  $_ = shift(@line)) {
378         $in .= "$_\n";
379     }
380     chomp $in;
381     return $in;
382 }
383
384 sub process_keyword($)
385 {
386     my($pattern) = @_ ;
387     my $kwd ;
388
389     &{"${kwd}_handler"}() 
390         while $kwd = check_keyword($pattern) ;
391 }
392
393 sub CASE_handler {
394     blurt ("Error: `CASE:' after unconditional `CASE:'")
395         if $condnum && $cond eq '';
396     $cond = $_;
397     TrimWhitespace($cond);
398     print "   ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
399     $_ = '' ;
400 }
401
402 sub INPUT_handler {
403     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
404         last if /^\s*NOT_IMPLEMENTED_YET/;
405         next unless /\S/;       # skip blank lines 
406
407         TrimWhitespace($_) ;
408         my $line = $_ ;
409
410         # remove trailing semicolon if no initialisation
411         s/\s*;$//g unless /[=;+].*\S/ ;
412
413         # check for optional initialisation code
414         my $var_init = '' ;
415         $var_init = $1 if s/\s*([=;+].*)$//s ;
416         $var_init =~ s/"/\\"/g;
417
418         s/\s+/ /g;
419         my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
420             or blurt("Error: invalid argument declaration '$line'"), next;
421
422         # Check for duplicate definitions
423         blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
424             if $arg_list{$var_name}++ 
425               or defined $arg_types{$var_name} and not $processing_arg_with_types;
426
427         $thisdone |= $var_name eq "THIS";
428         $retvaldone |= $var_name eq "RETVAL";
429         $var_types{$var_name} = $var_type;
430         # XXXX This check is a safeguard against the unfinished conversion of
431         # generate_init().  When generate_init() is fixed,
432         # one can use 2-args map_type() unconditionally.
433         if ($var_type =~ / \( \s* \* \s* \) /x) {
434           # Function pointers are not yet supported with &output_init!
435           print "\t" . &map_type($var_type, $var_name);
436           $name_printed = 1;
437         } else {
438           print "\t" . &map_type($var_type);
439           $name_printed = 0;
440         }
441         $var_num = $args_match{$var_name};
442
443         $proto_arg[$var_num] = ProtoString($var_type) 
444             if $var_num ;
445         $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
446         if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
447             or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
448             and $var_init !~ /\S/) {
449           if ($name_printed) {
450             print ";\n";
451           } else {
452             print "\t$var_name;\n";
453           }
454         } elsif ($var_init =~ /\S/) {
455             &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
456         } elsif ($var_num) {
457             # generate initialization code
458             &generate_init($var_type, $var_num, $var_name, $name_printed);
459         } else {
460             print ";\n";
461         }
462     }
463 }
464
465 sub OUTPUT_handler {
466     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
467         next unless /\S/;
468         if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
469             $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
470             next;
471         }
472         my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
473         blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
474             if $outargs{$outarg} ++ ;
475         if (!$gotRETVAL and $outarg eq 'RETVAL') {
476             # deal with RETVAL last
477             $RETVAL_code = $outcode ;
478             $gotRETVAL = 1 ;
479             next ;
480         }
481         blurt ("Error: OUTPUT $outarg not an argument"), next
482             unless defined($args_match{$outarg});
483         blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
484             unless defined $var_types{$outarg} ;
485         $var_num = $args_match{$outarg};
486         if ($outcode) {
487             print "\t$outcode\n";
488             print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
489         } else {
490             &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
491         }
492         delete $in_out{$outarg}         # No need to auto-OUTPUT 
493           if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
494     }
495 }
496
497 sub C_ARGS_handler() {
498     my $in = merge_section();
499   
500     TrimWhitespace($in);
501     $func_args = $in;
502
503
504 sub INTERFACE_MACRO_handler() {
505     my $in = merge_section();
506   
507     TrimWhitespace($in);
508     if ($in =~ /\s/) {          # two
509         ($interface_macro, $interface_macro_set) = split ' ', $in;
510     } else {
511         $interface_macro = $in;
512         $interface_macro_set = 'UNKNOWN_CVT'; # catch later
513     }
514     $interface = 1;             # local
515     $Interfaces = 1;            # global
516 }
517
518 sub INTERFACE_handler() {
519     my $in = merge_section();
520   
521     TrimWhitespace($in);
522     
523     foreach (split /[\s,]+/, $in) {
524         $Interfaces{$_} = $_;
525     }
526     print Q<<"EOF";
527 #       XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
528 EOF
529     $interface = 1;             # local
530     $Interfaces = 1;            # global
531 }
532
533 sub CLEANUP_handler() { print_section() } 
534 sub PREINIT_handler() { print_section() } 
535 sub POSTCALL_handler() { print_section() } 
536 sub INIT_handler()    { print_section() } 
537
538 sub GetAliases
539 {
540     my ($line) = @_ ;
541     my ($orig) = $line ;
542     my ($alias) ;
543     my ($value) ;
544
545     # Parse alias definitions
546     # format is
547     #    alias = value alias = value ...
548
549     while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
550         $alias = $1 ;
551         $orig_alias = $alias ;
552         $value = $2 ;
553
554         # check for optional package definition in the alias
555         $alias = $Packprefix . $alias if $alias !~ /::/ ;
556         
557         # check for duplicate alias name & duplicate value
558         Warn("Warning: Ignoring duplicate alias '$orig_alias'")
559             if defined $XsubAliases{$alias} ;
560
561         Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
562             if $XsubAliasValues{$value} ;
563
564         $XsubAliases = 1;
565         $XsubAliases{$alias} = $value ;
566         $XsubAliasValues{$value} = $orig_alias ;
567     }
568
569     blurt("Error: Cannot parse ALIAS definitions from '$orig'")
570         if $line ;
571 }
572
573 sub ATTRS_handler ()
574 {
575     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
576         next unless /\S/;
577         TrimWhitespace($_) ;
578         push @Attributes, $_;
579     }
580 }
581
582 sub ALIAS_handler ()
583 {
584     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
585         next unless /\S/;
586         TrimWhitespace($_) ;
587         GetAliases($_) if $_ ;
588     }
589 }
590
591 sub REQUIRE_handler ()
592 {
593     # the rest of the current line should contain a version number
594     my ($Ver) = $_ ;
595
596     TrimWhitespace($Ver) ;
597
598     death ("Error: REQUIRE expects a version number")
599         unless $Ver ;
600
601     # check that the version number is of the form n.n
602     death ("Error: REQUIRE: expected a number, got '$Ver'")
603         unless $Ver =~ /^\d+(\.\d*)?/ ;
604
605     death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
606         unless $XSUBPP_version >= $Ver ; 
607 }
608
609 sub VERSIONCHECK_handler ()
610 {
611     # the rest of the current line should contain either ENABLE or
612     # DISABLE
613  
614     TrimWhitespace($_) ;
615  
616     # check for ENABLE/DISABLE
617     death ("Error: VERSIONCHECK: ENABLE/DISABLE")
618         unless /^(ENABLE|DISABLE)/i ;
619  
620     $WantVersionChk = 1 if $1 eq 'ENABLE' ;
621     $WantVersionChk = 0 if $1 eq 'DISABLE' ;
622  
623 }
624
625 sub PROTOTYPE_handler ()
626 {
627     my $specified ;
628
629     death("Error: Only 1 PROTOTYPE definition allowed per xsub") 
630         if $proto_in_this_xsub ++ ;
631
632     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
633         next unless /\S/;
634         $specified = 1 ;
635         TrimWhitespace($_) ;
636         if ($_ eq 'DISABLE') {
637            $ProtoThisXSUB = 0 
638         }
639         elsif ($_ eq 'ENABLE') {
640            $ProtoThisXSUB = 1 
641         }
642         else {
643             # remove any whitespace
644             s/\s+//g ;
645             death("Error: Invalid prototype '$_'")
646                 unless ValidProtoString($_) ;
647             $ProtoThisXSUB = C_string($_) ;
648         }
649     }
650
651     # If no prototype specified, then assume empty prototype ""
652     $ProtoThisXSUB = 2 unless $specified ;
653
654     $ProtoUsed = 1 ;
655
656 }
657
658 sub SCOPE_handler ()
659 {
660     death("Error: Only 1 SCOPE declaration allowed per xsub") 
661         if $scope_in_this_xsub ++ ;
662
663     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
664                 next unless /\S/;
665                 TrimWhitespace($_) ;
666         if ($_ =~ /^DISABLE/i) {
667                    $ScopeThisXSUB = 0 
668         }
669         elsif ($_ =~ /^ENABLE/i) {
670                    $ScopeThisXSUB = 1 
671         }
672     }
673
674 }
675
676 sub PROTOTYPES_handler ()
677 {
678     # the rest of the current line should contain either ENABLE or
679     # DISABLE 
680
681     TrimWhitespace($_) ;
682
683     # check for ENABLE/DISABLE
684     death ("Error: PROTOTYPES: ENABLE/DISABLE")
685         unless /^(ENABLE|DISABLE)/i ;
686
687     $WantPrototypes = 1 if $1 eq 'ENABLE' ;
688     $WantPrototypes = 0 if $1 eq 'DISABLE' ;
689     $ProtoUsed = 1 ;
690
691 }
692
693 sub INCLUDE_handler ()
694 {
695     # the rest of the current line should contain a valid filename
696  
697     TrimWhitespace($_) ;
698  
699     death("INCLUDE: filename missing")
700         unless $_ ;
701
702     death("INCLUDE: output pipe is illegal")
703         if /^\s*\|/ ;
704
705     # simple minded recursion detector
706     death("INCLUDE loop detected")
707         if $IncludedFiles{$_} ;
708
709     ++ $IncludedFiles{$_} unless /\|\s*$/ ;
710
711     # Save the current file context.
712     push(@XSStack, {
713         type            => 'file',
714         LastLine        => $lastline,
715         LastLineNo      => $lastline_no,
716         Line            => \@line,
717         LineNo          => \@line_no,
718         Filename        => $filename,
719         Handle          => $FH,
720         }) ;
721  
722     ++ $FH ;
723
724     # open the new file
725     open ($FH, "$_") or death("Cannot open '$_': $!") ;
726  
727     print Q<<"EOF" ;
728 #
729 #/* INCLUDE:  Including '$_' from '$filename' */
730 #
731 EOF
732
733     $filename = $_ ;
734
735     # Prime the pump by reading the first 
736     # non-blank line
737
738     # skip leading blank lines
739     while (<$FH>) {
740         last unless /^\s*$/ ;
741     }
742
743     $lastline = $_ ;
744     $lastline_no = $. ;
745  
746 }
747  
748 sub PopFile()
749 {
750     return 0 unless $XSStack[-1]{type} eq 'file' ;
751
752     my $data     = pop @XSStack ;
753     my $ThisFile = $filename ;
754     my $isPipe   = ($filename =~ /\|\s*$/) ;
755  
756     -- $IncludedFiles{$filename}
757         unless $isPipe ;
758
759     close $FH ;
760
761     $FH         = $data->{Handle} ;
762     $filename   = $data->{Filename} ;
763     $lastline   = $data->{LastLine} ;
764     $lastline_no = $data->{LastLineNo} ;
765     @line       = @{ $data->{Line} } ;
766     @line_no    = @{ $data->{LineNo} } ;
767
768     if ($isPipe and $? ) {
769         -- $lastline_no ;
770         print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n"  ;
771         exit 1 ;
772     }
773
774     print Q<<"EOF" ;
775 #
776 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
777 #
778 EOF
779
780     return 1 ;
781 }
782
783 sub ValidProtoString ($)
784 {
785     my($string) = @_ ;
786
787     if ( $string =~ /^$proto_re+$/ ) {
788         return $string ;
789     }
790
791     return 0 ;
792 }
793
794 sub C_string ($)
795 {
796     my($string) = @_ ;
797
798     $string =~ s[\\][\\\\]g ;
799     $string ;
800 }
801
802 sub ProtoString ($)
803 {
804     my ($type) = @_ ;
805
806     $proto_letter{$type} or "\$" ;
807 }
808
809 sub check_cpp {
810     my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
811     if (@cpp) {
812         my ($cpp, $cpplevel);
813         for $cpp (@cpp) {
814             if ($cpp =~ /^\#\s*if/) {
815                 $cpplevel++;
816             } elsif (!$cpplevel) {
817                 Warn("Warning: #else/elif/endif without #if in this function");
818                 print STDERR "    (precede it with a blank line if the matching #if is outside the function)\n"
819                     if $XSStack[-1]{type} eq 'if';
820                 return;
821             } elsif ($cpp =~ /^\#\s*endif/) {
822                 $cpplevel--;
823             }
824         }
825         Warn("Warning: #if without #endif in this function") if $cpplevel;
826     }
827 }
828
829
830 sub Q {
831     my($text) = @_;
832     $text =~ s/^#//gm;
833     $text =~ s/\[\[/{/g;
834     $text =~ s/\]\]/}/g;
835     $text;
836 }
837
838 open($FH, $filename) or die "cannot open $filename: $!\n";
839
840 # Identify the version of xsubpp used
841 print <<EOM ;
842 /*
843  * This file was generated automatically by xsubpp version $XSUBPP_version from the 
844  * contents of $filename. Do not edit this file, edit $filename instead.
845  *
846  *      ANY CHANGES MADE HERE WILL BE LOST! 
847  *
848  */
849
850 EOM
851  
852
853 print("#line 1 \"$filename\"\n")
854     if $WantLineNumbers;
855
856 firstmodule:
857 while (<$FH>) {
858     if (/^=/) {
859         my $podstartline = $.;
860         do {
861             if (/^=cut\s*$/) {
862                 print("/* Skipped embedded POD. */\n");
863                 printf("#line %d \"$filename\"\n", $. + 1)
864                   if $WantLineNumbers;
865                 next firstmodule
866             }
867
868         } while (<$FH>);
869         # At this point $. is at end of file so die won't state the start
870         # of the problem, and as we haven't yet read any lines &death won't
871         # show the correct line in the message either.
872         die ("Error: Unterminated pod in $filename, line $podstartline\n")
873           unless $lastline;
874     }
875     last if ($Module, $Package, $Prefix) =
876         /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
877
878     print $_;
879 }
880 &Exit unless defined $_;
881
882 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
883
884 $lastline    = $_;
885 $lastline_no = $.;
886
887 # Read next xsub into @line from ($lastline, <$FH>).
888 sub fetch_para {
889     # parse paragraph
890     death ("Error: Unterminated `#if/#ifdef/#ifndef'")
891         if !defined $lastline && $XSStack[-1]{type} eq 'if';
892     @line = ();
893     @line_no = () ;
894     return PopFile() if !defined $lastline;
895
896     if ($lastline =~
897         /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
898         $Module = $1;
899         $Package = defined($2) ? $2 : '';       # keep -w happy
900         $Prefix  = defined($3) ? $3 : '';       # keep -w happy
901         $Prefix = quotemeta $Prefix ;
902         ($Module_cname = $Module) =~ s/\W/_/g;
903         ($Packid = $Package) =~ tr/:/_/;
904         $Packprefix = $Package;
905         $Packprefix .= "::" if $Packprefix ne "";
906         $lastline = "";
907     }
908
909     for(;;) {
910         # Skip embedded PODs 
911         while ($lastline =~ /^=/) {
912             while ($lastline = <$FH>) {
913                 last if ($lastline =~ /^=cut\s*$/);
914             }
915             death ("Error: Unterminated pod") unless $lastline;
916             $lastline = <$FH>;
917             chomp $lastline;
918             $lastline =~ s/^\s+$//;
919         }
920         if ($lastline !~ /^\s*#/ ||
921             # CPP directives:
922             #   ANSI:   if ifdef ifndef elif else endif define undef
923             #           line error pragma
924             #   gcc:    warning include_next
925             #   obj-c:  import
926             #   others: ident (gcc notes that some cpps have this one)
927             $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
928             last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
929             push(@line, $lastline);
930             push(@line_no, $lastline_no) ;
931         }
932
933         # Read next line and continuation lines
934         last unless defined($lastline = <$FH>);
935         $lastline_no = $.;
936         my $tmp_line;
937         $lastline .= $tmp_line
938             while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
939
940         chomp $lastline;
941         $lastline =~ s/^\s+$//;
942     }
943     pop(@line), pop(@line_no) while @line && $line[-1] eq "";
944     1;
945 }
946
947 PARAGRAPH:
948 while (fetch_para()) {
949     # Print initial preprocessor statements and blank lines
950     while (@line && $line[0] !~ /^[^\#]/) {
951         my $line = shift(@line);
952         print $line, "\n";
953         next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
954         my $statement = $+;
955         if ($statement eq 'if') {
956             $XSS_work_idx = @XSStack;
957             push(@XSStack, {type => 'if'});
958         } else {
959             death ("Error: `$statement' with no matching `if'")
960                 if $XSStack[-1]{type} ne 'if';
961             if ($XSStack[-1]{varname}) {
962                 push(@InitFileCode, "#endif\n");
963                 push(@BootCode,     "#endif");
964             }
965
966             my(@fns) = keys %{$XSStack[-1]{functions}};
967             if ($statement ne 'endif') {
968                 # Hide the functions defined in other #if branches, and reset.
969                 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
970                 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
971             } else {
972                 my($tmp) = pop(@XSStack);
973                 0 while (--$XSS_work_idx
974                          && $XSStack[$XSS_work_idx]{type} ne 'if');
975                 # Keep all new defined functions
976                 push(@fns, keys %{$tmp->{other_functions}});
977                 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
978             }
979         }
980     }
981
982     next PARAGRAPH unless @line;
983
984     if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
985         # We are inside an #if, but have not yet #defined its xsubpp variable.
986         print "#define $cpp_next_tmp 1\n\n";
987         push(@InitFileCode, "#if $cpp_next_tmp\n");
988         push(@BootCode,     "#if $cpp_next_tmp");
989         $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
990     }
991
992     death ("Code is not inside a function"
993            ." (maybe last function was ended by a blank line "
994            ." followed by a statement on column one?)")
995         if $line[0] =~ /^\s/;
996
997     # initialize info arrays
998     undef(%args_match);
999     undef(%var_types);
1000     undef(%defaults);
1001     undef($class);
1002     undef($static);
1003     undef($elipsis);
1004     undef($wantRETVAL) ;
1005     undef($RETVAL_no_return) ;
1006     undef(%arg_list) ;
1007     undef(@proto_arg) ;
1008     undef(@arg_with_types) ;
1009     undef($processing_arg_with_types) ;
1010     undef(%arg_types) ;
1011     undef(@outlist) ;
1012     undef(%in_out) ;
1013     undef($proto_in_this_xsub) ;
1014     undef($scope_in_this_xsub) ;
1015     undef($interface);
1016     undef($prepush_done);
1017     $interface_macro = 'XSINTERFACE_FUNC' ;
1018     $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
1019     $ProtoThisXSUB = $WantPrototypes ;
1020     $ScopeThisXSUB = 0;
1021     $xsreturn = 0;
1022
1023     $_ = shift(@line);
1024     while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
1025         &{"${kwd}_handler"}() ;
1026         next PARAGRAPH unless @line ;
1027         $_ = shift(@line);
1028     }
1029
1030     if (check_keyword("BOOT")) {
1031         &check_cpp;
1032         push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
1033           if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
1034         push (@BootCode, @line, "") ;
1035         next PARAGRAPH ;
1036     }
1037
1038
1039     # extract return type, function name and arguments
1040     ($ret_type) = TidyType($_);
1041     $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
1042
1043     # Allow one-line ANSI-like declaration
1044     unshift @line, $2
1045       if $process_argtypes
1046         and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
1047
1048     # a function definition needs at least 2 lines
1049     blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
1050         unless @line ;
1051
1052     $static = 1 if $ret_type =~ s/^static\s+//;
1053
1054     $func_header = shift(@line);
1055     blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
1056         unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
1057
1058     ($class, $func_name, $orig_args) =  ($1, $2, $3) ;
1059     $class = "$4 $class" if $4;
1060     ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
1061     ($clean_func_name = $func_name) =~ s/^$Prefix//;
1062     $Full_func_name = "${Packid}_$clean_func_name";
1063     if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
1064
1065     # Check for duplicate function definition
1066     for $tmp (@XSStack) {
1067         next unless defined $tmp->{functions}{$Full_func_name};
1068         Warn("Warning: duplicate function definition '$clean_func_name' detected");
1069         last;
1070     }
1071     $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
1072     %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
1073     $DoSetMagic = 1;
1074
1075     $orig_args =~ s/\\\s*/ /g;          # process line continuations
1076
1077     my %only_outlist;
1078     if ($process_argtypes and $orig_args =~ /\S/) {
1079         my $args = "$orig_args ,";
1080         if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
1081             @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
1082             for ( @args ) {
1083                 s/^\s+//;
1084                 s/\s+$//;
1085                 my $arg = $_;
1086                 my $default;
1087                 ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
1088                 my ($pre, $name) = ($arg =~ /(.*?) \s* \b(\w+) \s* $ /x);
1089                 next unless length $pre;
1090                 my $out_type;
1091                 my $inout_var;
1092                 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//) {
1093                     my $type = $1;
1094                     $out_type = $type if $type ne 'IN';
1095                     $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1096                 }
1097                 if (/\W/) {     # Has a type
1098                     push @arg_with_types, $arg;
1099                     # warn "pushing '$arg'\n";
1100                     $arg_types{$name} = $arg;
1101                     $_ = "$name$default";
1102                 }
1103                 $only_outlist{$_} = 1 if $out_type eq "OUTLIST";
1104                 push @outlist, $name if $out_type =~ /OUTLIST$/;
1105                 $in_out{$name} = $out_type if $out_type;
1106             }
1107         } else {
1108             @args = split(/\s*,\s*/, $orig_args);
1109             Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
1110         }
1111     } else {
1112         @args = split(/\s*,\s*/, $orig_args);
1113         for (@args) {
1114             if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\s+//) {
1115                 my $out_type = $1;
1116                 next if $out_type eq 'IN';
1117                 $only_outlist{$_} = 1 if $out_type eq "OUTLIST";
1118                 push @outlist, $name if $out_type =~ /OUTLIST$/;
1119                 $in_out{$_} = $out_type;
1120             }
1121         }
1122     }
1123     if (defined($class)) {
1124         my $arg0 = ((defined($static) or $func_name eq 'new')
1125                     ? "CLASS" : "THIS");
1126         unshift(@args, $arg0);
1127         ($report_args = "$arg0, $report_args") =~ s/^\w+, $/$arg0/;
1128     }
1129     my $extra_args = 0;
1130     @args_num = ();
1131     $num_args = 0;
1132     my $report_args = '';
1133     foreach $i (0 .. $#args) {
1134             if ($args[$i] =~ s/\.\.\.//) {
1135                     $elipsis = 1;
1136                     if ($args[$i] eq '' && $i == $#args) {
1137                         $report_args .= ", ...";
1138                         pop(@args);
1139                         last;
1140                     }
1141             }
1142             if ($only_outlist{$args[$i]}) {
1143                 push @args_num, undef;
1144             } else {
1145                 push @args_num, ++$num_args;
1146                 $report_args .= ", $args[$i]";
1147             }
1148             if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
1149                     $extra_args++;
1150                     $args[$i] = $1;
1151                     $defaults{$args[$i]} = $2;
1152                     $defaults{$args[$i]} =~ s/"/\\"/g;
1153             }
1154             $proto_arg[$i+1] = "\$" ;
1155     }
1156     $min_args = $num_args - $extra_args;
1157     $report_args =~ s/"/\\"/g;
1158     $report_args =~ s/^,\s+//;
1159     my @func_args = @args;
1160     shift @func_args if defined($class);
1161
1162     for (@func_args) {
1163         s/^/&/ if $in_out{$_};
1164     }
1165     $func_args = join(", ", @func_args);
1166     @args_match{@args} = @args_num;
1167
1168     $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
1169     $CODE = grep(/^\s*CODE\s*:/, @line);
1170     # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
1171     #   to set explicit return values.
1172     $EXPLICIT_RETURN = ($CODE &&
1173                 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
1174     $ALIAS  = grep(/^\s*ALIAS\s*:/,  @line);
1175     $INTERFACE  = grep(/^\s*INTERFACE\s*:/,  @line);
1176
1177     $xsreturn = 1 if $EXPLICIT_RETURN;
1178
1179     # print function header
1180     print Q<<"EOF";
1181 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
1182 #XS(XS_${Full_func_name})
1183 #[[
1184 #    dXSARGS;
1185 EOF
1186     print Q<<"EOF" if $ALIAS ;
1187 #    dXSI32;
1188 EOF
1189     print Q<<"EOF" if $INTERFACE ;
1190 #    dXSFUNCTION($ret_type);
1191 EOF
1192     if ($elipsis) {
1193         $cond = ($min_args ? qq(items < $min_args) : 0);
1194     }
1195     elsif ($min_args == $num_args) {
1196         $cond = qq(items != $min_args);
1197     }
1198     else {
1199         $cond = qq(items < $min_args || items > $num_args);
1200     }
1201
1202     print Q<<"EOF" if $except;
1203 #    char errbuf[1024];
1204 #    *errbuf = '\0';
1205 EOF
1206
1207     if ($ALIAS) 
1208       { print Q<<"EOF" if $cond }
1209 #    if ($cond)
1210 #       Perl_croak(aTHX_ "Usage: %s($report_args)", GvNAME(CvGV(cv)));
1211 EOF
1212     else 
1213       { print Q<<"EOF" if $cond }
1214 #    if ($cond)
1215 #       Perl_croak(aTHX_ "Usage: $pname($report_args)");
1216 EOF
1217
1218     #gcc -Wall: if an xsub has no arguments and PPCODE is used
1219     #it is likely none of ST, XSRETURN or XSprePUSH macros are used
1220     #hence `ax' (setup by dXSARGS) is unused
1221     #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
1222     #but such a move could break third-party extensions
1223     print Q<<"EOF" if $PPCODE and $num_args == 0;
1224 #   PERL_UNUSED_VAR(ax); /* -Wall */
1225 EOF
1226
1227     print Q<<"EOF" if $PPCODE;
1228 #    SP -= items;
1229 EOF
1230
1231     # Now do a block of some sort.
1232
1233     $condnum = 0;
1234     $cond = '';                 # last CASE: condidional
1235     push(@line, "$END:");
1236     push(@line_no, $line_no[-1]);
1237     $_ = '';
1238     &check_cpp;
1239     while (@line) {
1240         &CASE_handler if check_keyword("CASE");
1241         print Q<<"EOF";
1242 #   $except [[
1243 EOF
1244
1245         # do initialization of input variables
1246         $thisdone = 0;
1247         $retvaldone = 0;
1248         $deferred = "";
1249         %arg_list = () ;
1250         $gotRETVAL = 0;
1251
1252         INPUT_handler() ;
1253         process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE") ;
1254
1255         print Q<<"EOF" if $ScopeThisXSUB;
1256 #   ENTER;
1257 #   [[
1258 EOF
1259         
1260         if (!$thisdone && defined($class)) {
1261             if (defined($static) or $func_name eq 'new') {
1262                 print "\tchar *";
1263                 $var_types{"CLASS"} = "char *";
1264                 &generate_init("char *", 1, "CLASS");
1265             }
1266             else {
1267                 print "\t$class *";
1268                 $var_types{"THIS"} = "$class *";
1269                 &generate_init("$class *", 1, "THIS");
1270             }
1271         }
1272
1273         # do code
1274         if (/^\s*NOT_IMPLEMENTED_YET/) {
1275                 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1276                 $_ = '' ;
1277         } else {
1278                 if ($ret_type ne "void") {
1279                         print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
1280                                 if !$retvaldone;
1281                         $args_match{"RETVAL"} = 0;
1282                         $var_types{"RETVAL"} = $ret_type;
1283                         print "\tdXSTARG;\n"
1284                                 if $WantOptimize and $targetable{$type_kind{$ret_type}};
1285                 }
1286
1287                 if (@arg_with_types) {
1288                     unshift @line, @arg_with_types, $_;
1289                     $_ = "";
1290                     $processing_arg_with_types = 1;
1291                     INPUT_handler() ;
1292                 }
1293                 print $deferred;
1294
1295         process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
1296
1297                 if (check_keyword("PPCODE")) {
1298                         print_section();
1299                         death ("PPCODE must be last thing") if @line;
1300                         print "\tLEAVE;\n" if $ScopeThisXSUB;
1301                         print "\tPUTBACK;\n\treturn;\n";
1302                 } elsif (check_keyword("CODE")) {
1303                         print_section() ;
1304                 } elsif (defined($class) and $func_name eq "DESTROY") {
1305                         print "\n\t";
1306                         print "delete THIS;\n";
1307                 } else {
1308                         print "\n\t";
1309                         if ($ret_type ne "void") {
1310                                 print "RETVAL = ";
1311                                 $wantRETVAL = 1;
1312                         }
1313                         if (defined($static)) {
1314                             if ($func_name eq 'new') {
1315                                 $func_name = "$class";
1316                             } else {
1317                                 print "${class}::";
1318                             }
1319                         } elsif (defined($class)) {
1320                             if ($func_name eq 'new') {
1321                                 $func_name .= " $class";
1322                             } else {
1323                                 print "THIS->";
1324                             }
1325                         }
1326                         $func_name =~ s/^($spat)//
1327                             if defined($spat);
1328                         $func_name = 'XSFUNCTION' if $interface;
1329                         print "$func_name($func_args);\n";
1330                 }
1331         }
1332
1333         # do output variables
1334         $gotRETVAL = 0;         # 1 if RETVAL seen in OUTPUT section;
1335         undef $RETVAL_code ;    # code to set RETVAL (from OUTPUT section);
1336         # $wantRETVAL set if 'RETVAL =' autogenerated
1337         ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
1338         undef %outargs ;
1339         process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE"); 
1340
1341         &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
1342           for grep $in_out{$_} =~ /OUT$/, keys %in_out;
1343
1344         # all OUTPUT done, so now push the return value on the stack
1345         if ($gotRETVAL && $RETVAL_code) {
1346             print "\t$RETVAL_code\n";
1347         } elsif ($gotRETVAL || $wantRETVAL) {
1348             my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
1349             my $var = 'RETVAL';
1350             my $type = $ret_type;
1351
1352             # 0: type, 1: with_size, 2: how, 3: how_size
1353             if ($t and not $t->[1] and $t->[0] eq 'p') {
1354                 # PUSHp corresponds to setpvn.  Treate setpv directly
1355                 my $what = eval qq("$t->[2]");
1356                 warn $@ if $@;
1357
1358                 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
1359                 $prepush_done = 1;
1360             }
1361             elsif ($t) {
1362                 my $what = eval qq("$t->[2]");
1363                 warn $@ if $@;
1364
1365                 my $size = $t->[3];
1366                 $size = '' unless defined $size;
1367                 $size = eval qq("$size");
1368                 warn $@ if $@;
1369                 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
1370                 $prepush_done = 1;
1371             }
1372             else {
1373                 # RETVAL almost never needs SvSETMAGIC()
1374                 &generate_output($ret_type, 0, 'RETVAL', 0);
1375             }
1376         }
1377
1378         $xsreturn = 1 if $ret_type ne "void";
1379         my $num = $xsreturn;
1380         my $c = @outlist;
1381         print "\tXSprePUSH;" if $c and not $prepush_done;
1382         print "\tEXTEND(SP,$c);\n" if $c;
1383         $xsreturn += $c;
1384         generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
1385
1386         # do cleanup
1387         process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE") ;
1388
1389         print Q<<"EOF" if $ScopeThisXSUB;
1390 #   ]]
1391 EOF
1392         print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1393 #   LEAVE;
1394 EOF
1395
1396         # print function trailer
1397         print Q<<EOF;
1398 #    ]]
1399 EOF
1400         print Q<<EOF if $except;
1401 #    BEGHANDLERS
1402 #    CATCHALL
1403 #       sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1404 #    ENDHANDLERS
1405 EOF
1406         if (check_keyword("CASE")) {
1407             blurt ("Error: No `CASE:' at top of function")
1408                 unless $condnum;
1409             $_ = "CASE: $_";    # Restore CASE: label
1410             next;
1411         }
1412         last if $_ eq "$END:";
1413         death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1414     }
1415
1416     print Q<<EOF if $except;
1417 #    if (errbuf[0])
1418 #       Perl_croak(aTHX_ errbuf);
1419 EOF
1420
1421     if ($xsreturn) {
1422         print Q<<EOF unless $PPCODE;
1423 #    XSRETURN($xsreturn);
1424 EOF
1425     } else {
1426         print Q<<EOF unless $PPCODE;
1427 #    XSRETURN_EMPTY;
1428 EOF
1429     }
1430
1431     print Q<<EOF;
1432 #]]
1433 #
1434 EOF
1435
1436     my $newXS = "newXS" ;
1437     my $proto = "" ;
1438
1439     # Build the prototype string for the xsub
1440     if ($ProtoThisXSUB) {
1441         $newXS = "newXSproto";
1442
1443         if ($ProtoThisXSUB eq 2) {
1444             # User has specified empty prototype
1445             $proto = ', ""' ;
1446         }
1447         elsif ($ProtoThisXSUB ne 1) {
1448             # User has specified a prototype
1449             $proto = ', "' . $ProtoThisXSUB . '"';
1450         }
1451         else {
1452             my $s = ';';
1453             if ($min_args < $num_args)  {
1454                 $s = ''; 
1455                 $proto_arg[$min_args] .= ";" ;
1456             }
1457             push @proto_arg, "$s\@" 
1458                 if $elipsis ;
1459     
1460             $proto = ', "' . join ("", @proto_arg) . '"';
1461         }
1462     }
1463
1464     if (%XsubAliases) {
1465         $XsubAliases{$pname} = 0 
1466             unless defined $XsubAliases{$pname} ;
1467         while ( ($name, $value) = each %XsubAliases) {
1468             push(@InitFileCode, Q<<"EOF");
1469 #        cv = newXS(\"$name\", XS_$Full_func_name, file);
1470 #        XSANY.any_i32 = $value ;
1471 EOF
1472         push(@InitFileCode, Q<<"EOF") if $proto;
1473 #        sv_setpv((SV*)cv$proto) ;
1474 EOF
1475         }
1476     } 
1477     elsif (@Attributes) {
1478             push(@InitFileCode, Q<<"EOF");
1479 #        cv = newXS(\"$pname\", XS_$Full_func_name, file);
1480 #        apply_attrs_string("$Package", cv, "@Attributes", 0);
1481 EOF
1482     }
1483     elsif ($interface) {
1484         while ( ($name, $value) = each %Interfaces) {
1485             $name = "$Package\::$name" unless $name =~ /::/;
1486             push(@InitFileCode, Q<<"EOF");
1487 #        cv = newXS(\"$name\", XS_$Full_func_name, file);
1488 #        $interface_macro_set(cv,$value) ;
1489 EOF
1490             push(@InitFileCode, Q<<"EOF") if $proto;
1491 #        sv_setpv((SV*)cv$proto) ;
1492 EOF
1493         }
1494     }
1495     else {
1496         push(@InitFileCode,
1497              "        ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1498     }
1499 }
1500
1501 # print initialization routine
1502
1503 print Q<<"EOF";
1504 ##ifdef __cplusplus
1505 #extern "C"
1506 ##endif
1507 EOF
1508
1509 print Q<<"EOF";
1510 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1511 #XS(boot_$Module_cname)
1512 EOF
1513
1514 print Q<<"EOF";
1515 #[[
1516 #    dXSARGS;
1517 EOF
1518
1519 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1520 #so `file' is unused
1521 print Q<<"EOF" if $Full_func_name;
1522 #    char* file = __FILE__;
1523 EOF
1524
1525 print Q "#\n";
1526
1527 print Q<<"EOF" if $WantVersionChk ;
1528 #    XS_VERSION_BOOTCHECK ;
1529 #
1530 EOF
1531
1532 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1533 #    {
1534 #        CV * cv ;
1535 #
1536 EOF
1537
1538 print @InitFileCode;
1539
1540 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1541 #    }
1542 EOF
1543
1544 if (@BootCode)
1545 {
1546     print "\n    /* Initialisation Section */\n\n" ;
1547     @line = @BootCode;
1548     print_section();
1549     print "\n    /* End of Initialisation Section */\n\n" ;
1550 }
1551
1552 print Q<<"EOF";;
1553 #    XSRETURN_YES;
1554 #]]
1555 #
1556 EOF
1557
1558 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n") 
1559     unless $ProtoUsed ;
1560 &Exit;
1561
1562 sub output_init {
1563     local($type, $num, $var, $init, $name_printed) = @_;
1564     local($arg) = "ST(" . ($num - 1) . ")";
1565
1566     if(  $init =~ /^=/  ) {
1567         if ($name_printed) {
1568           eval qq/print " $init\\n"/;
1569         } else {
1570           eval qq/print "\\t$var $init\\n"/;
1571         }
1572         warn $@   if  $@;
1573     } else {
1574         if(  $init =~ s/^\+//  &&  $num  ) {
1575             &generate_init($type, $num, $var, $name_printed);
1576         } elsif ($name_printed) {
1577             print ";\n";
1578             $init =~ s/^;//;
1579         } else {
1580             eval qq/print "\\t$var;\\n"/;
1581             warn $@   if  $@;
1582             $init =~ s/^;//;
1583         }
1584         $deferred .= eval qq/"\\n\\t$init\\n"/;
1585         warn $@   if  $@;
1586     }
1587 }
1588
1589 sub Warn
1590 {
1591     # work out the line number
1592     my $line_no = $line_no[@line_no - @line -1] ;
1593  
1594     print STDERR "@_ in $filename, line $line_no\n" ;
1595 }
1596
1597 sub blurt 
1598
1599     Warn @_ ;
1600     $errors ++ 
1601 }
1602
1603 sub death
1604 {
1605     Warn @_ ;
1606     exit 1 ;
1607 }
1608
1609 sub generate_init {
1610     local($type, $num, $var) = @_;
1611     local($arg) = "ST(" . ($num - 1) . ")";
1612     local($argoff) = $num - 1;
1613     local($ntype);
1614     local($tk);
1615
1616     $type = TidyType($type) ;
1617     blurt("Error: '$type' not in typemap"), return 
1618         unless defined($type_kind{$type});
1619
1620     ($ntype = $type) =~ s/\s*\*/Ptr/g;
1621     ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1622     $tk = $type_kind{$type};
1623     $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1624     $type =~ tr/:/_/;
1625     blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1626         unless defined $input_expr{$tk} ;
1627     $expr = $input_expr{$tk};
1628     if ($expr =~ /DO_ARRAY_ELEM/) {
1629         blurt("Error: '$subtype' not in typemap"), return 
1630             unless defined($type_kind{$subtype});
1631         blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1632             unless defined $input_expr{$type_kind{$subtype}} ;
1633         $subexpr = $input_expr{$type_kind{$subtype}};
1634         $subexpr =~ s/\$type/\$subtype/g;
1635         $subexpr =~ s/ntype/subtype/g;
1636         $subexpr =~ s/\$arg/ST(ix_$var)/g;
1637         $subexpr =~ s/\n\t/\n\t\t/g;
1638         $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1639         $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1640         $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1641     }
1642     if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1643         $ScopeThisXSUB = 1;
1644     }
1645     if (defined($defaults{$var})) {
1646             $expr =~ s/(\t+)/$1    /g;
1647             $expr =~ s/        /\t/g;
1648             if ($name_printed) {
1649               print ";\n";
1650             } else {
1651               eval qq/print "\\t$var;\\n"/;
1652               warn $@   if  $@;
1653             }
1654             if ($defaults{$var} eq 'NO_INIT') {
1655                 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1656             } else {
1657                 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t    $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1658             }
1659             warn $@   if  $@;
1660     } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1661             if ($name_printed) {
1662               print ";\n";
1663             } else {
1664               eval qq/print "\\t$var;\\n"/;
1665               warn $@   if  $@;
1666             }
1667             $deferred .= eval qq/"\\n$expr;\\n"/;
1668             warn $@   if  $@;
1669     } else {
1670             die "panic: do not know how to handle this branch for function pointers"
1671               if $name_printed;
1672             eval qq/print "$expr;\\n"/;
1673             warn $@   if  $@;
1674     }
1675 }
1676
1677 sub generate_output {
1678     local($type, $num, $var, $do_setmagic, $do_push) = @_;
1679     local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1680     local($argoff) = $num - 1;
1681     local($ntype);
1682
1683     $type = TidyType($type) ;
1684     if ($type =~ /^array\(([^,]*),(.*)\)/) {
1685             print "\t$arg = sv_newmortal();\n";
1686             print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1687             print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1688     } else {
1689             blurt("Error: '$type' not in typemap"), return
1690                 unless defined($type_kind{$type});
1691             blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1692                 unless defined $output_expr{$type_kind{$type}} ;
1693             ($ntype = $type) =~ s/\s*\*/Ptr/g;
1694             $ntype =~ s/\(\)//g;
1695             ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1696             $expr = $output_expr{$type_kind{$type}};
1697             if ($expr =~ /DO_ARRAY_ELEM/) {
1698                 blurt("Error: '$subtype' not in typemap"), return
1699                     unless defined($type_kind{$subtype});
1700                 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1701                     unless defined $output_expr{$type_kind{$subtype}} ;
1702                 $subexpr = $output_expr{$type_kind{$subtype}};
1703                 $subexpr =~ s/ntype/subtype/g;
1704                 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1705                 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1706                 $subexpr =~ s/\n\t/\n\t\t/g;
1707                 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1708                 eval "print qq\a$expr\a";
1709                 warn $@   if  $@;
1710                 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1711             }
1712             elsif ($var eq 'RETVAL') {
1713                 if ($expr =~ /^\t\$arg = new/) {
1714                     # We expect that $arg has refcnt 1, so we need to
1715                     # mortalize it.
1716                     eval "print qq\a$expr\a";
1717                     warn $@   if  $@;
1718                     print "\tsv_2mortal(ST($num));\n";
1719                     print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1720                 }
1721                 elsif ($expr =~ /^\s*\$arg\s*=/) {
1722                     # We expect that $arg has refcnt >=1, so we need
1723                     # to mortalize it!
1724                     eval "print qq\a$expr\a";
1725                     warn $@   if  $@;
1726                     print "\tsv_2mortal(ST(0));\n";
1727                     print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1728                 }
1729                 else {
1730                     # Just hope that the entry would safely write it
1731                     # over an already mortalized value. By
1732                     # coincidence, something like $arg = &sv_undef
1733                     # works too.
1734                     print "\tST(0) = sv_newmortal();\n";
1735                     eval "print qq\a$expr\a";
1736                     warn $@   if  $@;
1737                     # new mortals don't have set magic
1738                 }
1739             }
1740             elsif ($do_push) {
1741                 print "\tPUSHs(sv_newmortal());\n";
1742                 $arg = "ST($num)";
1743                 eval "print qq\a$expr\a";
1744                 warn $@   if  $@;
1745                 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1746             }
1747             elsif ($arg =~ /^ST\(\d+\)$/) {
1748                 eval "print qq\a$expr\a";
1749                 warn $@   if  $@;
1750                 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1751             }
1752     }
1753 }
1754
1755 sub map_type {
1756     my($type, $varname) = @_;
1757
1758     $type =~ tr/:/_/;
1759     $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1760     if ($varname) {
1761       if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1762         (substr $type, pos $type, 0) = " $varname ";
1763       } else {
1764         $type .= "\t$varname";
1765       }
1766     }
1767     $type;
1768 }
1769
1770
1771 sub Exit {
1772 # If this is VMS, the exit status has meaning to the shell, so we
1773 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1774 # arbitrary number.
1775 #    exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1776     exit ($errors ? 1 : 0);
1777 }