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