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