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