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