d43eb1cb232de4fc328409fb7402d96cf31f58e7
[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<-typemap typemap>]... file.xs
10
11 =head1 DESCRIPTION
12
13 I<xsubpp> will compile XS code into C code by embedding the constructs
14 necessary to let C functions manipulate Perl values and creates the glue
15 necessary to let Perl access those functions.  The compiler uses typemaps to
16 determine how to map C function parameters and variables to Perl values.
17
18 The compiler will search for typemap files called I<typemap>.  It will use
19 the following search path to find default typemaps, with the rightmost
20 typemap taking precedence.
21
22         ../../../typemap:../../typemap:../typemap:typemap
23
24 =head1 OPTIONS
25
26 =over 5
27
28 =item B<-C++>
29
30 Adds ``extern "C"'' to the C code.
31
32
33 =item B<-except>
34
35 Adds exception handling stubs to the C code.
36
37 =item B<-typemap typemap>
38
39 Indicates that a user-supplied typemap should take precedence over the
40 default typemaps.  This option may be used multiple times, with the last
41 typemap having the highest precedence.
42
43 =item B<-v>
44
45 Prints the I<xsubpp> version number to standard output, then exits.
46
47 =item B<-prototypes>
48
49 By default I<xsubpp> will not automatically generate prototype code for
50 all xsubs. This flag will enable prototypes.
51
52 =item B<-noversioncheck>
53
54 Disables the run time test that determines if the object file (derived
55 from the C<.xs> file) and the C<.pm> files have the same version
56 number.
57
58 =back
59
60 =head1 ENVIRONMENT
61
62 No environment variables are used.
63
64 =head1 AUTHOR
65
66 Larry Wall
67
68 =head1 MODIFICATION HISTORY
69
70 See the file F<changes.pod>.
71
72 =head1 SEE ALSO
73
74 perl(1), perlxs(1), perlxstut(1), perlxs(1)
75
76 =cut
77
78 # Global Constants
79 $XSUBPP_version = "1.940";
80 require 5.002;
81 use vars '$cplusplus';
82
83 sub Q ;
84
85 $FH = 'File0000' ;
86
87 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-s pattern] [-typemap typemap]... file.xs\n";
88
89 $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
90
91 $except = "";
92 $WantPrototypes = -1 ;
93 $WantVersionChk = 1 ;
94 $ProtoUsed = 0 ;
95 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
96     $flag = shift @ARGV;
97     $flag =~ s/^-// ;
98     $spat = quotemeta shift,    next SWITCH     if $flag eq 's';
99     $cplusplus = 1,     next SWITCH     if $flag eq 'C++';
100     $WantPrototypes = 0, next SWITCH    if $flag eq 'noprototypes';
101     $WantPrototypes = 1, next SWITCH    if $flag eq 'prototypes';
102     $WantVersionChk = 0, next SWITCH    if $flag eq 'noversioncheck';
103     $WantVersionChk = 1, next SWITCH    if $flag eq 'versioncheck';
104     $except = " TRY",   next SWITCH     if $flag eq 'except';
105     push(@tm,shift),    next SWITCH     if $flag eq 'typemap';
106     (print "xsubpp version $XSUBPP_version\n"), exit    
107         if $flag eq 'v';
108     die $usage;
109 }
110 if ($WantPrototypes == -1)
111   { $WantPrototypes = 0}
112 else
113   { $ProtoUsed = 1 }
114
115
116 @ARGV == 1 or die $usage;
117 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
118         or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
119         or ($dir, $filename) = ('.', $ARGV[0]);
120 chdir($dir);
121 # Check for VMS; Config.pm may not be installed yet, but this routine
122 # is built into VMS perl
123 if (defined(&VMS::Filespec::vmsify)) { $Is_VMS = 1; $pwd = $ENV{DEFAULT}; }
124 else                                 { $Is_VMS = 0; chomp($pwd = `pwd`);   }
125
126 ++ $IncludedFiles{$ARGV[0]} ;
127
128 my(@XSStack) = ({type => 'none'});      # Stack of conditionals and INCLUDEs
129 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
130
131 sub TrimWhitespace
132 {
133     $_[0] =~ s/^\s+|\s+$//go ;
134 }
135
136 sub TidyType
137 {
138     local ($_) = @_ ;
139
140     # rationalise any '*' by joining them into bunches and removing whitespace
141     s#\s*(\*+)\s*#$1#g;
142     s#(\*+)# $1 #g ;
143
144     # change multiple whitespace into a single space
145     s/\s+/ /g ;
146     
147     # trim leading & trailing whitespace
148     TrimWhitespace($_) ;
149
150     $_ ;
151 }
152
153 $typemap = shift @ARGV;
154 foreach $typemap (@tm) {
155     die "Can't find $typemap in $pwd\n" unless -r $typemap;
156 }
157 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
158                 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
159                 ../typemap typemap);
160 foreach $typemap (@tm) {
161     next unless -e $typemap ;
162     # skip directories, binary files etc.
163     warn("Warning: ignoring non-text typemap file '$typemap'\n"), next 
164         unless -T $typemap ;
165     open(TYPEMAP, $typemap) 
166         or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
167     $mode = 'Typemap';
168     $junk = "" ;
169     $current = \$junk;
170     while (<TYPEMAP>) {
171         next if /^\s*#/;
172         my $line_no = $. + 1; 
173         if (/^INPUT\s*$/)   { $mode = 'Input';   $current = \$junk;  next; }
174         if (/^OUTPUT\s*$/)  { $mode = 'Output';  $current = \$junk;  next; }
175         if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk;  next; }
176         if ($mode eq 'Typemap') {
177             chomp;
178             my $line = $_ ;
179             TrimWhitespace($_) ;
180             # skip blank lines and comment lines
181             next if /^$/ or /^#/ ;
182             my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
183                 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
184             $type = TidyType($type) ;
185             $type_kind{$type} = $kind ;
186             # prototype defaults to '$'
187             $proto = "\$" unless $proto ;
188             warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n") 
189                 unless ValidProtoString($proto) ;
190             $proto_letter{$type} = C_string($proto) ;
191         }
192         elsif (/^\s/) {
193             $$current .= $_;
194         }
195         elsif ($mode eq 'Input') {
196             s/\s+$//;
197             $input_expr{$_} = '';
198             $current = \$input_expr{$_};
199         }
200         else {
201             s/\s+$//;
202             $output_expr{$_} = '';
203             $current = \$output_expr{$_};
204         }
205     }
206     close(TYPEMAP);
207 }
208
209 foreach $key (keys %input_expr) {
210     $input_expr{$key} =~ s/\n+$//;
211 }
212
213 $END = "!End!\n\n";             # "impossible" keyword (multiple newline)
214
215 # Match an XS keyword
216 $BLOCK_re= '\s*(' . join('|', qw(
217         REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT 
218         CLEANUP ALIAS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
219         SCOPE
220         )) . "|$END)\\s*:";
221
222 # Input:  ($_, @line) == unparsed input.
223 # Output: ($_, @line) == (rest of line, following lines).
224 # Return: the matched keyword if found, otherwise 0
225 sub check_keyword {
226         $_ = shift(@line) while !/\S/ && @line;
227         s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
228 }
229
230
231 sub print_section {
232     my $count = 0;
233     $_ = shift(@line) while !/\S/ && @line;
234     for (;  defined($_) && !/^$BLOCK_re/o;  $_ = shift(@line)) {
235         print line_directive() unless ($count++);
236         print "$_\n";
237     }
238 }
239
240 sub process_keyword($)
241 {
242     my($pattern) = @_ ;
243     my $kwd ;
244
245     &{"${kwd}_handler"}() 
246         while $kwd = check_keyword($pattern) ;
247     print line_directive();
248 }
249
250 sub CASE_handler {
251     blurt ("Error: `CASE:' after unconditional `CASE:'")
252         if $condnum && $cond eq '';
253     $cond = $_;
254     TrimWhitespace($cond);
255     print "   ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
256     $_ = '' ;
257 }
258
259 sub INPUT_handler {
260     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
261         last if /^\s*NOT_IMPLEMENTED_YET/;
262         next unless /\S/;       # skip blank lines 
263
264         TrimWhitespace($_) ;
265         my $line = $_ ;
266
267         # remove trailing semicolon if no initialisation
268         s/\s*;$//g unless /=/ ;
269
270         # check for optional initialisation code
271         my $var_init = '' ;
272         $var_init = $1 if s/\s*(=.*)$//s ;
273         $var_init =~ s/"/\\"/g;
274
275         s/\s+/ /g;
276         my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
277             or blurt("Error: invalid argument declaration '$line'"), next;
278
279         # Check for duplicate definitions
280         blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
281             if $arg_list{$var_name} ++  ;
282
283         $thisdone |= $var_name eq "THIS";
284         $retvaldone |= $var_name eq "RETVAL";
285         $var_types{$var_name} = $var_type;
286         print "\t" . &map_type($var_type);
287         $var_num = $args_match{$var_name};
288
289         $proto_arg[$var_num] = ProtoString($var_type) 
290             if $var_num ;
291         if ($var_addr) {
292             $var_addr{$var_name} = 1;
293             $func_args =~ s/\b($var_name)\b/&$1/;
294         }
295         if ($var_init =~ /^=\s*NO_INIT\s*;?\s*$/) {
296             print "\t$var_name;\n";
297         } elsif ($var_init =~ /\S/) {
298             &output_init($var_type, $var_num, "$var_name $var_init");
299         } elsif ($var_num) {
300             # generate initialization code
301             &generate_init($var_type, $var_num, $var_name);
302         } else {
303             print ";\n";
304         }
305     }
306 }
307
308 sub OUTPUT_handler {
309     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
310         next unless /\S/;
311         my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
312         blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
313             if $outargs{$outarg} ++ ;
314         if (!$gotRETVAL and $outarg eq 'RETVAL') {
315             # deal with RETVAL last
316             $RETVAL_code = $outcode ;
317             $gotRETVAL = 1 ;
318             next ;
319         }
320         blurt ("Error: OUTPUT $outarg not an argument"), next
321             unless defined($args_match{$outarg});
322         blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
323             unless defined $var_types{$outarg} ;
324         print line_directive();
325         if ($outcode) {
326             print "\t$outcode\n";
327         } else {
328             $var_num = $args_match{$outarg};
329             &generate_output($var_types{$outarg}, $var_num, $outarg); 
330         }
331     }
332 }
333
334 sub CLEANUP_handler() { print_section() } 
335 sub PREINIT_handler() { print_section() } 
336 sub INIT_handler()    { print_section() } 
337
338 sub GetAliases
339 {
340     my ($line) = @_ ;
341     my ($orig) = $line ;
342     my ($alias) ;
343     my ($value) ;
344
345     # Parse alias definitions
346     # format is
347     #    alias = value alias = value ...
348
349     while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
350         $alias = $1 ;
351         $orig_alias = $alias ;
352         $value = $2 ;
353
354         # check for optional package definition in the alias
355         $alias = $Packprefix . $alias if $alias !~ /::/ ;
356         
357         # check for duplicate alias name & duplicate value
358         Warn("Warning: Ignoring duplicate alias '$orig_alias'")
359             if defined $XsubAliases{$alias} ;
360
361         Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
362             if $XsubAliasValues{$value} ;
363
364         $XsubAliases = 1;
365         $XsubAliases{$alias} = $value ;
366         $XsubAliasValues{$value} = $orig_alias ;
367     }
368
369     blurt("Error: Cannot parse ALIAS definitions from '$orig'")
370         if $line ;
371 }
372
373 sub ALIAS_handler ()
374 {
375     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
376         next unless /\S/;
377         TrimWhitespace($_) ;
378         GetAliases($_) if $_ ;
379     }
380 }
381
382 sub REQUIRE_handler ()
383 {
384     # the rest of the current line should contain a version number
385     my ($Ver) = $_ ;
386
387     TrimWhitespace($Ver) ;
388
389     death ("Error: REQUIRE expects a version number")
390         unless $Ver ;
391
392     # check that the version number is of the form n.n
393     death ("Error: REQUIRE: expected a number, got '$Ver'")
394         unless $Ver =~ /^\d+(\.\d*)?/ ;
395
396     death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
397         unless $XSUBPP_version >= $Ver ; 
398 }
399
400 sub VERSIONCHECK_handler ()
401 {
402     # the rest of the current line should contain either ENABLE or
403     # DISABLE
404  
405     TrimWhitespace($_) ;
406  
407     # check for ENABLE/DISABLE
408     death ("Error: VERSIONCHECK: ENABLE/DISABLE")
409         unless /^(ENABLE|DISABLE)/i ;
410  
411     $WantVersionChk = 1 if $1 eq 'ENABLE' ;
412     $WantVersionChk = 0 if $1 eq 'DISABLE' ;
413  
414 }
415
416 sub PROTOTYPE_handler ()
417 {
418     my $specified ;
419
420     death("Error: Only 1 PROTOTYPE definition allowed per xsub") 
421         if $proto_in_this_xsub ++ ;
422
423     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
424         next unless /\S/;
425         $specified = 1 ;
426         TrimWhitespace($_) ;
427         if ($_ eq 'DISABLE') {
428            $ProtoThisXSUB = 0 
429         }
430         elsif ($_ eq 'ENABLE') {
431            $ProtoThisXSUB = 1 
432         }
433         else {
434             # remove any whitespace
435             s/\s+//g ;
436             death("Error: Invalid prototype '$_'")
437                 unless ValidProtoString($_) ;
438             $ProtoThisXSUB = C_string($_) ;
439         }
440     }
441
442     # If no prototype specified, then assume empty prototype ""
443     $ProtoThisXSUB = 2 unless $specified ;
444
445     $ProtoUsed = 1 ;
446
447 }
448
449 sub SCOPE_handler ()
450 {
451     death("Error: Only 1 SCOPE declaration allowed per xsub") 
452         if $scope_in_this_xsub ++ ;
453
454     for (;  !/^$BLOCK_re/o;  $_ = shift(@line)) {
455                 next unless /\S/;
456                 TrimWhitespace($_) ;
457         if ($_ =~ /^DISABLE/i) {
458                    $ScopeThisXSUB = 0 
459         }
460         elsif ($_ =~ /^ENABLE/i) {
461                    $ScopeThisXSUB = 1 
462         }
463     }
464
465 }
466
467 sub PROTOTYPES_handler ()
468 {
469     # the rest of the current line should contain either ENABLE or
470     # DISABLE 
471
472     TrimWhitespace($_) ;
473
474     # check for ENABLE/DISABLE
475     death ("Error: PROTOTYPES: ENABLE/DISABLE")
476         unless /^(ENABLE|DISABLE)/i ;
477
478     $WantPrototypes = 1 if $1 eq 'ENABLE' ;
479     $WantPrototypes = 0 if $1 eq 'DISABLE' ;
480     $ProtoUsed = 1 ;
481
482 }
483
484 sub INCLUDE_handler ()
485 {
486     # the rest of the current line should contain a valid filename
487  
488     TrimWhitespace($_) ;
489  
490     death("INCLUDE: filename missing")
491         unless $_ ;
492
493     death("INCLUDE: output pipe is illegal")
494         if /^\s*\|/ ;
495
496     # simple minded recursion detector
497     death("INCLUDE loop detected")
498         if $IncludedFiles{$_} ;
499
500     ++ $IncludedFiles{$_} unless /\|\s*$/ ;
501
502     # Save the current file context.
503     push(@XSStack, {
504         type            => 'file',
505         LastLine        => $lastline,
506         LastLineNo      => $lastline_no,
507         Line            => \@line,
508         LineNo          => \@line_no,
509         Filename        => $filename,
510         Handle          => $FH,
511         }) ;
512  
513     ++ $FH ;
514
515     # open the new file
516     open ($FH, "$_") or death("Cannot open '$_': $!") ;
517  
518     print Q<<"EOF" ;
519 #
520 #/* INCLUDE:  Including '$_' from '$filename' */
521 #
522 EOF
523
524     $filename = $_ ;
525
526     # Prime the pump by reading the first 
527     # non-blank line
528
529     # skip leading blank lines
530     while (<$FH>) {
531         last unless /^\s*$/ ;
532     }
533
534     $lastline = $_ ;
535     $lastline_no = $. ;
536  
537 }
538  
539 sub PopFile()
540 {
541     return 0 unless $XSStack[-1]{type} eq 'file' ;
542
543     my $data     = pop @XSStack ;
544     my $ThisFile = $filename ;
545     my $isPipe   = ($filename =~ /\|\s*$/) ;
546  
547     -- $IncludedFiles{$filename}
548         unless $isPipe ;
549
550     close $FH ;
551
552     $FH         = $data->{Handle} ;
553     $filename   = $data->{Filename} ;
554     $lastline   = $data->{LastLine} ;
555     $lastline_no = $data->{LastLineNo} ;
556     @line       = @{ $data->{Line} } ;
557     @line_no    = @{ $data->{LineNo} } ;
558
559     if ($isPipe and $? ) {
560         -- $lastline_no ;
561         print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n"  ;
562         exit 1 ;
563     }
564
565     print Q<<"EOF" ;
566 #
567 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
568 #
569 EOF
570
571     return 1 ;
572 }
573
574 sub ValidProtoString ($)
575 {
576     my($string) = @_ ;
577
578     if ( $string =~ /^$proto_re+$/ ) {
579         return $string ;
580     }
581
582     return 0 ;
583 }
584
585 sub C_string ($)
586 {
587     my($string) = @_ ;
588
589     $string =~ s[\\][\\\\]g ;
590     $string ;
591 }
592
593 sub ProtoString ($)
594 {
595     my ($type) = @_ ;
596
597     $proto_letter{$type} or "\$" ;
598 }
599
600 sub check_cpp {
601     my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
602     if (@cpp) {
603         my ($cpp, $cpplevel);
604         for $cpp (@cpp) {
605             if ($cpp =~ /^\#\s*if/) {
606                 $cpplevel++;
607             } elsif (!$cpplevel) {
608                 Warn("Warning: #else/elif/endif without #if in this function");
609                 print STDERR "    (precede it with a blank line if the matching #if is outside the function)\n"
610                     if $XSStack[-1]{type} eq 'if';
611                 return;
612             } elsif ($cpp =~ /^\#\s*endif/) {
613                 $cpplevel--;
614             }
615         }
616         Warn("Warning: #if without #endif in this function") if $cpplevel;
617     }
618 }
619
620
621 sub Q {
622     my($text) = @_;
623     $text =~ s/^#//gm;
624     $text =~ s/\[\[/{/g;
625     $text =~ s/\]\]/}/g;
626     $text;
627 }
628
629 open($FH, $filename) or die "cannot open $filename: $!\n";
630
631 # Identify the version of xsubpp used
632 print <<EOM ;
633 /*
634  * This file was generated automatically by xsubpp version $XSUBPP_version from the 
635  * contents of $filename. Do not edit this file, edit $filename instead.
636  *
637  *      ANY CHANGES MADE HERE WILL BE LOST! 
638  *
639  */
640
641 EOM
642 print "#line 1 \"$filename\"\n"; 
643
644 while (<$FH>) {
645     last if ($Module, $Package, $Prefix) =
646         /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
647     print $_;
648 }
649 &Exit unless defined $_;
650
651 $lastline    = $_;
652 $lastline_no = $.;
653
654 # Read next xsub into @line from ($lastline, <$FH>).
655 sub fetch_para {
656     # parse paragraph
657     death ("Error: Unterminated `#if/#ifdef/#ifndef'")
658         if !defined $lastline && $XSStack[-1]{type} eq 'if';
659     @line = ();
660     @line_no = () ;
661     return PopFile() if !defined $lastline;
662
663     if ($lastline =~
664         /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
665         $Module = $1;
666         $Package = defined($2) ? $2 : '';       # keep -w happy
667         $Prefix  = defined($3) ? $3 : '';       # keep -w happy
668         $Prefix = quotemeta $Prefix ;
669         ($Module_cname = $Module) =~ s/\W/_/g;
670         ($Packid = $Package) =~ tr/:/_/;
671         $Packprefix = $Package;
672         $Packprefix .= "::" if $Packprefix ne "";
673         $lastline = "";
674     }
675
676     for(;;) {
677         if ($lastline !~ /^\s*#/ ||
678             # CPP directives:
679             #   ANSI:   if ifdef ifndef elif else endif define undef
680             #           line error pragma
681             #   gcc:    warning include_next
682             #   obj-c:  import
683             #   others: ident (gcc notes that some cpps have this one)
684             $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
685             last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
686             push(@line, $lastline);
687             push(@line_no, $lastline_no) ;
688         }
689
690         # Read next line and continuation lines
691         last unless defined($lastline = <$FH>);
692         $lastline_no = $.;
693         my $tmp_line;
694         $lastline .= $tmp_line
695             while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
696             
697         chomp $lastline;
698         $lastline =~ s/^\s+$//;
699     }
700     pop(@line), pop(@line_no) while @line && $line[-1] eq "";
701     1;
702 }
703
704 PARAGRAPH:
705 while (fetch_para()) {
706     # Print initial preprocessor statements and blank lines
707     while (@line && $line[0] !~ /^[^\#]/) {
708         my $line = shift(@line);
709         print $line, "\n";
710         next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
711         my $statement = $+;
712         if ($statement eq 'if') {
713             $XSS_work_idx = @XSStack;
714             push(@XSStack, {type => 'if'});
715         } else {
716             death ("Error: `$statement' with no matching `if'")
717                 if $XSStack[-1]{type} ne 'if';
718             if ($XSStack[-1]{varname}) {
719                 push(@InitFileCode, "#endif\n");
720                 push(@BootCode,     "#endif");
721             }
722
723             my(@fns) = keys %{$XSStack[-1]{functions}};
724             if ($statement ne 'endif') {
725                 # Hide the functions defined in other #if branches, and reset.
726                 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
727                 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
728             } else {
729                 my($tmp) = pop(@XSStack);
730                 0 while (--$XSS_work_idx
731                          && $XSStack[$XSS_work_idx]{type} ne 'if');
732                 # Keep all new defined functions
733                 push(@fns, keys %{$tmp->{other_functions}});
734                 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
735             }
736         }
737     }
738
739     next PARAGRAPH unless @line;
740
741     if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
742         # We are inside an #if, but have not yet #defined its xsubpp variable.
743         print "#define $cpp_next_tmp 1\n\n";
744         push(@InitFileCode, "#if $cpp_next_tmp\n");
745         push(@BootCode,     "#if $cpp_next_tmp");
746         $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
747     }
748
749     death ("Code is not inside a function"
750            ." (maybe last function was ended by a blank line "
751            ." followed by a a statement on column one?)")
752         if $line[0] =~ /^\s/;
753
754     # initialize info arrays
755     undef(%args_match);
756     undef(%var_types);
757     undef(%var_addr);
758     undef(%defaults);
759     undef($class);
760     undef($static);
761     undef($elipsis);
762     undef($wantRETVAL) ;
763     undef(%arg_list) ;
764     undef(@proto_arg) ;
765     undef($proto_in_this_xsub) ;
766     undef($scope_in_this_xsub) ;
767     $ProtoThisXSUB = $WantPrototypes ;
768     $ScopeThisXSUB = 0;
769
770     $_ = shift(@line);
771     while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
772         &{"${kwd}_handler"}() ;
773         next PARAGRAPH unless @line ;
774         $_ = shift(@line);
775     }
776
777     if (check_keyword("BOOT")) {
778         &check_cpp;
779         push (@BootCode, $_, line_directive(), @line, "") ;
780         next PARAGRAPH ;
781     }
782
783
784     # extract return type, function name and arguments
785     my($ret_type) = TidyType($_);
786
787     # a function definition needs at least 2 lines
788     blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
789         unless @line ;
790
791     $static = 1 if $ret_type =~ s/^static\s+//;
792
793     $func_header = shift(@line);
794     blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
795         unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*$/s;
796
797     ($class, $func_name, $orig_args) =  ($1, $2, $3) ;
798     ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
799     ($clean_func_name = $func_name) =~ s/^$Prefix//;
800     $Full_func_name = "${Packid}_$clean_func_name";
801
802     # Check for duplicate function definition
803     for $tmp (@XSStack) {
804         next unless defined $tmp->{functions}{$Full_func_name};
805         Warn("Warning: duplicate function definition '$clean_func_name' detected");
806         last;
807     }
808     $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
809     %XsubAliases = %XsubAliasValues = ();
810
811     @args = split(/\s*,\s*/, $orig_args);
812     if (defined($class)) {
813         my $arg0 = ((defined($static) or $func_name =~ /^new/) ? "CLASS" : "THIS");
814         unshift(@args, $arg0);
815         ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
816     }
817     $orig_args =~ s/"/\\"/g;
818     $min_args = $num_args = @args;
819     foreach $i (0..$num_args-1) {
820             if ($args[$i] =~ s/\.\.\.//) {
821                     $elipsis = 1;
822                     $min_args--;
823                     if ($args[$i] eq '' && $i == $num_args - 1) {
824                         pop(@args);
825                         last;
826                     }
827             }
828             if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
829                     $min_args--;
830                     $args[$i] = $1;
831                     $defaults{$args[$i]} = $2;
832                     $defaults{$args[$i]} =~ s/"/\\"/g;
833             }
834             $proto_arg[$i+1] = "\$" ;
835     }
836     if (defined($class)) {
837             $func_args = join(", ", @args[1..$#args]);
838     } else {
839             $func_args = join(", ", @args);
840     }
841     @args_match{@args} = 1..@args;
842
843     $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
844     $CODE = grep(/^\s*CODE\s*:/, @line);
845     $ALIAS  = grep(/^\s*ALIAS\s*:/,  @line);
846
847     # print function header
848     print Q<<"EOF";
849 #XS(XS_${Full_func_name})
850 #[[
851 #    dXSARGS;
852 EOF
853     print Q<<"EOF" if $ALIAS ;
854 #    dXSI32;
855 EOF
856     if ($elipsis) {
857         $cond = ($min_args ? qq(items < $min_args) : 0);
858     }
859     elsif ($min_args == $num_args) {
860         $cond = qq(items != $min_args);
861     }
862     else {
863         $cond = qq(items < $min_args || items > $num_args);
864     }
865
866     print Q<<"EOF" if $except;
867 #    char errbuf[1024];
868 #    *errbuf = '\0';
869 EOF
870
871     if ($ALIAS) 
872       { print Q<<"EOF" if $cond }
873 #    if ($cond)
874 #       croak("Usage: %s($orig_args)", GvNAME(CvGV(cv)));
875 EOF
876     else 
877       { print Q<<"EOF" if $cond }
878 #    if ($cond)
879 #       croak("Usage: $pname($orig_args)");
880 EOF
881
882     print Q<<"EOF" if $PPCODE;
883 #    SP -= items;
884 EOF
885
886     # Now do a block of some sort.
887
888     $condnum = 0;
889     $cond = '';                 # last CASE: condidional
890     push(@line, "$END:");
891     push(@line_no, $line_no[-1]);
892     $_ = '';
893     &check_cpp;
894     while (@line) {
895         &CASE_handler if check_keyword("CASE");
896         print Q<<"EOF";
897 #   $except [[
898 EOF
899
900         # do initialization of input variables
901         $thisdone = 0;
902         $retvaldone = 0;
903         $deferred = "";
904         %arg_list = () ;
905         $gotRETVAL = 0;
906
907         INPUT_handler() ;
908         process_keyword("INPUT|PREINIT|ALIAS|PROTOTYPE|SCOPE") ;
909
910         print Q<<"EOF" if $ScopeThisXSUB;
911 #   ENTER;
912 #   [[
913 EOF
914         
915         if (!$thisdone && defined($class)) {
916             if (defined($static) or $func_name =~ /^new/) {
917                 print "\tchar *";
918                 $var_types{"CLASS"} = "char *";
919                 &generate_init("char *", 1, "CLASS");
920             }
921             else {
922                 print "\t$class *";
923                 $var_types{"THIS"} = "$class *";
924                 &generate_init("$class *", 1, "THIS");
925             }
926         }
927
928         # do code
929         if (/^\s*NOT_IMPLEMENTED_YET/) {
930                 print "\n\tcroak(\"$pname: not implemented yet\");\n";
931                 $_ = '' ;
932         } else {
933                 if ($ret_type ne "void") {
934                         print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
935                                 if !$retvaldone;
936                         $args_match{"RETVAL"} = 0;
937                         $var_types{"RETVAL"} = $ret_type;
938                 }
939
940                 print $deferred;
941
942         process_keyword("INIT|ALIAS|PROTOTYPE") ;
943
944                 if (check_keyword("PPCODE")) {
945                         print_section();
946                         death ("PPCODE must be last thing") if @line;
947                         print "\tLEAVE;\n" if $ScopeThisXSUB;
948                         print "\tPUTBACK;\n\treturn;\n";
949                 } elsif (check_keyword("CODE")) {
950                         print_section() ;
951                 } elsif (defined($class) and $func_name eq "DESTROY") {
952                         print "\n\t";
953                         print "delete THIS;\n";
954                 } else {
955                         print "\n\t";
956                         if ($ret_type ne "void") {
957                                 print "RETVAL = ";
958                                 $wantRETVAL = 1;
959                         }
960                         if (defined($static)) {
961                             if ($func_name =~ /^new/) {
962                                 $func_name = "$class";
963                             } else {
964                                 print "${class}::";
965                             }
966                         } elsif (defined($class)) {
967                             if ($func_name =~ /^new/) {
968                                 $func_name .= " $class";
969                             } else {
970                                 print "THIS->";
971                             }
972                         }
973                         $func_name =~ s/^($spat)//
974                             if defined($spat);
975                         print "$func_name($func_args);\n";
976                 }
977         }
978
979         # do output variables
980         $gotRETVAL = 0;
981         undef $RETVAL_code ;
982         undef %outargs ;
983         process_keyword("OUTPUT|ALIAS|PROTOTYPE"); 
984
985         # all OUTPUT done, so now push the return value on the stack
986         if ($gotRETVAL && $RETVAL_code) {
987             print "\t$RETVAL_code\n";
988         } elsif ($gotRETVAL || $wantRETVAL) {
989             &generate_output($ret_type, 0, 'RETVAL');
990         }
991         print line_directive();
992
993         # do cleanup
994         process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
995
996         print Q<<"EOF" if $ScopeThisXSUB;
997 #   ]]
998 EOF
999         print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1000 #   LEAVE;
1001 EOF
1002
1003         # print function trailer
1004         print Q<<EOF;
1005 #    ]]
1006 EOF
1007         print Q<<EOF if $except;
1008 #    BEGHANDLERS
1009 #    CATCHALL
1010 #       sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1011 #    ENDHANDLERS
1012 EOF
1013         if (check_keyword("CASE")) {
1014             blurt ("Error: No `CASE:' at top of function")
1015                 unless $condnum;
1016             $_ = "CASE: $_";    # Restore CASE: label
1017             next;
1018         }
1019         last if $_ eq "$END:";
1020         death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1021     }
1022
1023     print Q<<EOF if $except;
1024 #    if (errbuf[0])
1025 #       croak(errbuf);
1026 EOF
1027
1028     if ($ret_type ne "void" or $CODE) {
1029         print Q<<EOF unless $PPCODE;
1030 #    XSRETURN(1);
1031 EOF
1032     } else {
1033         print Q<<EOF unless $PPCODE;
1034 #    XSRETURN_EMPTY;
1035 EOF
1036     }
1037
1038     print Q<<EOF;
1039 #]]
1040 #
1041 EOF
1042
1043     my $newXS = "newXS" ;
1044     my $proto = "" ;
1045
1046     # Build the prototype string for the xsub
1047     if ($ProtoThisXSUB) {
1048         $newXS = "newXSproto";
1049
1050         if ($ProtoThisXSUB == 2) {
1051             # User has specified empty prototype
1052             $proto = ', ""' ;
1053         }
1054         elsif ($ProtoThisXSUB != 1) {
1055             # User has specified a prototype
1056             $proto = ', "' . $ProtoThisXSUB . '"';
1057         }
1058         else {
1059             my $s = ';';
1060             if ($min_args < $num_args)  {
1061                 $s = ''; 
1062                 $proto_arg[$min_args] .= ";" ;
1063             }
1064             push @proto_arg, "$s\@" 
1065                 if $elipsis ;
1066     
1067             $proto = ', "' . join ("", @proto_arg) . '"';
1068         }
1069     }
1070
1071     if (%XsubAliases) {
1072         $XsubAliases{$pname} = 0 
1073             unless defined $XsubAliases{$pname} ;
1074         while ( ($name, $value) = each %XsubAliases) {
1075             push(@InitFileCode, Q<<"EOF");
1076 #        cv = newXS(\"$name\", XS_$Full_func_name, file);
1077 #        XSANY.any_i32 = $value ;
1078 EOF
1079         push(@InitFileCode, Q<<"EOF") if $proto;
1080 #        sv_setpv((SV*)cv$proto) ;
1081 EOF
1082         }
1083     }
1084     else {
1085         push(@InitFileCode,
1086              "        ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1087     }
1088 }
1089
1090 # print initialization routine
1091 print Q<<"EOF";
1092 ##ifdef __cplusplus
1093 #extern "C"
1094 ##endif
1095 #XS(boot_$Module_cname)
1096 #[[
1097 #    dXSARGS;
1098 #    char* file = __FILE__;
1099 #
1100 EOF
1101
1102 print Q<<"EOF" if $WantVersionChk ;
1103 #    XS_VERSION_BOOTCHECK ;
1104 #
1105 EOF
1106
1107 print Q<<"EOF" if defined $XsubAliases ;
1108 #    {
1109 #        CV * cv ;
1110 #
1111 EOF
1112
1113 print @InitFileCode;
1114
1115 print Q<<"EOF" if defined $XsubAliases ;
1116 #    }
1117 EOF
1118
1119 if (@BootCode)
1120 {
1121     print "\n    /* Initialisation Section */\n" ;
1122     print grep (s/$/\n/, @BootCode) ;
1123     print "\n    /* End of Initialisation Section */\n\n" ;
1124 }
1125
1126 print Q<<"EOF";;
1127 #    ST(0) = &sv_yes;
1128 #    XSRETURN(1);
1129 #]]
1130 EOF
1131
1132 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n") 
1133     unless $ProtoUsed ;
1134 &Exit;
1135
1136
1137 sub output_init {
1138     local($type, $num, $init) = @_;
1139     local($arg) = "ST(" . ($num - 1) . ")";
1140
1141     eval qq/print " $init\\\n"/;
1142 }
1143
1144 sub line_directive
1145 {
1146     # work out the line number
1147     my $line_no = $line_no[@line_no - @line -1] ;
1148  
1149     return "#line $line_no \"$filename\"\n" ;
1150
1151 }
1152
1153 sub Warn
1154 {
1155     # work out the line number
1156     my $line_no = $line_no[@line_no - @line -1] ;
1157  
1158     print STDERR "@_ in $filename, line $line_no\n" ;
1159 }
1160
1161 sub blurt 
1162
1163     Warn @_ ;
1164     $errors ++ 
1165 }
1166
1167 sub death
1168 {
1169     Warn @_ ;
1170     exit 1 ;
1171 }
1172
1173 sub generate_init {
1174     local($type, $num, $var) = @_;
1175     local($arg) = "ST(" . ($num - 1) . ")";
1176     local($argoff) = $num - 1;
1177     local($ntype);
1178     local($tk);
1179
1180     $type = TidyType($type) ;
1181     blurt("Error: '$type' not in typemap"), return 
1182         unless defined($type_kind{$type});
1183
1184     ($ntype = $type) =~ s/\s*\*/Ptr/g;
1185     ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1186     $tk = $type_kind{$type};
1187     $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1188     $type =~ tr/:/_/;
1189     blurt("Error: No INPUT definition for type '$type' found"), return
1190         unless defined $input_expr{$tk} ;
1191     $expr = $input_expr{$tk};
1192     if ($expr =~ /DO_ARRAY_ELEM/) {
1193         blurt("Error: '$subtype' not in typemap"), return 
1194             unless defined($type_kind{$subtype});
1195         blurt("Error: No INPUT definition for type '$subtype' found"), return
1196             unless defined $input_expr{$type_kind{$subtype}} ;
1197         $subexpr = $input_expr{$type_kind{$subtype}};
1198         $subexpr =~ s/ntype/subtype/g;
1199         $subexpr =~ s/\$arg/ST(ix_$var)/g;
1200         $subexpr =~ s/\n\t/\n\t\t/g;
1201         $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1202         $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1203         $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1204     }
1205     if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1206         $ScopeThisXSUB = 1;
1207     }
1208     if (defined($defaults{$var})) {
1209             $expr =~ s/(\t+)/$1    /g;
1210             $expr =~ s/        /\t/g;
1211             eval qq/print "\\t$var;\\n"/;
1212             $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t    $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1213     } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1214             eval qq/print "\\t$var;\\n"/;
1215             $deferred .= eval qq/"\\n$expr;\\n"/;
1216     } else {
1217             eval qq/print "$expr;\\n"/;
1218     }
1219 }
1220
1221 sub generate_output {
1222     local($type, $num, $var) = @_;
1223     local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1224     local($argoff) = $num - 1;
1225     local($ntype);
1226
1227     $type = TidyType($type) ;
1228     if ($type =~ /^array\(([^,]*),(.*)\)/) {
1229             print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
1230     } else {
1231             blurt("Error: '$type' not in typemap"), return
1232                 unless defined($type_kind{$type});
1233             blurt("Error: No OUTPUT definition for type '$type' found"), return
1234                 unless defined $output_expr{$type_kind{$type}} ;
1235             ($ntype = $type) =~ s/\s*\*/Ptr/g;
1236             $ntype =~ s/\(\)//g;
1237             ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1238             $expr = $output_expr{$type_kind{$type}};
1239             if ($expr =~ /DO_ARRAY_ELEM/) {
1240                 blurt("Error: '$subtype' not in typemap"), return
1241                     unless defined($type_kind{$subtype});
1242                 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1243                     unless defined $output_expr{$type_kind{$subtype}} ;
1244                 $subexpr = $output_expr{$type_kind{$subtype}};
1245                 $subexpr =~ s/ntype/subtype/g;
1246                 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1247                 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1248                 $subexpr =~ s/\n\t/\n\t\t/g;
1249                 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1250                 eval "print qq\a$expr\a";
1251             }
1252             elsif ($var eq 'RETVAL') {
1253                 if ($expr =~ /^\t\$arg = new/) {
1254                     # We expect that $arg has refcnt 1, so we need to
1255                     # mortalize it.
1256                     eval "print qq\a$expr\a";
1257                     print "\tsv_2mortal(ST(0));\n";
1258                 }
1259                 elsif ($expr =~ /^\s*\$arg\s*=/) {
1260                     # We expect that $arg has refcnt >=1, so we need
1261                     # to mortalize it. However, the extension may have
1262                     # returned the built-in perl value, which is
1263                     # read-only, thus not mortalizable. However, it is
1264                     # safe to leave it as it is, since it would be
1265                     # ignored by REFCNT_dec. Builtin values have REFCNT==0.
1266                     eval "print qq\a$expr\a";
1267                     print "\tif (SvREFCNT(ST(0))) sv_2mortal(ST(0));\n";
1268                 }
1269                 else {
1270                     # Just hope that the entry would safely write it
1271                     # over an already mortalized value. By
1272                     # coincidence, something like $arg = &sv_undef
1273                     # works too.
1274                     print "\tST(0) = sv_newmortal();\n";
1275                     eval "print qq\a$expr\a";
1276                 }
1277             }
1278             elsif ($arg =~ /^ST\(\d+\)$/) {
1279                 eval "print qq\a$expr\a";
1280             }
1281     }
1282 }
1283
1284 sub map_type {
1285     my($type) = @_;
1286
1287     $type =~ tr/:/_/;
1288     $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1289     $type;
1290 }
1291
1292
1293 sub Exit {
1294 # If this is VMS, the exit status has meaning to the shell, so we
1295 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1296 # arbitrary number.
1297     exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1298 }