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