xsubpp
[p5sagit/p5-mst-13.2.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         # Process the length(foo) declarations
414         if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
415           print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
416           $lengthof{$2} = $name;
417           # $islengthof{$name} = $1;
418           $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;";
419         }
420
421         # check for optional initialisation code
422         my $var_init = '' ;
423         $var_init = $1 if s/\s*([=;+].*)$//s ;
424         $var_init =~ s/"/\\"/g;
425
426         s/\s+/ /g;
427         my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
428             or blurt("Error: invalid argument declaration '$line'"), next;
429
430         # Check for duplicate definitions
431         blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
432             if $arg_list{$var_name}++ 
433               or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
434
435         $thisdone |= $var_name eq "THIS";
436         $retvaldone |= $var_name eq "RETVAL";
437         $var_types{$var_name} = $var_type;
438         # XXXX This check is a safeguard against the unfinished conversion of
439         # generate_init().  When generate_init() is fixed,
440         # one can use 2-args map_type() unconditionally.
441         if ($var_type =~ / \( \s* \* \s* \) /x) {
442           # Function pointers are not yet supported with &output_init!
443           print "\t" . &map_type($var_type, $var_name);
444           $name_printed = 1;
445         } else {
446           print "\t" . &map_type($var_type);
447           $name_printed = 0;
448         }
449         $var_num = $args_match{$var_name};
450
451         $proto_arg[$var_num] = ProtoString($var_type) 
452             if $var_num ;
453         $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
454         if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
455             or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
456             and $var_init !~ /\S/) {
457           if ($name_printed) {
458             print ";\n";
459           } else {
460             print "\t$var_name;\n";
461           }
462         } elsif ($var_init =~ /\S/) {
463             &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
464         } elsif ($var_num) {
465             # generate initialization code
466             &generate_init($var_type, $var_num, $var_name, $name_printed);
467         } else {
468             print ";\n";
469         }
470     }
471 }
472
473 sub OUTPUT_handler {
474     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
475         next unless /\S/;
476         if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
477             $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
478             next;
479         }
480         my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
481         blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
482             if $outargs{$outarg} ++ ;
483         if (!$gotRETVAL and $outarg eq 'RETVAL') {
484             # deal with RETVAL last
485             $RETVAL_code = $outcode ;
486             $gotRETVAL = 1 ;
487             next ;
488         }
489         blurt ("Error: OUTPUT $outarg not an argument"), next
490             unless defined($args_match{$outarg});
491         blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
492             unless defined $var_types{$outarg} ;
493         $var_num = $args_match{$outarg};
494         if ($outcode) {
495             print "\t$outcode\n";
496             print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
497         } else {
498             &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
499         }
500         delete $in_out{$outarg}         # No need to auto-OUTPUT 
501           if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
502     }
503 }
504
505 sub C_ARGS_handler() {
506     my $in = merge_section();
507   
508     TrimWhitespace($in);
509     $func_args = $in;
510
511
512 sub INTERFACE_MACRO_handler() {
513     my $in = merge_section();
514   
515     TrimWhitespace($in);
516     if ($in =~ /\s/) {          # two
517         ($interface_macro, $interface_macro_set) = split ' ', $in;
518     } else {
519         $interface_macro = $in;
520         $interface_macro_set = 'UNKNOWN_CVT'; # catch later
521     }
522     $interface = 1;             # local
523     $Interfaces = 1;            # global
524 }
525
526 sub INTERFACE_handler() {
527     my $in = merge_section();
528   
529     TrimWhitespace($in);
530     
531     foreach (split /[\s,]+/, $in) {
532         $Interfaces{$_} = $_;
533     }
534     print Q<<"EOF";
535 #       XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
536 EOF
537     $interface = 1;             # local
538     $Interfaces = 1;            # global
539 }
540
541 sub CLEANUP_handler() { print_section() } 
542 sub PREINIT_handler() { print_section() } 
543 sub POSTCALL_handler() { print_section() } 
544 sub INIT_handler()    { print_section() } 
545
546 sub GetAliases
547 {
548     my ($line) = @_ ;
549     my ($orig) = $line ;
550     my ($alias) ;
551     my ($value) ;
552
553     # Parse alias definitions
554     # format is
555     #    alias = value alias = value ...
556
557     while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
558         $alias = $1 ;
559         $orig_alias = $alias ;
560         $value = $2 ;
561
562         # check for optional package definition in the alias
563         $alias = $Packprefix . $alias if $alias !~ /::/ ;
564         
565         # check for duplicate alias name & duplicate value
566         Warn("Warning: Ignoring duplicate alias '$orig_alias'")
567             if defined $XsubAliases{$alias} ;
568
569         Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
570             if $XsubAliasValues{$value} ;
571
572         $XsubAliases = 1;
573         $XsubAliases{$alias} = $value ;
574         $XsubAliasValues{$value} = $orig_alias ;
575     }
576
577     blurt("Error: Cannot parse ALIAS definitions from '$orig'")
578         if $line ;
579 }
580
581 sub ATTRS_handler ()
582 {
583     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
584         next unless /\S/;
585         TrimWhitespace($_) ;
586         push @Attributes, $_;
587     }
588 }
589
590 sub ALIAS_handler ()
591 {
592     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
593         next unless /\S/;
594         TrimWhitespace($_) ;
595         GetAliases($_) if $_ ;
596     }
597 }
598
599 sub REQUIRE_handler ()
600 {
601     # the rest of the current line should contain a version number
602     my ($Ver) = $_ ;
603
604     TrimWhitespace($Ver) ;
605
606     death ("Error: REQUIRE expects a version number")
607         unless $Ver ;
608
609     # check that the version number is of the form n.n
610     death ("Error: REQUIRE: expected a number, got '$Ver'")
611         unless $Ver =~ /^\d+(\.\d*)?/ ;
612
613     death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
614         unless $XSUBPP_version >= $Ver ; 
615 }
616
617 sub VERSIONCHECK_handler ()
618 {
619     # the rest of the current line should contain either ENABLE or
620     # DISABLE
621  
622     TrimWhitespace($_) ;
623  
624     # check for ENABLE/DISABLE
625     death ("Error: VERSIONCHECK: ENABLE/DISABLE")
626         unless /^(ENABLE|DISABLE)/i ;
627  
628     $WantVersionChk = 1 if $1 eq 'ENABLE' ;
629     $WantVersionChk = 0 if $1 eq 'DISABLE' ;
630  
631 }
632
633 sub PROTOTYPE_handler ()
634 {
635     my $specified ;
636
637     death("Error: Only 1 PROTOTYPE definition allowed per xsub") 
638         if $proto_in_this_xsub ++ ;
639
640     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
641         next unless /\S/;
642         $specified = 1 ;
643         TrimWhitespace($_) ;
644         if ($_ eq 'DISABLE') {
645            $ProtoThisXSUB = 0 
646         }
647         elsif ($_ eq 'ENABLE') {
648            $ProtoThisXSUB = 1 
649         }
650         else {
651             # remove any whitespace
652             s/\s+//g ;
653             death("Error: Invalid prototype '$_'")
654                 unless ValidProtoString($_) ;
655             $ProtoThisXSUB = C_string($_) ;
656         }
657     }
658
659     # If no prototype specified, then assume empty prototype ""
660     $ProtoThisXSUB = 2 unless $specified ;
661
662     $ProtoUsed = 1 ;
663
664 }
665
666 sub SCOPE_handler ()
667 {
668     death("Error: Only 1 SCOPE declaration allowed per xsub") 
669         if $scope_in_this_xsub ++ ;
670
671     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
672                 next unless /\S/;
673                 TrimWhitespace($_) ;
674         if ($_ =~ /^DISABLE/i) {
675                    $ScopeThisXSUB = 0 
676         }
677         elsif ($_ =~ /^ENABLE/i) {
678                    $ScopeThisXSUB = 1 
679         }
680     }
681
682 }
683
684 sub PROTOTYPES_handler ()
685 {
686     # the rest of the current line should contain either ENABLE or
687     # DISABLE 
688
689     TrimWhitespace($_) ;
690
691     # check for ENABLE/DISABLE
692     death ("Error: PROTOTYPES: ENABLE/DISABLE")
693         unless /^(ENABLE|DISABLE)/i ;
694
695     $WantPrototypes = 1 if $1 eq 'ENABLE' ;
696     $WantPrototypes = 0 if $1 eq 'DISABLE' ;
697     $ProtoUsed = 1 ;
698
699 }
700
701 sub INCLUDE_handler ()
702 {
703     # the rest of the current line should contain a valid filename
704  
705     TrimWhitespace($_) ;
706  
707     death("INCLUDE: filename missing")
708         unless $_ ;
709
710     death("INCLUDE: output pipe is illegal")
711         if /^\s*\|/ ;
712
713     # simple minded recursion detector
714     death("INCLUDE loop detected")
715         if $IncludedFiles{$_} ;
716
717     ++ $IncludedFiles{$_} unless /\|\s*$/ ;
718
719     # Save the current file context.
720     push(@XSStack, {
721         type            => 'file',
722         LastLine        => $lastline,
723         LastLineNo      => $lastline_no,
724         Line            => \@line,
725         LineNo          => \@line_no,
726         Filename        => $filename,
727         Handle          => $FH,
728         }) ;
729  
730     ++ $FH ;
731
732     # open the new file
733     open ($FH, "$_") or death("Cannot open '$_': $!") ;
734  
735     print Q<<"EOF" ;
736 #
737 #/* INCLUDE:  Including '$_' from '$filename' */
738 #
739 EOF
740
741     $filename = $_ ;
742
743     # Prime the pump by reading the first 
744     # non-blank line
745
746     # skip leading blank lines
747     while (<$FH>) {
748         last unless /^\s*$/ ;
749     }
750
751     $lastline = $_ ;
752     $lastline_no = $. ;
753  
754 }
755  
756 sub PopFile()
757 {
758     return 0 unless $XSStack[-1]{type} eq 'file' ;
759
760     my $data     = pop @XSStack ;
761     my $ThisFile = $filename ;
762     my $isPipe   = ($filename =~ /\|\s*$/) ;
763  
764     -- $IncludedFiles{$filename}
765         unless $isPipe ;
766
767     close $FH ;
768
769     $FH         = $data->{Handle} ;
770     $filename   = $data->{Filename} ;
771     $lastline   = $data->{LastLine} ;
772     $lastline_no = $data->{LastLineNo} ;
773     @line       = @{ $data->{Line} } ;
774     @line_no    = @{ $data->{LineNo} } ;
775
776     if ($isPipe and $? ) {
777         -- $lastline_no ;
778         print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n"  ;
779         exit 1 ;
780     }
781
782     print Q<<"EOF" ;
783 #
784 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
785 #
786 EOF
787
788     return 1 ;
789 }
790
791 sub ValidProtoString ($)
792 {
793     my($string) = @_ ;
794
795     if ( $string =~ /^$proto_re+$/ ) {
796         return $string ;
797     }
798
799     return 0 ;
800 }
801
802 sub C_string ($)
803 {
804     my($string) = @_ ;
805
806     $string =~ s[\\][\\\\]g ;
807     $string ;
808 }
809
810 sub ProtoString ($)
811 {
812     my ($type) = @_ ;
813
814     $proto_letter{$type} or "\$" ;
815 }
816
817 sub check_cpp {
818     my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
819     if (@cpp) {
820         my ($cpp, $cpplevel);
821         for $cpp (@cpp) {
822             if ($cpp =~ /^\#\s*if/) {
823                 $cpplevel++;
824             } elsif (!$cpplevel) {
825                 Warn("Warning: #else/elif/endif without #if in this function");
826                 print STDERR "    (precede it with a blank line if the matching #if is outside the function)\n"
827                     if $XSStack[-1]{type} eq 'if';
828                 return;
829             } elsif ($cpp =~ /^\#\s*endif/) {
830                 $cpplevel--;
831             }
832         }
833         Warn("Warning: #if without #endif in this function") if $cpplevel;
834     }
835 }
836
837
838 sub Q {
839     my($text) = @_;
840     $text =~ s/^#//gm;
841     $text =~ s/\[\[/{/g;
842     $text =~ s/\]\]/}/g;
843     $text;
844 }
845
846 open($FH, $filename) or die "cannot open $filename: $!\n";
847
848 # Identify the version of xsubpp used
849 print <<EOM ;
850 /*
851  * This file was generated automatically by xsubpp version $XSUBPP_version from the 
852  * contents of $filename. Do not edit this file, edit $filename instead.
853  *
854  *      ANY CHANGES MADE HERE WILL BE LOST! 
855  *
856  */
857
858 EOM
859  
860
861 print("#line 1 \"$filename\"\n")
862     if $WantLineNumbers;
863
864 firstmodule:
865 while (<$FH>) {
866     if (/^=/) {
867         my $podstartline = $.;
868         do {
869             if (/^=cut\s*$/) {
870                 print("/* Skipped embedded POD. */\n");
871                 printf("#line %d \"$filename\"\n", $. + 1)
872                   if $WantLineNumbers;
873                 next firstmodule
874             }
875
876         } while (<$FH>);
877         # At this point $. is at end of file so die won't state the start
878         # of the problem, and as we haven't yet read any lines &death won't
879         # show the correct line in the message either.
880         die ("Error: Unterminated pod in $filename, line $podstartline\n")
881           unless $lastline;
882     }
883     last if ($Module, $Package, $Prefix) =
884         /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
885
886     print $_;
887 }
888 &Exit unless defined $_;
889
890 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
891
892 $lastline    = $_;
893 $lastline_no = $.;
894
895 # Read next xsub into @line from ($lastline, <$FH>).
896 sub fetch_para {
897     # parse paragraph
898     death ("Error: Unterminated `#if/#ifdef/#ifndef'")
899         if !defined $lastline && $XSStack[-1]{type} eq 'if';
900     @line = ();
901     @line_no = () ;
902     return PopFile() if !defined $lastline;
903
904     if ($lastline =~
905         /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
906         $Module = $1;
907         $Package = defined($2) ? $2 : '';       # keep -w happy
908         $Prefix  = defined($3) ? $3 : '';       # keep -w happy
909         $Prefix = quotemeta $Prefix ;
910         ($Module_cname = $Module) =~ s/\W/_/g;
911         ($Packid = $Package) =~ tr/:/_/;
912         $Packprefix = $Package;
913         $Packprefix .= "::" if $Packprefix ne "";
914         $lastline = "";
915     }
916
917     for(;;) {
918         # Skip embedded PODs 
919         while ($lastline =~ /^=/) {
920             while ($lastline = <$FH>) {
921                 last if ($lastline =~ /^=cut\s*$/);
922             }
923             death ("Error: Unterminated pod") unless $lastline;
924             $lastline = <$FH>;
925             chomp $lastline;
926             $lastline =~ s/^\s+$//;
927         }
928         if ($lastline !~ /^\s*#/ ||
929             # CPP directives:
930             #   ANSI:   if ifdef ifndef elif else endif define undef
931             #           line error pragma
932             #   gcc:    warning include_next
933             #   obj-c:  import
934             #   others: ident (gcc notes that some cpps have this one)
935             $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
936             last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
937             push(@line, $lastline);
938             push(@line_no, $lastline_no) ;
939         }
940
941         # Read next line and continuation lines
942         last unless defined($lastline = <$FH>);
943         $lastline_no = $.;
944         my $tmp_line;
945         $lastline .= $tmp_line
946             while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
947
948         chomp $lastline;
949         $lastline =~ s/^\s+$//;
950     }
951     pop(@line), pop(@line_no) while @line && $line[-1] eq "";
952     1;
953 }
954
955 PARAGRAPH:
956 while (fetch_para()) {
957     # Print initial preprocessor statements and blank lines
958     while (@line && $line[0] !~ /^[^\#]/) {
959         my $line = shift(@line);
960         print $line, "\n";
961         next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
962         my $statement = $+;
963         if ($statement eq 'if') {
964             $XSS_work_idx = @XSStack;
965             push(@XSStack, {type => 'if'});
966         } else {
967             death ("Error: `$statement' with no matching `if'")
968                 if $XSStack[-1]{type} ne 'if';
969             if ($XSStack[-1]{varname}) {
970                 push(@InitFileCode, "#endif\n");
971                 push(@BootCode,     "#endif");
972             }
973
974             my(@fns) = keys %{$XSStack[-1]{functions}};
975             if ($statement ne 'endif') {
976                 # Hide the functions defined in other #if branches, and reset.
977                 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
978                 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
979             } else {
980                 my($tmp) = pop(@XSStack);
981                 0 while (--$XSS_work_idx
982                          && $XSStack[$XSS_work_idx]{type} ne 'if');
983                 # Keep all new defined functions
984                 push(@fns, keys %{$tmp->{other_functions}});
985                 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
986             }
987         }
988     }
989
990     next PARAGRAPH unless @line;
991
992     if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
993         # We are inside an #if, but have not yet #defined its xsubpp variable.
994         print "#define $cpp_next_tmp 1\n\n";
995         push(@InitFileCode, "#if $cpp_next_tmp\n");
996         push(@BootCode,     "#if $cpp_next_tmp");
997         $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
998     }
999
1000     death ("Code is not inside a function"
1001            ." (maybe last function was ended by a blank line "
1002            ." followed by a statement on column one?)")
1003         if $line[0] =~ /^\s/;
1004
1005     # initialize info arrays
1006     undef(%args_match);
1007     undef(%var_types);
1008     undef(%defaults);
1009     undef($class);
1010     undef($static);
1011     undef($elipsis);
1012     undef($wantRETVAL) ;
1013     undef($RETVAL_no_return) ;
1014     undef(%arg_list) ;
1015     undef(@proto_arg) ;
1016     undef(@fake_INPUT_pre) ;    # For length(s) generated variables
1017     undef(@fake_INPUT) ;
1018     undef($processing_arg_with_types) ;
1019     undef(%argtype_seen) ;
1020     undef(@outlist) ;
1021     undef(%in_out) ;
1022     undef(%lengthof) ;
1023     # undef(%islengthof) ;
1024     undef($proto_in_this_xsub) ;
1025     undef($scope_in_this_xsub) ;
1026     undef($interface);
1027     undef($prepush_done);
1028     $interface_macro = 'XSINTERFACE_FUNC' ;
1029     $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
1030     $ProtoThisXSUB = $WantPrototypes ;
1031     $ScopeThisXSUB = 0;
1032     $xsreturn = 0;
1033
1034     $_ = shift(@line);
1035     while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
1036         &{"${kwd}_handler"}() ;
1037         next PARAGRAPH unless @line ;
1038         $_ = shift(@line);
1039     }
1040
1041     if (check_keyword("BOOT")) {
1042         &check_cpp;
1043         push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
1044           if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
1045         push (@BootCode, @line, "") ;
1046         next PARAGRAPH ;
1047     }
1048
1049
1050     # extract return type, function name and arguments
1051     ($ret_type) = TidyType($_);
1052     $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
1053
1054     # Allow one-line ANSI-like declaration
1055     unshift @line, $2
1056       if $process_argtypes
1057         and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
1058
1059     # a function definition needs at least 2 lines
1060     blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
1061         unless @line ;
1062
1063     $static = 1 if $ret_type =~ s/^static\s+//;
1064
1065     $func_header = shift(@line);
1066     blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
1067         unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
1068
1069     ($class, $func_name, $orig_args) =  ($1, $2, $3) ;
1070     $class = "$4 $class" if $4;
1071     ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
1072     ($clean_func_name = $func_name) =~ s/^$Prefix//;
1073     $Full_func_name = "${Packid}_$clean_func_name";
1074     if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
1075
1076     # Check for duplicate function definition
1077     for $tmp (@XSStack) {
1078         next unless defined $tmp->{functions}{$Full_func_name};
1079         Warn("Warning: duplicate function definition '$clean_func_name' detected");
1080         last;
1081     }
1082     $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
1083     %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
1084     $DoSetMagic = 1;
1085
1086     $orig_args =~ s/\\\s*/ /g;          # process line continuations
1087
1088     my %only_C_inlist;  # Not in the signature of Perl function
1089     if ($process_argtypes and $orig_args =~ /\S/) {
1090         my $args = "$orig_args ,";
1091         if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
1092             @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
1093             for ( @args ) {
1094                 s/^\s+//;
1095                 s/\s+$//;
1096                 my ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
1097                 my ($pre, $name) = ($arg =~ /(.*?) \s*
1098                                              \b ( \w+ | length\( \s*\w+\s* \) )
1099                                              \s* $ /x);
1100                 next unless length $pre;
1101                 my $out_type;
1102                 my $inout_var;
1103                 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//) {
1104                     my $type = $1;
1105                     $out_type = $type if $type ne 'IN';
1106                     $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1107                     $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1108                 }
1109                 my $islength;
1110                 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
1111                   $name = "XSauto_length_of_$1";
1112                   $islength = 1;
1113                   die "Default value on length() argument: `$_'"
1114                     if length $default;
1115                 }
1116                 if (length $pre or $islength) { # Has a type
1117                     if ($islength) {
1118                       push @fake_INPUT_pre, $arg;
1119                     } else {
1120                       push @fake_INPUT, $arg;
1121                     }
1122                     # warn "pushing '$arg'\n";
1123                     $argtype_seen{$name}++;
1124                     $_ = "$name$default"; # Assigns to @args
1125                 }
1126                 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
1127                 push @outlist, $name if $out_type =~ /OUTLIST$/;
1128                 $in_out{$name} = $out_type if $out_type;
1129             }
1130         } else {
1131             @args = split(/\s*,\s*/, $orig_args);
1132             Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
1133         }
1134     } else {
1135         @args = split(/\s*,\s*/, $orig_args);
1136         for (@args) {
1137             if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\s+//) {
1138                 my $out_type = $1;
1139                 next if $out_type eq 'IN';
1140                 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
1141                 push @outlist, $name if $out_type =~ /OUTLIST$/;
1142                 $in_out{$_} = $out_type;
1143             }
1144         }
1145     }
1146     if (defined($class)) {
1147         my $arg0 = ((defined($static) or $func_name eq 'new')
1148                     ? "CLASS" : "THIS");
1149         unshift(@args, $arg0);
1150         ($report_args = "$arg0, $report_args") =~ s/^\w+, $/$arg0/;
1151     }
1152     my $extra_args = 0;
1153     @args_num = ();
1154     $num_args = 0;
1155     my $report_args = '';
1156     foreach $i (0 .. $#args) {
1157             if ($args[$i] =~ s/\.\.\.//) {
1158                     $elipsis = 1;
1159                     if ($args[$i] eq '' && $i == $#args) {
1160                         $report_args .= ", ...";
1161                         pop(@args);
1162                         last;
1163                     }
1164             }
1165             if ($only_C_inlist{$args[$i]}) {
1166                 push @args_num, undef;
1167             } else {
1168                 push @args_num, ++$num_args;
1169                 $report_args .= ", $args[$i]";
1170             }
1171             if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
1172                     $extra_args++;
1173                     $args[$i] = $1;
1174                     $defaults{$args[$i]} = $2;
1175                     $defaults{$args[$i]} =~ s/"/\\"/g;
1176             }
1177             $proto_arg[$i+1] = "\$" ;
1178     }
1179     $min_args = $num_args - $extra_args;
1180     $report_args =~ s/"/\\"/g;
1181     $report_args =~ s/^,\s+//;
1182     my @func_args = @args;
1183     shift @func_args if defined($class);
1184
1185     for (@func_args) {
1186         s/^/&/ if $in_out{$_};
1187     }
1188     $func_args = join(", ", @func_args);
1189     @args_match{@args} = @args_num;
1190
1191     $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
1192     $CODE = grep(/^\s*CODE\s*:/, @line);
1193     # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
1194     #   to set explicit return values.
1195     $EXPLICIT_RETURN = ($CODE &&
1196                 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
1197     $ALIAS  = grep(/^\s*ALIAS\s*:/,  @line);
1198     $INTERFACE  = grep(/^\s*INTERFACE\s*:/,  @line);
1199
1200     $xsreturn = 1 if $EXPLICIT_RETURN;
1201
1202     # print function header
1203     print Q<<"EOF";
1204 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
1205 #XS(XS_${Full_func_name})
1206 #[[
1207 #    dXSARGS;
1208 EOF
1209     print Q<<"EOF" if $ALIAS ;
1210 #    dXSI32;
1211 EOF
1212     print Q<<"EOF" if $INTERFACE ;
1213 #    dXSFUNCTION($ret_type);
1214 EOF
1215     if ($elipsis) {
1216         $cond = ($min_args ? qq(items < $min_args) : 0);
1217     }
1218     elsif ($min_args == $num_args) {
1219         $cond = qq(items != $min_args);
1220     }
1221     else {
1222         $cond = qq(items < $min_args || items > $num_args);
1223     }
1224
1225     print Q<<"EOF" if $except;
1226 #    char errbuf[1024];
1227 #    *errbuf = '\0';
1228 EOF
1229
1230     if ($ALIAS) 
1231       { print Q<<"EOF" if $cond }
1232 #    if ($cond)
1233 #       Perl_croak(aTHX_ "Usage: %s($report_args)", GvNAME(CvGV(cv)));
1234 EOF
1235     else 
1236       { print Q<<"EOF" if $cond }
1237 #    if ($cond)
1238 #       Perl_croak(aTHX_ "Usage: $pname($report_args)");
1239 EOF
1240
1241     #gcc -Wall: if an xsub has no arguments and PPCODE is used
1242     #it is likely none of ST, XSRETURN or XSprePUSH macros are used
1243     #hence `ax' (setup by dXSARGS) is unused
1244     #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
1245     #but such a move could break third-party extensions
1246     print Q<<"EOF" if $PPCODE and $num_args == 0;
1247 #   PERL_UNUSED_VAR(ax); /* -Wall */
1248 EOF
1249
1250     print Q<<"EOF" if $PPCODE;
1251 #    SP -= items;
1252 EOF
1253
1254     # Now do a block of some sort.
1255
1256     $condnum = 0;
1257     $cond = '';                 # last CASE: condidional
1258     push(@line, "$END:");
1259     push(@line_no, $line_no[-1]);
1260     $_ = '';
1261     &check_cpp;
1262     while (@line) {
1263         &CASE_handler if check_keyword("CASE");
1264         print Q<<"EOF";
1265 #   $except [[
1266 EOF
1267
1268         # do initialization of input variables
1269         $thisdone = 0;
1270         $retvaldone = 0;
1271         $deferred = "";
1272         %arg_list = () ;
1273         $gotRETVAL = 0;
1274
1275         INPUT_handler() ;
1276         process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE") ;
1277
1278         print Q<<"EOF" if $ScopeThisXSUB;
1279 #   ENTER;
1280 #   [[
1281 EOF
1282         
1283         if (!$thisdone && defined($class)) {
1284             if (defined($static) or $func_name eq 'new') {
1285                 print "\tchar *";
1286                 $var_types{"CLASS"} = "char *";
1287                 &generate_init("char *", 1, "CLASS");
1288             }
1289             else {
1290                 print "\t$class *";
1291                 $var_types{"THIS"} = "$class *";
1292                 &generate_init("$class *", 1, "THIS");
1293             }
1294         }
1295
1296         # do code
1297         if (/^\s*NOT_IMPLEMENTED_YET/) {
1298                 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1299                 $_ = '' ;
1300         } else {
1301                 if ($ret_type ne "void") {
1302                         print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
1303                                 if !$retvaldone;
1304                         $args_match{"RETVAL"} = 0;
1305                         $var_types{"RETVAL"} = $ret_type;
1306                         print "\tdXSTARG;\n"
1307                                 if $WantOptimize and $targetable{$type_kind{$ret_type}};
1308                 }
1309
1310                 if (@fake_INPUT or @fake_INPUT_pre) {
1311                     unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
1312                     $_ = "";
1313                     $processing_arg_with_types = 1;
1314                     INPUT_handler() ;
1315                 }
1316                 print $deferred;
1317
1318         process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
1319
1320                 if (check_keyword("PPCODE")) {
1321                         print_section();
1322                         death ("PPCODE must be last thing") if @line;
1323                         print "\tLEAVE;\n" if $ScopeThisXSUB;
1324                         print "\tPUTBACK;\n\treturn;\n";
1325                 } elsif (check_keyword("CODE")) {
1326                         print_section() ;
1327                 } elsif (defined($class) and $func_name eq "DESTROY") {
1328                         print "\n\t";
1329                         print "delete THIS;\n";
1330                 } else {
1331                         print "\n\t";
1332                         if ($ret_type ne "void") {
1333                                 print "RETVAL = ";
1334                                 $wantRETVAL = 1;
1335                         }
1336                         if (defined($static)) {
1337                             if ($func_name eq 'new') {
1338                                 $func_name = "$class";
1339                             } else {
1340                                 print "${class}::";
1341                             }
1342                         } elsif (defined($class)) {
1343                             if ($func_name eq 'new') {
1344                                 $func_name .= " $class";
1345                             } else {
1346                                 print "THIS->";
1347                             }
1348                         }
1349                         $func_name =~ s/^($spat)//
1350                             if defined($spat);
1351                         $func_name = 'XSFUNCTION' if $interface;
1352                         print "$func_name($func_args);\n";
1353                 }
1354         }
1355
1356         # do output variables
1357         $gotRETVAL = 0;         # 1 if RETVAL seen in OUTPUT section;
1358         undef $RETVAL_code ;    # code to set RETVAL (from OUTPUT section);
1359         # $wantRETVAL set if 'RETVAL =' autogenerated
1360         ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
1361         undef %outargs ;
1362         process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE"); 
1363
1364         &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
1365           for grep $in_out{$_} =~ /OUT$/, keys %in_out;
1366
1367         # all OUTPUT done, so now push the return value on the stack
1368         if ($gotRETVAL && $RETVAL_code) {
1369             print "\t$RETVAL_code\n";
1370         } elsif ($gotRETVAL || $wantRETVAL) {
1371             my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
1372             my $var = 'RETVAL';
1373             my $type = $ret_type;
1374
1375             # 0: type, 1: with_size, 2: how, 3: how_size
1376             if ($t and not $t->[1] and $t->[0] eq 'p') {
1377                 # PUSHp corresponds to setpvn.  Treate setpv directly
1378                 my $what = eval qq("$t->[2]");
1379                 warn $@ if $@;
1380
1381                 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
1382                 $prepush_done = 1;
1383             }
1384             elsif ($t) {
1385                 my $what = eval qq("$t->[2]");
1386                 warn $@ if $@;
1387
1388                 my $size = $t->[3];
1389                 $size = '' unless defined $size;
1390                 $size = eval qq("$size");
1391                 warn $@ if $@;
1392                 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
1393                 $prepush_done = 1;
1394             }
1395             else {
1396                 # RETVAL almost never needs SvSETMAGIC()
1397                 &generate_output($ret_type, 0, 'RETVAL', 0);
1398             }
1399         }
1400
1401         $xsreturn = 1 if $ret_type ne "void";
1402         my $num = $xsreturn;
1403         my $c = @outlist;
1404         print "\tXSprePUSH;" if $c and not $prepush_done;
1405         print "\tEXTEND(SP,$c);\n" if $c;
1406         $xsreturn += $c;
1407         generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
1408
1409         # do cleanup
1410         process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE") ;
1411
1412         print Q<<"EOF" if $ScopeThisXSUB;
1413 #   ]]
1414 EOF
1415         print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1416 #   LEAVE;
1417 EOF
1418
1419         # print function trailer
1420         print Q<<EOF;
1421 #    ]]
1422 EOF
1423         print Q<<EOF if $except;
1424 #    BEGHANDLERS
1425 #    CATCHALL
1426 #       sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1427 #    ENDHANDLERS
1428 EOF
1429         if (check_keyword("CASE")) {
1430             blurt ("Error: No `CASE:' at top of function")
1431                 unless $condnum;
1432             $_ = "CASE: $_";    # Restore CASE: label
1433             next;
1434         }
1435         last if $_ eq "$END:";
1436         death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1437     }
1438
1439     print Q<<EOF if $except;
1440 #    if (errbuf[0])
1441 #       Perl_croak(aTHX_ errbuf);
1442 EOF
1443
1444     if ($xsreturn) {
1445         print Q<<EOF unless $PPCODE;
1446 #    XSRETURN($xsreturn);
1447 EOF
1448     } else {
1449         print Q<<EOF unless $PPCODE;
1450 #    XSRETURN_EMPTY;
1451 EOF
1452     }
1453
1454     print Q<<EOF;
1455 #]]
1456 #
1457 EOF
1458
1459     my $newXS = "newXS" ;
1460     my $proto = "" ;
1461
1462     # Build the prototype string for the xsub
1463     if ($ProtoThisXSUB) {
1464         $newXS = "newXSproto";
1465
1466         if ($ProtoThisXSUB eq 2) {
1467             # User has specified empty prototype
1468             $proto = ', ""' ;
1469         }
1470         elsif ($ProtoThisXSUB ne 1) {
1471             # User has specified a prototype
1472             $proto = ', "' . $ProtoThisXSUB . '"';
1473         }
1474         else {
1475             my $s = ';';
1476             if ($min_args < $num_args)  {
1477                 $s = ''; 
1478                 $proto_arg[$min_args] .= ";" ;
1479             }
1480             push @proto_arg, "$s\@" 
1481                 if $elipsis ;
1482     
1483             $proto = ', "' . join ("", @proto_arg) . '"';
1484         }
1485     }
1486
1487     if (%XsubAliases) {
1488         $XsubAliases{$pname} = 0 
1489             unless defined $XsubAliases{$pname} ;
1490         while ( ($name, $value) = each %XsubAliases) {
1491             push(@InitFileCode, Q<<"EOF");
1492 #        cv = newXS(\"$name\", XS_$Full_func_name, file);
1493 #        XSANY.any_i32 = $value ;
1494 EOF
1495         push(@InitFileCode, Q<<"EOF") if $proto;
1496 #        sv_setpv((SV*)cv$proto) ;
1497 EOF
1498         }
1499     } 
1500     elsif (@Attributes) {
1501             push(@InitFileCode, Q<<"EOF");
1502 #        cv = newXS(\"$pname\", XS_$Full_func_name, file);
1503 #        apply_attrs_string("$Package", cv, "@Attributes", 0);
1504 EOF
1505     }
1506     elsif ($interface) {
1507         while ( ($name, $value) = each %Interfaces) {
1508             $name = "$Package\::$name" unless $name =~ /::/;
1509             push(@InitFileCode, Q<<"EOF");
1510 #        cv = newXS(\"$name\", XS_$Full_func_name, file);
1511 #        $interface_macro_set(cv,$value) ;
1512 EOF
1513             push(@InitFileCode, Q<<"EOF") if $proto;
1514 #        sv_setpv((SV*)cv$proto) ;
1515 EOF
1516         }
1517     }
1518     else {
1519         push(@InitFileCode,
1520              "        ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1521     }
1522 }
1523
1524 # print initialization routine
1525
1526 print Q<<"EOF";
1527 ##ifdef __cplusplus
1528 #extern "C"
1529 ##endif
1530 EOF
1531
1532 print Q<<"EOF";
1533 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1534 #XS(boot_$Module_cname)
1535 EOF
1536
1537 print Q<<"EOF";
1538 #[[
1539 #    dXSARGS;
1540 EOF
1541
1542 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1543 #so `file' is unused
1544 print Q<<"EOF" if $Full_func_name;
1545 #    char* file = __FILE__;
1546 EOF
1547
1548 print Q "#\n";
1549
1550 print Q<<"EOF" if $WantVersionChk ;
1551 #    XS_VERSION_BOOTCHECK ;
1552 #
1553 EOF
1554
1555 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1556 #    {
1557 #        CV * cv ;
1558 #
1559 EOF
1560
1561 print @InitFileCode;
1562
1563 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1564 #    }
1565 EOF
1566
1567 if (@BootCode)
1568 {
1569     print "\n    /* Initialisation Section */\n\n" ;
1570     @line = @BootCode;
1571     print_section();
1572     print "\n    /* End of Initialisation Section */\n\n" ;
1573 }
1574
1575 print Q<<"EOF";;
1576 #    XSRETURN_YES;
1577 #]]
1578 #
1579 EOF
1580
1581 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n") 
1582     unless $ProtoUsed ;
1583 &Exit;
1584
1585 sub output_init {
1586     local($type, $num, $var, $init, $name_printed) = @_;
1587     local($arg) = "ST(" . ($num - 1) . ")";
1588
1589     if(  $init =~ /^=/  ) {
1590         if ($name_printed) {
1591           eval qq/print " $init\\n"/;
1592         } else {
1593           eval qq/print "\\t$var $init\\n"/;
1594         }
1595         warn $@   if  $@;
1596     } else {
1597         if(  $init =~ s/^\+//  &&  $num  ) {
1598             &generate_init($type, $num, $var, $name_printed);
1599         } elsif ($name_printed) {
1600             print ";\n";
1601             $init =~ s/^;//;
1602         } else {
1603             eval qq/print "\\t$var;\\n"/;
1604             warn $@   if  $@;
1605             $init =~ s/^;//;
1606         }
1607         $deferred .= eval qq/"\\n\\t$init\\n"/;
1608         warn $@   if  $@;
1609     }
1610 }
1611
1612 sub Warn
1613 {
1614     # work out the line number
1615     my $line_no = $line_no[@line_no - @line -1] ;
1616  
1617     print STDERR "@_ in $filename, line $line_no\n" ;
1618 }
1619
1620 sub blurt 
1621
1622     Warn @_ ;
1623     $errors ++ 
1624 }
1625
1626 sub death
1627 {
1628     Warn @_ ;
1629     exit 1 ;
1630 }
1631
1632 sub generate_init {
1633     local($type, $num, $var) = @_;
1634     local($arg) = "ST(" . ($num - 1) . ")";
1635     local($argoff) = $num - 1;
1636     local($ntype);
1637     local($tk);
1638
1639     $type = TidyType($type) ;
1640     blurt("Error: '$type' not in typemap"), return 
1641         unless defined($type_kind{$type});
1642
1643     ($ntype = $type) =~ s/\s*\*/Ptr/g;
1644     ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1645     $tk = $type_kind{$type};
1646     $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1647     if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1648       print "\t$var" unless $name_printed;
1649       print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1650       die "default value not supported with length(NAME) supplied"
1651         if defined $defaults{$var};
1652       return;
1653     }
1654     $type =~ tr/:/_/;
1655     blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1656         unless defined $input_expr{$tk} ;
1657     $expr = $input_expr{$tk};
1658     if ($expr =~ /DO_ARRAY_ELEM/) {
1659         blurt("Error: '$subtype' not in typemap"), return 
1660             unless defined($type_kind{$subtype});
1661         blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1662             unless defined $input_expr{$type_kind{$subtype}} ;
1663         $subexpr = $input_expr{$type_kind{$subtype}};
1664         $subexpr =~ s/\$type/\$subtype/g;
1665         $subexpr =~ s/ntype/subtype/g;
1666         $subexpr =~ s/\$arg/ST(ix_$var)/g;
1667         $subexpr =~ s/\n\t/\n\t\t/g;
1668         $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1669         $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1670         $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1671     }
1672     if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1673         $ScopeThisXSUB = 1;
1674     }
1675     if (defined($defaults{$var})) {
1676             $expr =~ s/(\t+)/$1    /g;
1677             $expr =~ s/        /\t/g;
1678             if ($name_printed) {
1679               print ";\n";
1680             } else {
1681               eval qq/print "\\t$var;\\n"/;
1682               warn $@   if  $@;
1683             }
1684             if ($defaults{$var} eq 'NO_INIT') {
1685                 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1686             } else {
1687                 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t    $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1688             }
1689             warn $@   if  $@;
1690     } elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1691             if ($name_printed) {
1692               print ";\n";
1693             } else {
1694               eval qq/print "\\t$var;\\n"/;
1695               warn $@   if  $@;
1696             }
1697             $deferred .= eval qq/"\\n$expr;\\n"/;
1698             warn $@   if  $@;
1699     } else {
1700             die "panic: do not know how to handle this branch for function pointers"
1701               if $name_printed;
1702             eval qq/print "$expr;\\n"/;
1703             warn $@   if  $@;
1704     }
1705 }
1706
1707 sub generate_output {
1708     local($type, $num, $var, $do_setmagic, $do_push) = @_;
1709     local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1710     local($argoff) = $num - 1;
1711     local($ntype);
1712
1713     $type = TidyType($type) ;
1714     if ($type =~ /^array\(([^,]*),(.*)\)/) {
1715             print "\t$arg = sv_newmortal();\n";
1716             print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1717             print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1718     } else {
1719             blurt("Error: '$type' not in typemap"), return
1720                 unless defined($type_kind{$type});
1721             blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1722                 unless defined $output_expr{$type_kind{$type}} ;
1723             ($ntype = $type) =~ s/\s*\*/Ptr/g;
1724             $ntype =~ s/\(\)//g;
1725             ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1726             $expr = $output_expr{$type_kind{$type}};
1727             if ($expr =~ /DO_ARRAY_ELEM/) {
1728                 blurt("Error: '$subtype' not in typemap"), return
1729                     unless defined($type_kind{$subtype});
1730                 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1731                     unless defined $output_expr{$type_kind{$subtype}} ;
1732                 $subexpr = $output_expr{$type_kind{$subtype}};
1733                 $subexpr =~ s/ntype/subtype/g;
1734                 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1735                 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1736                 $subexpr =~ s/\n\t/\n\t\t/g;
1737                 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1738                 eval "print qq\a$expr\a";
1739                 warn $@   if  $@;
1740                 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1741             }
1742             elsif ($var eq 'RETVAL') {
1743                 if ($expr =~ /^\t\$arg = new/) {
1744                     # We expect that $arg has refcnt 1, so we need to
1745                     # mortalize it.
1746                     eval "print qq\a$expr\a";
1747                     warn $@   if  $@;
1748                     print "\tsv_2mortal(ST($num));\n";
1749                     print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1750                 }
1751                 elsif ($expr =~ /^\s*\$arg\s*=/) {
1752                     # We expect that $arg has refcnt >=1, so we need
1753                     # to mortalize it!
1754                     eval "print qq\a$expr\a";
1755                     warn $@   if  $@;
1756                     print "\tsv_2mortal(ST(0));\n";
1757                     print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1758                 }
1759                 else {
1760                     # Just hope that the entry would safely write it
1761                     # over an already mortalized value. By
1762                     # coincidence, something like $arg = &sv_undef
1763                     # works too.
1764                     print "\tST(0) = sv_newmortal();\n";
1765                     eval "print qq\a$expr\a";
1766                     warn $@   if  $@;
1767                     # new mortals don't have set magic
1768                 }
1769             }
1770             elsif ($do_push) {
1771                 print "\tPUSHs(sv_newmortal());\n";
1772                 $arg = "ST($num)";
1773                 eval "print qq\a$expr\a";
1774                 warn $@   if  $@;
1775                 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1776             }
1777             elsif ($arg =~ /^ST\(\d+\)$/) {
1778                 eval "print qq\a$expr\a";
1779                 warn $@   if  $@;
1780                 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1781             }
1782     }
1783 }
1784
1785 sub map_type {
1786     my($type, $varname) = @_;
1787
1788     $type =~ tr/:/_/;
1789     $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1790     if ($varname) {
1791       if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1792         (substr $type, pos $type, 0) = " $varname ";
1793       } else {
1794         $type .= "\t$varname";
1795       }
1796     }
1797     $type;
1798 }
1799
1800
1801 sub Exit {
1802 # If this is VMS, the exit status has meaning to the shell, so we
1803 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1804 # arbitrary number.
1805 #    exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1806     exit ($errors ? 1 : 0);
1807 }