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