5 xsubpp - compiler to convert Perl XS code into C code
9 B<xsubpp> [B<-v>] [B<-C++>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-typemap typemap>]... file.xs
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.
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.
22 ../../../typemap:../../typemap:../typemap:typemap
30 Adds ``extern "C"'' to the C code.
35 Adds exception handling stubs to the C code.
37 =item B<-typemap typemap>
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.
45 Prints the I<xsubpp> version number to standard output, then exits.
49 By default I<xsubpp> will not automatically generate prototype code for
50 all xsubs. This flag will enable prototypes.
52 =item B<-noversioncheck>
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
62 No environment variables are used.
68 =head1 MODIFICATION HISTORY
70 See the file F<changes.pod>.
74 perl(1), perlxs(1), perlxstut(1), perlxs(1)
80 use vars '$cplusplus';
83 $XSUBPP_version = "1.9401";
84 $Is_VMS = $^O eq 'VMS';
90 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-s pattern] [-typemap typemap]... file.xs\n";
92 $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
95 $WantPrototypes = -1 ;
98 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
101 $spat = quotemeta shift, next SWITCH if $flag eq 's';
102 $cplusplus = 1, next SWITCH if $flag eq 'C++';
103 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
104 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
105 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
106 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
107 $except = " TRY", next SWITCH if $flag eq 'except';
108 push(@tm,shift), next SWITCH if $flag eq 'typemap';
109 (print "xsubpp version $XSUBPP_version\n"), exit
113 if ($WantPrototypes == -1)
114 { $WantPrototypes = 0}
119 @ARGV == 1 or die $usage;
120 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
121 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
122 or ($dir, $filename) = ('.', $ARGV[0]);
126 ++ $IncludedFiles{$ARGV[0]} ;
128 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
129 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
132 # Establish set of global symbols with max length 28, since xsubpp
133 # will later add the 'XS_' prefix.
134 require ExtUtils::XSSymSet;
135 $SymSet = new ExtUtils::XSSymSet 28;
140 $_[0] =~ s/^\s+|\s+$//go ;
147 # rationalise any '*' by joining them into bunches and removing whitespace
151 # change multiple whitespace into a single space
154 # trim leading & trailing whitespace
160 $typemap = shift @ARGV;
161 foreach $typemap (@tm) {
162 die "Can't find $typemap in $pwd\n" unless -r $typemap;
164 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
165 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
167 foreach $typemap (@tm) {
168 next unless -e $typemap ;
169 # skip directories, binary files etc.
170 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
172 open(TYPEMAP, $typemap)
173 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
179 my $line_no = $. + 1;
180 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
181 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
182 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
183 if ($mode eq 'Typemap') {
187 # skip blank lines and comment lines
188 next if /^$/ or /^#/ ;
189 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
190 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
191 $type = TidyType($type) ;
192 $type_kind{$type} = $kind ;
193 # prototype defaults to '$'
194 $proto = "\$" unless $proto ;
195 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
196 unless ValidProtoString($proto) ;
197 $proto_letter{$type} = C_string($proto) ;
202 elsif ($mode eq 'Input') {
204 $input_expr{$_} = '';
205 $current = \$input_expr{$_};
209 $output_expr{$_} = '';
210 $current = \$output_expr{$_};
216 foreach $key (keys %input_expr) {
217 $input_expr{$key} =~ s/\n+$//;
220 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
222 # Match an XS keyword
223 $BLOCK_re= '\s*(' . join('|', qw(
224 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
225 CLEANUP ALIAS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
229 # Input: ($_, @line) == unparsed input.
230 # Output: ($_, @line) == (rest of line, following lines).
231 # Return: the matched keyword if found, otherwise 0
233 $_ = shift(@line) while !/\S/ && @line;
234 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
240 $_ = shift(@line) while !/\S/ && @line;
241 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
242 print line_directive() unless ($count++);
247 sub process_keyword($)
252 &{"${kwd}_handler"}()
253 while $kwd = check_keyword($pattern) ;
254 print line_directive();
258 blurt ("Error: `CASE:' after unconditional `CASE:'")
259 if $condnum && $cond eq '';
261 TrimWhitespace($cond);
262 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
267 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
268 last if /^\s*NOT_IMPLEMENTED_YET/;
269 next unless /\S/; # skip blank lines
274 # remove trailing semicolon if no initialisation
275 s/\s*;$//g unless /=/ ;
277 # check for optional initialisation code
279 $var_init = $1 if s/\s*(=.*)$//s ;
280 $var_init =~ s/"/\\"/g;
283 my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
284 or blurt("Error: invalid argument declaration '$line'"), next;
286 # Check for duplicate definitions
287 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
288 if $arg_list{$var_name} ++ ;
290 $thisdone |= $var_name eq "THIS";
291 $retvaldone |= $var_name eq "RETVAL";
292 $var_types{$var_name} = $var_type;
293 print "\t" . &map_type($var_type);
294 $var_num = $args_match{$var_name};
296 $proto_arg[$var_num] = ProtoString($var_type)
299 $var_addr{$var_name} = 1;
300 $func_args =~ s/\b($var_name)\b/&$1/;
302 if ($var_init =~ /^=\s*NO_INIT\s*;?\s*$/) {
303 print "\t$var_name;\n";
304 } elsif ($var_init =~ /\S/) {
305 &output_init($var_type, $var_num, "$var_name $var_init");
307 # generate initialization code
308 &generate_init($var_type, $var_num, $var_name);
316 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
318 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
319 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
320 if $outargs{$outarg} ++ ;
321 if (!$gotRETVAL and $outarg eq 'RETVAL') {
322 # deal with RETVAL last
323 $RETVAL_code = $outcode ;
327 blurt ("Error: OUTPUT $outarg not an argument"), next
328 unless defined($args_match{$outarg});
329 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
330 unless defined $var_types{$outarg} ;
331 print line_directive();
333 print "\t$outcode\n";
335 $var_num = $args_match{$outarg};
336 &generate_output($var_types{$outarg}, $var_num, $outarg);
341 sub CLEANUP_handler() { print_section() }
342 sub PREINIT_handler() { print_section() }
343 sub INIT_handler() { print_section() }
352 # Parse alias definitions
354 # alias = value alias = value ...
356 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
358 $orig_alias = $alias ;
361 # check for optional package definition in the alias
362 $alias = $Packprefix . $alias if $alias !~ /::/ ;
364 # check for duplicate alias name & duplicate value
365 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
366 if defined $XsubAliases{$alias} ;
368 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
369 if $XsubAliasValues{$value} ;
372 $XsubAliases{$alias} = $value ;
373 $XsubAliasValues{$value} = $orig_alias ;
376 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
382 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
385 GetAliases($_) if $_ ;
389 sub REQUIRE_handler ()
391 # the rest of the current line should contain a version number
394 TrimWhitespace($Ver) ;
396 death ("Error: REQUIRE expects a version number")
399 # check that the version number is of the form n.n
400 death ("Error: REQUIRE: expected a number, got '$Ver'")
401 unless $Ver =~ /^\d+(\.\d*)?/ ;
403 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
404 unless $XSUBPP_version >= $Ver ;
407 sub VERSIONCHECK_handler ()
409 # the rest of the current line should contain either ENABLE or
414 # check for ENABLE/DISABLE
415 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
416 unless /^(ENABLE|DISABLE)/i ;
418 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
419 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
423 sub PROTOTYPE_handler ()
427 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
428 if $proto_in_this_xsub ++ ;
430 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
434 if ($_ eq 'DISABLE') {
437 elsif ($_ eq 'ENABLE') {
441 # remove any whitespace
443 death("Error: Invalid prototype '$_'")
444 unless ValidProtoString($_) ;
445 $ProtoThisXSUB = C_string($_) ;
449 # If no prototype specified, then assume empty prototype ""
450 $ProtoThisXSUB = 2 unless $specified ;
458 death("Error: Only 1 SCOPE declaration allowed per xsub")
459 if $scope_in_this_xsub ++ ;
461 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
464 if ($_ =~ /^DISABLE/i) {
467 elsif ($_ =~ /^ENABLE/i) {
474 sub PROTOTYPES_handler ()
476 # the rest of the current line should contain either ENABLE or
481 # check for ENABLE/DISABLE
482 death ("Error: PROTOTYPES: ENABLE/DISABLE")
483 unless /^(ENABLE|DISABLE)/i ;
485 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
486 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
491 sub INCLUDE_handler ()
493 # the rest of the current line should contain a valid filename
497 death("INCLUDE: filename missing")
500 death("INCLUDE: output pipe is illegal")
503 # simple minded recursion detector
504 death("INCLUDE loop detected")
505 if $IncludedFiles{$_} ;
507 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
509 # Save the current file context.
512 LastLine => $lastline,
513 LastLineNo => $lastline_no,
516 Filename => $filename,
523 open ($FH, "$_") or death("Cannot open '$_': $!") ;
527 #/* INCLUDE: Including '$_' from '$filename' */
533 # Prime the pump by reading the first
536 # skip leading blank lines
538 last unless /^\s*$/ ;
548 return 0 unless $XSStack[-1]{type} eq 'file' ;
550 my $data = pop @XSStack ;
551 my $ThisFile = $filename ;
552 my $isPipe = ($filename =~ /\|\s*$/) ;
554 -- $IncludedFiles{$filename}
559 $FH = $data->{Handle} ;
560 $filename = $data->{Filename} ;
561 $lastline = $data->{LastLine} ;
562 $lastline_no = $data->{LastLineNo} ;
563 @line = @{ $data->{Line} } ;
564 @line_no = @{ $data->{LineNo} } ;
566 if ($isPipe and $? ) {
568 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
574 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
581 sub ValidProtoString ($)
585 if ( $string =~ /^$proto_re+$/ ) {
596 $string =~ s[\\][\\\\]g ;
604 $proto_letter{$type} or "\$" ;
608 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
610 my ($cpp, $cpplevel);
612 if ($cpp =~ /^\#\s*if/) {
614 } elsif (!$cpplevel) {
615 Warn("Warning: #else/elif/endif without #if in this function");
616 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
617 if $XSStack[-1]{type} eq 'if';
619 } elsif ($cpp =~ /^\#\s*endif/) {
623 Warn("Warning: #if without #endif in this function") if $cpplevel;
636 open($FH, $filename) or die "cannot open $filename: $!\n";
638 # Identify the version of xsubpp used
641 * This file was generated automatically by xsubpp version $XSUBPP_version from the
642 * contents of $filename. Do not edit this file, edit $filename instead.
644 * ANY CHANGES MADE HERE WILL BE LOST!
649 print "#line 1 \"$filename\"\n";
652 last if ($Module, $Package, $Prefix) =
653 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
656 &Exit unless defined $_;
661 # Read next xsub into @line from ($lastline, <$FH>).
664 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
665 if !defined $lastline && $XSStack[-1]{type} eq 'if';
668 return PopFile() if !defined $lastline;
671 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
673 $Package = defined($2) ? $2 : ''; # keep -w happy
674 $Prefix = defined($3) ? $3 : ''; # keep -w happy
675 $Prefix = quotemeta $Prefix ;
676 ($Module_cname = $Module) =~ s/\W/_/g;
677 ($Packid = $Package) =~ tr/:/_/;
678 $Packprefix = $Package;
679 $Packprefix .= "::" if $Packprefix ne "";
684 if ($lastline !~ /^\s*#/ ||
686 # ANSI: if ifdef ifndef elif else endif define undef
688 # gcc: warning include_next
690 # others: ident (gcc notes that some cpps have this one)
691 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
692 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
693 push(@line, $lastline);
694 push(@line_no, $lastline_no) ;
697 # Read next line and continuation lines
698 last unless defined($lastline = <$FH>);
701 $lastline .= $tmp_line
702 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
705 $lastline =~ s/^\s+$//;
707 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
712 while (fetch_para()) {
713 # Print initial preprocessor statements and blank lines
714 while (@line && $line[0] !~ /^[^\#]/) {
715 my $line = shift(@line);
717 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
719 if ($statement eq 'if') {
720 $XSS_work_idx = @XSStack;
721 push(@XSStack, {type => 'if'});
723 death ("Error: `$statement' with no matching `if'")
724 if $XSStack[-1]{type} ne 'if';
725 if ($XSStack[-1]{varname}) {
726 push(@InitFileCode, "#endif\n");
727 push(@BootCode, "#endif");
730 my(@fns) = keys %{$XSStack[-1]{functions}};
731 if ($statement ne 'endif') {
732 # Hide the functions defined in other #if branches, and reset.
733 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
734 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
736 my($tmp) = pop(@XSStack);
737 0 while (--$XSS_work_idx
738 && $XSStack[$XSS_work_idx]{type} ne 'if');
739 # Keep all new defined functions
740 push(@fns, keys %{$tmp->{other_functions}});
741 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
746 next PARAGRAPH unless @line;
748 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
749 # We are inside an #if, but have not yet #defined its xsubpp variable.
750 print "#define $cpp_next_tmp 1\n\n";
751 push(@InitFileCode, "#if $cpp_next_tmp\n");
752 push(@BootCode, "#if $cpp_next_tmp");
753 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
756 death ("Code is not inside a function"
757 ." (maybe last function was ended by a blank line "
758 ." followed by a a statement on column one?)")
759 if $line[0] =~ /^\s/;
761 # initialize info arrays
772 undef($proto_in_this_xsub) ;
773 undef($scope_in_this_xsub) ;
774 $ProtoThisXSUB = $WantPrototypes ;
778 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
779 &{"${kwd}_handler"}() ;
780 next PARAGRAPH unless @line ;
784 if (check_keyword("BOOT")) {
786 push (@BootCode, $_, line_directive(), @line, "") ;
791 # extract return type, function name and arguments
792 my($ret_type) = TidyType($_);
794 # a function definition needs at least 2 lines
795 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
798 $static = 1 if $ret_type =~ s/^static\s+//;
800 $func_header = shift(@line);
801 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
802 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*$/s;
804 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
805 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
806 ($clean_func_name = $func_name) =~ s/^$Prefix//;
807 $Full_func_name = "${Packid}_$clean_func_name";
808 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
810 # Check for duplicate function definition
811 for $tmp (@XSStack) {
812 next unless defined $tmp->{functions}{$Full_func_name};
813 Warn("Warning: duplicate function definition '$clean_func_name' detected");
816 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
817 %XsubAliases = %XsubAliasValues = ();
819 @args = split(/\s*,\s*/, $orig_args);
820 if (defined($class)) {
821 my $arg0 = ((defined($static) or $func_name =~ /^new/) ? "CLASS" : "THIS");
822 unshift(@args, $arg0);
823 ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
825 $orig_args =~ s/"/\\"/g;
826 $min_args = $num_args = @args;
827 foreach $i (0..$num_args-1) {
828 if ($args[$i] =~ s/\.\.\.//) {
831 if ($args[$i] eq '' && $i == $num_args - 1) {
836 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
839 $defaults{$args[$i]} = $2;
840 $defaults{$args[$i]} =~ s/"/\\"/g;
842 $proto_arg[$i+1] = "\$" ;
844 if (defined($class)) {
845 $func_args = join(", ", @args[1..$#args]);
847 $func_args = join(", ", @args);
849 @args_match{@args} = 1..@args;
851 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
852 $CODE = grep(/^\s*CODE\s*:/, @line);
853 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
854 # to set explicit return values.
855 $EXPLICIT_RETURN = ($CODE &&
856 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
857 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
859 # print function header
861 #XS(XS_${Full_func_name})
865 print Q<<"EOF" if $ALIAS ;
869 $cond = ($min_args ? qq(items < $min_args) : 0);
871 elsif ($min_args == $num_args) {
872 $cond = qq(items != $min_args);
875 $cond = qq(items < $min_args || items > $num_args);
878 print Q<<"EOF" if $except;
884 { print Q<<"EOF" if $cond }
886 # croak("Usage: %s($orig_args)", GvNAME(CvGV(cv)));
889 { print Q<<"EOF" if $cond }
891 # croak("Usage: $pname($orig_args)");
894 print Q<<"EOF" if $PPCODE;
898 # Now do a block of some sort.
901 $cond = ''; # last CASE: condidional
902 push(@line, "$END:");
903 push(@line_no, $line_no[-1]);
907 &CASE_handler if check_keyword("CASE");
912 # do initialization of input variables
920 process_keyword("INPUT|PREINIT|ALIAS|PROTOTYPE|SCOPE") ;
922 print Q<<"EOF" if $ScopeThisXSUB;
927 if (!$thisdone && defined($class)) {
928 if (defined($static) or $func_name =~ /^new/) {
930 $var_types{"CLASS"} = "char *";
931 &generate_init("char *", 1, "CLASS");
935 $var_types{"THIS"} = "$class *";
936 &generate_init("$class *", 1, "THIS");
941 if (/^\s*NOT_IMPLEMENTED_YET/) {
942 print "\n\tcroak(\"$pname: not implemented yet\");\n";
945 if ($ret_type ne "void") {
946 print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
948 $args_match{"RETVAL"} = 0;
949 $var_types{"RETVAL"} = $ret_type;
954 process_keyword("INIT|ALIAS|PROTOTYPE") ;
956 if (check_keyword("PPCODE")) {
958 death ("PPCODE must be last thing") if @line;
959 print "\tLEAVE;\n" if $ScopeThisXSUB;
960 print "\tPUTBACK;\n\treturn;\n";
961 } elsif (check_keyword("CODE")) {
963 } elsif (defined($class) and $func_name eq "DESTROY") {
965 print "delete THIS;\n";
968 if ($ret_type ne "void") {
972 if (defined($static)) {
973 if ($func_name =~ /^new/) {
974 $func_name = "$class";
978 } elsif (defined($class)) {
979 if ($func_name =~ /^new/) {
980 $func_name .= " $class";
985 $func_name =~ s/^($spat)//
987 print "$func_name($func_args);\n";
991 # do output variables
995 process_keyword("OUTPUT|ALIAS|PROTOTYPE");
997 # all OUTPUT done, so now push the return value on the stack
998 if ($gotRETVAL && $RETVAL_code) {
999 print "\t$RETVAL_code\n";
1000 } elsif ($gotRETVAL || $wantRETVAL) {
1001 &generate_output($ret_type, 0, 'RETVAL');
1003 print line_directive();
1006 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
1008 print Q<<"EOF" if $ScopeThisXSUB;
1011 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1015 # print function trailer
1019 print Q<<EOF if $except;
1022 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1025 if (check_keyword("CASE")) {
1026 blurt ("Error: No `CASE:' at top of function")
1028 $_ = "CASE: $_"; # Restore CASE: label
1031 last if $_ eq "$END:";
1032 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1035 print Q<<EOF if $except;
1040 if ($ret_type ne "void" or $EXPLICIT_RETURN) {
1041 print Q<<EOF unless $PPCODE;
1045 print Q<<EOF unless $PPCODE;
1055 my $newXS = "newXS" ;
1058 # Build the prototype string for the xsub
1059 if ($ProtoThisXSUB) {
1060 $newXS = "newXSproto";
1062 if ($ProtoThisXSUB == 2) {
1063 # User has specified empty prototype
1066 elsif ($ProtoThisXSUB != 1) {
1067 # User has specified a prototype
1068 $proto = ', "' . $ProtoThisXSUB . '"';
1072 if ($min_args < $num_args) {
1074 $proto_arg[$min_args] .= ";" ;
1076 push @proto_arg, "$s\@"
1079 $proto = ', "' . join ("", @proto_arg) . '"';
1084 $XsubAliases{$pname} = 0
1085 unless defined $XsubAliases{$pname} ;
1086 while ( ($name, $value) = each %XsubAliases) {
1087 push(@InitFileCode, Q<<"EOF");
1088 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1089 # XSANY.any_i32 = $value ;
1091 push(@InitFileCode, Q<<"EOF") if $proto;
1092 # sv_setpv((SV*)cv$proto) ;
1098 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1102 # print initialization routine
1107 #XS(boot_$Module_cname)
1110 # char* file = __FILE__;
1114 print Q<<"EOF" if $WantVersionChk ;
1115 # XS_VERSION_BOOTCHECK ;
1119 print Q<<"EOF" if defined $XsubAliases ;
1125 print @InitFileCode;
1127 print Q<<"EOF" if defined $XsubAliases ;
1133 print "\n /* Initialisation Section */\n" ;
1134 print grep (s/$/\n/, @BootCode) ;
1135 print "\n /* End of Initialisation Section */\n\n" ;
1144 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1150 local($type, $num, $init) = @_;
1151 local($arg) = "ST(" . ($num - 1) . ")";
1153 eval qq/print " $init\\\n"/;
1158 # work out the line number
1159 my $line_no = $line_no[@line_no - @line -1] ;
1161 return "#line $line_no \"$filename\"\n" ;
1167 # work out the line number
1168 my $line_no = $line_no[@line_no - @line -1] ;
1170 print STDERR "@_ in $filename, line $line_no\n" ;
1186 local($type, $num, $var) = @_;
1187 local($arg) = "ST(" . ($num - 1) . ")";
1188 local($argoff) = $num - 1;
1192 $type = TidyType($type) ;
1193 blurt("Error: '$type' not in typemap"), return
1194 unless defined($type_kind{$type});
1196 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1197 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1198 $tk = $type_kind{$type};
1199 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1201 blurt("Error: No INPUT definition for type '$type' found"), return
1202 unless defined $input_expr{$tk} ;
1203 $expr = $input_expr{$tk};
1204 if ($expr =~ /DO_ARRAY_ELEM/) {
1205 blurt("Error: '$subtype' not in typemap"), return
1206 unless defined($type_kind{$subtype});
1207 blurt("Error: No INPUT definition for type '$subtype' found"), return
1208 unless defined $input_expr{$type_kind{$subtype}} ;
1209 $subexpr = $input_expr{$type_kind{$subtype}};
1210 $subexpr =~ s/ntype/subtype/g;
1211 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1212 $subexpr =~ s/\n\t/\n\t\t/g;
1213 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1214 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1215 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1217 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1220 if (defined($defaults{$var})) {
1221 $expr =~ s/(\t+)/$1 /g;
1223 eval qq/print "\\t$var;\\n"/;
1224 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1225 } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1226 eval qq/print "\\t$var;\\n"/;
1227 $deferred .= eval qq/"\\n$expr;\\n"/;
1229 eval qq/print "$expr;\\n"/;
1233 sub generate_output {
1234 local($type, $num, $var) = @_;
1235 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1236 local($argoff) = $num - 1;
1239 $type = TidyType($type) ;
1240 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1241 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
1243 blurt("Error: '$type' not in typemap"), return
1244 unless defined($type_kind{$type});
1245 blurt("Error: No OUTPUT definition for type '$type' found"), return
1246 unless defined $output_expr{$type_kind{$type}} ;
1247 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1248 $ntype =~ s/\(\)//g;
1249 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1250 $expr = $output_expr{$type_kind{$type}};
1251 if ($expr =~ /DO_ARRAY_ELEM/) {
1252 blurt("Error: '$subtype' not in typemap"), return
1253 unless defined($type_kind{$subtype});
1254 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1255 unless defined $output_expr{$type_kind{$subtype}} ;
1256 $subexpr = $output_expr{$type_kind{$subtype}};
1257 $subexpr =~ s/ntype/subtype/g;
1258 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1259 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1260 $subexpr =~ s/\n\t/\n\t\t/g;
1261 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1262 eval "print qq\a$expr\a";
1264 elsif ($var eq 'RETVAL') {
1265 if ($expr =~ /^\t\$arg = new/) {
1266 # We expect that $arg has refcnt 1, so we need to
1268 eval "print qq\a$expr\a";
1269 print "\tsv_2mortal(ST(0));\n";
1271 elsif ($expr =~ /^\s*\$arg\s*=/) {
1272 # We expect that $arg has refcnt >=1, so we need
1273 # to mortalize it. However, the extension may have
1274 # returned the built-in perl value, which is
1275 # read-only, thus not mortalizable. However, it is
1276 # safe to leave it as it is, since it would be
1277 # ignored by REFCNT_dec. Builtin values have REFCNT==0.
1278 eval "print qq\a$expr\a";
1279 print "\tif (SvREFCNT(ST(0))) sv_2mortal(ST(0));\n";
1282 # Just hope that the entry would safely write it
1283 # over an already mortalized value. By
1284 # coincidence, something like $arg = &sv_undef
1286 print "\tST(0) = sv_newmortal();\n";
1287 eval "print qq\a$expr\a";
1290 elsif ($arg =~ /^ST\(\d+\)$/) {
1291 eval "print qq\a$expr\a";
1300 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1306 # If this is VMS, the exit status has meaning to the shell, so we
1307 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1309 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1310 exit ($errors ? 1 : 0);