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