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<-nolinenumbers>] [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
58 =item B<-nolinenumbers>
60 Prevents the inclusion of `#line' directives in the output.
66 No environment variables are used.
72 =head1 MODIFICATION HISTORY
74 See the file F<changes.pod>.
78 perl(1), perlxs(1), perlxstut(1)
84 use vars '$cplusplus';
90 $XSUBPP_version = "1.9506";
92 my ($Is_VMS, $SymSet);
95 # Establish set of global symbols with max length 28, since xsubpp
96 # will later add the 'XS_' prefix.
97 require ExtUtils::XSSymSet;
98 $SymSet = new ExtUtils::XSSymSet 28;
103 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-s pattern] [-typemap typemap]... file.xs\n";
105 $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
108 $WantPrototypes = -1 ;
109 $WantVersionChk = 1 ;
111 $WantLineNumbers = 1 ;
112 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
115 $spat = quotemeta shift, next SWITCH if $flag eq 's';
116 $cplusplus = 1, next SWITCH if $flag eq 'C++';
117 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
118 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
119 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
120 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
121 $except = " TRY", next SWITCH if $flag eq 'except';
122 push(@tm,shift), next SWITCH if $flag eq 'typemap';
123 $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
124 $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
125 (print "xsubpp version $XSUBPP_version\n"), exit
129 if ($WantPrototypes == -1)
130 { $WantPrototypes = 0}
135 @ARGV == 1 or die $usage;
136 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
137 or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
138 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
139 or ($dir, $filename) = ('.', $ARGV[0]);
143 ++ $IncludedFiles{$ARGV[0]} ;
145 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
146 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
151 $_[0] =~ s/^\s+|\s+$//go ;
158 # rationalise any '*' by joining them into bunches and removing whitespace
162 # change multiple whitespace into a single space
165 # trim leading & trailing whitespace
171 $typemap = shift @ARGV;
172 foreach $typemap (@tm) {
173 die "Can't find $typemap in $pwd\n" unless -r $typemap;
175 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
176 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
178 foreach $typemap (@tm) {
179 next unless -e $typemap ;
180 # skip directories, binary files etc.
181 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
183 open(TYPEMAP, $typemap)
184 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
190 my $line_no = $. + 1;
191 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
192 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
193 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
194 if ($mode eq 'Typemap') {
198 # skip blank lines and comment lines
199 next if /^$/ or /^#/ ;
200 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
201 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
202 $type = TidyType($type) ;
203 $type_kind{$type} = $kind ;
204 # prototype defaults to '$'
205 $proto = "\$" unless $proto ;
206 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
207 unless ValidProtoString($proto) ;
208 $proto_letter{$type} = C_string($proto) ;
213 elsif ($mode eq 'Input') {
215 $input_expr{$_} = '';
216 $current = \$input_expr{$_};
220 $output_expr{$_} = '';
221 $current = \$output_expr{$_};
227 foreach $key (keys %input_expr) {
228 $input_expr{$key} =~ s/\n+$//;
231 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
233 # Match an XS keyword
234 $BLOCK_re= '\s*(' . join('|', qw(
235 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
236 CLEANUP ALIAS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
240 # Input: ($_, @line) == unparsed input.
241 # Output: ($_, @line) == (rest of line, following lines).
242 # Return: the matched keyword if found, otherwise 0
244 $_ = shift(@line) while !/\S/ && @line;
245 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
249 if ($WantLineNumbers) {
251 package xsubpp::counter;
253 my ($class, $cfile) = @_;
255 $SECTION_END_MARKER = "#line --- \"$cfile\"";
264 while ($$self =~ s/^([^\n]*\n)//) {
267 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
276 $self->PRINT(sprintf($fmt, @_));
280 # Not necessary if we're careful to end with a "\n"
286 my $cfile = $filename;
287 $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
288 tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
289 select PSEUDO_STDOUT;
293 # the "do" is required for right semantics
294 do { $_ = shift(@line) } while !/\S/ && @line;
296 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
297 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
298 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
301 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
304 sub process_keyword($)
309 &{"${kwd}_handler"}()
310 while $kwd = check_keyword($pattern) ;
314 blurt ("Error: `CASE:' after unconditional `CASE:'")
315 if $condnum && $cond eq '';
317 TrimWhitespace($cond);
318 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
323 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
324 last if /^\s*NOT_IMPLEMENTED_YET/;
325 next unless /\S/; # skip blank lines
330 # remove trailing semicolon if no initialisation
331 s/\s*;$//g unless /=/ ;
333 # check for optional initialisation code
335 $var_init = $1 if s/\s*(=.*)$//s ;
336 $var_init =~ s/"/\\"/g;
339 my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
340 or blurt("Error: invalid argument declaration '$line'"), next;
342 # Check for duplicate definitions
343 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
344 if $arg_list{$var_name} ++ ;
346 $thisdone |= $var_name eq "THIS";
347 $retvaldone |= $var_name eq "RETVAL";
348 $var_types{$var_name} = $var_type;
349 print "\t" . &map_type($var_type);
350 $var_num = $args_match{$var_name};
352 $proto_arg[$var_num] = ProtoString($var_type)
355 $var_addr{$var_name} = 1;
356 $func_args =~ s/\b($var_name)\b/&$1/;
358 if ($var_init =~ /^=\s*NO_INIT\s*;?\s*$/) {
359 print "\t$var_name;\n";
360 } elsif ($var_init =~ /\S/) {
361 &output_init($var_type, $var_num, "$var_name $var_init");
363 # generate initialization code
364 &generate_init($var_type, $var_num, $var_name);
372 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
374 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
375 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
378 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
379 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
380 if $outargs{$outarg} ++ ;
381 if (!$gotRETVAL and $outarg eq 'RETVAL') {
382 # deal with RETVAL last
383 $RETVAL_code = $outcode ;
387 blurt ("Error: OUTPUT $outarg not an argument"), next
388 unless defined($args_match{$outarg});
389 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
390 unless defined $var_types{$outarg} ;
391 $var_num = $args_match{$outarg};
393 print "\t$outcode\n";
394 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
396 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
401 sub CLEANUP_handler() { print_section() }
402 sub PREINIT_handler() { print_section() }
403 sub INIT_handler() { print_section() }
412 # Parse alias definitions
414 # alias = value alias = value ...
416 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
418 $orig_alias = $alias ;
421 # check for optional package definition in the alias
422 $alias = $Packprefix . $alias if $alias !~ /::/ ;
424 # check for duplicate alias name & duplicate value
425 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
426 if defined $XsubAliases{$alias} ;
428 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
429 if $XsubAliasValues{$value} ;
432 $XsubAliases{$alias} = $value ;
433 $XsubAliasValues{$value} = $orig_alias ;
436 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
442 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
445 GetAliases($_) if $_ ;
449 sub REQUIRE_handler ()
451 # the rest of the current line should contain a version number
454 TrimWhitespace($Ver) ;
456 death ("Error: REQUIRE expects a version number")
459 # check that the version number is of the form n.n
460 death ("Error: REQUIRE: expected a number, got '$Ver'")
461 unless $Ver =~ /^\d+(\.\d*)?/ ;
463 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
464 unless $XSUBPP_version >= $Ver ;
467 sub VERSIONCHECK_handler ()
469 # the rest of the current line should contain either ENABLE or
474 # check for ENABLE/DISABLE
475 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
476 unless /^(ENABLE|DISABLE)/i ;
478 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
479 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
483 sub PROTOTYPE_handler ()
487 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
488 if $proto_in_this_xsub ++ ;
490 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
494 if ($_ eq 'DISABLE') {
497 elsif ($_ eq 'ENABLE') {
501 # remove any whitespace
503 death("Error: Invalid prototype '$_'")
504 unless ValidProtoString($_) ;
505 $ProtoThisXSUB = C_string($_) ;
509 # If no prototype specified, then assume empty prototype ""
510 $ProtoThisXSUB = 2 unless $specified ;
518 death("Error: Only 1 SCOPE declaration allowed per xsub")
519 if $scope_in_this_xsub ++ ;
521 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
524 if ($_ =~ /^DISABLE/i) {
527 elsif ($_ =~ /^ENABLE/i) {
534 sub PROTOTYPES_handler ()
536 # the rest of the current line should contain either ENABLE or
541 # check for ENABLE/DISABLE
542 death ("Error: PROTOTYPES: ENABLE/DISABLE")
543 unless /^(ENABLE|DISABLE)/i ;
545 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
546 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
551 sub INCLUDE_handler ()
553 # the rest of the current line should contain a valid filename
557 death("INCLUDE: filename missing")
560 death("INCLUDE: output pipe is illegal")
563 # simple minded recursion detector
564 death("INCLUDE loop detected")
565 if $IncludedFiles{$_} ;
567 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
569 # Save the current file context.
572 LastLine => $lastline,
573 LastLineNo => $lastline_no,
576 Filename => $filename,
583 open ($FH, "$_") or death("Cannot open '$_': $!") ;
587 #/* INCLUDE: Including '$_' from '$filename' */
593 # Prime the pump by reading the first
596 # skip leading blank lines
598 last unless /^\s*$/ ;
608 return 0 unless $XSStack[-1]{type} eq 'file' ;
610 my $data = pop @XSStack ;
611 my $ThisFile = $filename ;
612 my $isPipe = ($filename =~ /\|\s*$/) ;
614 -- $IncludedFiles{$filename}
619 $FH = $data->{Handle} ;
620 $filename = $data->{Filename} ;
621 $lastline = $data->{LastLine} ;
622 $lastline_no = $data->{LastLineNo} ;
623 @line = @{ $data->{Line} } ;
624 @line_no = @{ $data->{LineNo} } ;
626 if ($isPipe and $? ) {
628 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
634 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
641 sub ValidProtoString ($)
645 if ( $string =~ /^$proto_re+$/ ) {
656 $string =~ s[\\][\\\\]g ;
664 $proto_letter{$type} or "\$" ;
668 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
670 my ($cpp, $cpplevel);
672 if ($cpp =~ /^\#\s*if/) {
674 } elsif (!$cpplevel) {
675 Warn("Warning: #else/elif/endif without #if in this function");
676 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
677 if $XSStack[-1]{type} eq 'if';
679 } elsif ($cpp =~ /^\#\s*endif/) {
683 Warn("Warning: #if without #endif in this function") if $cpplevel;
696 open($FH, $filename) or die "cannot open $filename: $!\n";
698 # Identify the version of xsubpp used
701 * This file was generated automatically by xsubpp version $XSUBPP_version from the
702 * contents of $filename. Do not edit this file, edit $filename instead.
704 * ANY CHANGES MADE HERE WILL BE LOST!
711 print("#line 1 \"$filename\"\n")
715 last if ($Module, $Package, $Prefix) =
716 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
719 &Exit unless defined $_;
724 # Read next xsub into @line from ($lastline, <$FH>).
727 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
728 if !defined $lastline && $XSStack[-1]{type} eq 'if';
731 return PopFile() if !defined $lastline;
734 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
736 $Package = defined($2) ? $2 : ''; # keep -w happy
737 $Prefix = defined($3) ? $3 : ''; # keep -w happy
738 $Prefix = quotemeta $Prefix ;
739 ($Module_cname = $Module) =~ s/\W/_/g;
740 ($Packid = $Package) =~ tr/:/_/;
741 $Packprefix = $Package;
742 $Packprefix .= "::" if $Packprefix ne "";
747 if ($lastline !~ /^\s*#/ ||
749 # ANSI: if ifdef ifndef elif else endif define undef
751 # gcc: warning include_next
753 # others: ident (gcc notes that some cpps have this one)
754 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
755 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
756 push(@line, $lastline);
757 push(@line_no, $lastline_no) ;
760 # Read next line and continuation lines
761 last unless defined($lastline = <$FH>);
764 $lastline .= $tmp_line
765 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
768 $lastline =~ s/^\s+$//;
770 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
775 while (fetch_para()) {
776 # Print initial preprocessor statements and blank lines
777 while (@line && $line[0] !~ /^[^\#]/) {
778 my $line = shift(@line);
780 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
782 if ($statement eq 'if') {
783 $XSS_work_idx = @XSStack;
784 push(@XSStack, {type => 'if'});
786 death ("Error: `$statement' with no matching `if'")
787 if $XSStack[-1]{type} ne 'if';
788 if ($XSStack[-1]{varname}) {
789 push(@InitFileCode, "#endif\n");
790 push(@BootCode, "#endif");
793 my(@fns) = keys %{$XSStack[-1]{functions}};
794 if ($statement ne 'endif') {
795 # Hide the functions defined in other #if branches, and reset.
796 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
797 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
799 my($tmp) = pop(@XSStack);
800 0 while (--$XSS_work_idx
801 && $XSStack[$XSS_work_idx]{type} ne 'if');
802 # Keep all new defined functions
803 push(@fns, keys %{$tmp->{other_functions}});
804 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
809 next PARAGRAPH unless @line;
811 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
812 # We are inside an #if, but have not yet #defined its xsubpp variable.
813 print "#define $cpp_next_tmp 1\n\n";
814 push(@InitFileCode, "#if $cpp_next_tmp\n");
815 push(@BootCode, "#if $cpp_next_tmp");
816 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
819 death ("Code is not inside a function"
820 ." (maybe last function was ended by a blank line "
821 ." followed by a a statement on column one?)")
822 if $line[0] =~ /^\s/;
824 # initialize info arrays
835 undef($proto_in_this_xsub) ;
836 undef($scope_in_this_xsub) ;
837 $ProtoThisXSUB = $WantPrototypes ;
841 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
842 &{"${kwd}_handler"}() ;
843 next PARAGRAPH unless @line ;
847 if (check_keyword("BOOT")) {
849 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
850 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
851 push (@BootCode, @line, "") ;
856 # extract return type, function name and arguments
857 my($ret_type) = TidyType($_);
859 # a function definition needs at least 2 lines
860 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
863 $static = 1 if $ret_type =~ s/^static\s+//;
865 $func_header = shift(@line);
866 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
867 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*$/s;
869 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
870 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
871 ($clean_func_name = $func_name) =~ s/^$Prefix//;
872 $Full_func_name = "${Packid}_$clean_func_name";
873 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
875 # Check for duplicate function definition
876 for $tmp (@XSStack) {
877 next unless defined $tmp->{functions}{$Full_func_name};
878 Warn("Warning: duplicate function definition '$clean_func_name' detected");
881 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
882 %XsubAliases = %XsubAliasValues = ();
885 @args = split(/\s*,\s*/, $orig_args);
886 if (defined($class)) {
887 my $arg0 = ((defined($static) or $func_name eq 'new')
889 unshift(@args, $arg0);
890 ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
892 $orig_args =~ s/"/\\"/g;
893 $min_args = $num_args = @args;
894 foreach $i (0..$num_args-1) {
895 if ($args[$i] =~ s/\.\.\.//) {
898 if ($args[$i] eq '' && $i == $num_args - 1) {
903 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
906 $defaults{$args[$i]} = $2;
907 $defaults{$args[$i]} =~ s/"/\\"/g;
909 $proto_arg[$i+1] = "\$" ;
911 if (defined($class)) {
912 $func_args = join(", ", @args[1..$#args]);
914 $func_args = join(", ", @args);
916 @args_match{@args} = 1..@args;
918 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
919 $CODE = grep(/^\s*CODE\s*:/, @line);
920 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
921 # to set explicit return values.
922 $EXPLICIT_RETURN = ($CODE &&
923 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
924 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
926 # print function header
928 #XS(XS_${Full_func_name})
932 print Q<<"EOF" if $ALIAS ;
936 $cond = ($min_args ? qq(items < $min_args) : 0);
938 elsif ($min_args == $num_args) {
939 $cond = qq(items != $min_args);
942 $cond = qq(items < $min_args || items > $num_args);
945 print Q<<"EOF" if $except;
951 { print Q<<"EOF" if $cond }
953 # croak("Usage: %s($orig_args)", GvNAME(CvGV(cv)));
956 { print Q<<"EOF" if $cond }
958 # croak("Usage: $pname($orig_args)");
961 print Q<<"EOF" if $PPCODE;
965 # Now do a block of some sort.
968 $cond = ''; # last CASE: condidional
969 push(@line, "$END:");
970 push(@line_no, $line_no[-1]);
974 &CASE_handler if check_keyword("CASE");
979 # do initialization of input variables
987 process_keyword("INPUT|PREINIT|ALIAS|PROTOTYPE|SCOPE") ;
989 print Q<<"EOF" if $ScopeThisXSUB;
994 if (!$thisdone && defined($class)) {
995 if (defined($static) or $func_name eq 'new') {
997 $var_types{"CLASS"} = "char *";
998 &generate_init("char *", 1, "CLASS");
1002 $var_types{"THIS"} = "$class *";
1003 &generate_init("$class *", 1, "THIS");
1008 if (/^\s*NOT_IMPLEMENTED_YET/) {
1009 print "\n\tcroak(\"$pname: not implemented yet\");\n";
1012 if ($ret_type ne "void") {
1013 print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
1015 $args_match{"RETVAL"} = 0;
1016 $var_types{"RETVAL"} = $ret_type;
1021 process_keyword("INIT|ALIAS|PROTOTYPE") ;
1023 if (check_keyword("PPCODE")) {
1025 death ("PPCODE must be last thing") if @line;
1026 print "\tLEAVE;\n" if $ScopeThisXSUB;
1027 print "\tPUTBACK;\n\treturn;\n";
1028 } elsif (check_keyword("CODE")) {
1030 } elsif (defined($class) and $func_name eq "DESTROY") {
1032 print "delete THIS;\n";
1035 if ($ret_type ne "void") {
1039 if (defined($static)) {
1040 if ($func_name eq 'new') {
1041 $func_name = "$class";
1045 } elsif (defined($class)) {
1046 if ($func_name eq 'new') {
1047 $func_name .= " $class";
1052 $func_name =~ s/^($spat)//
1054 print "$func_name($func_args);\n";
1058 # do output variables
1060 undef $RETVAL_code ;
1062 process_keyword("OUTPUT|ALIAS|PROTOTYPE");
1064 # all OUTPUT done, so now push the return value on the stack
1065 if ($gotRETVAL && $RETVAL_code) {
1066 print "\t$RETVAL_code\n";
1067 } elsif ($gotRETVAL || $wantRETVAL) {
1068 # RETVAL almost never needs SvSETMAGIC()
1069 &generate_output($ret_type, 0, 'RETVAL', 0);
1073 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
1075 print Q<<"EOF" if $ScopeThisXSUB;
1078 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1082 # print function trailer
1086 print Q<<EOF if $except;
1089 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1092 if (check_keyword("CASE")) {
1093 blurt ("Error: No `CASE:' at top of function")
1095 $_ = "CASE: $_"; # Restore CASE: label
1098 last if $_ eq "$END:";
1099 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1102 print Q<<EOF if $except;
1107 if ($ret_type ne "void" or $EXPLICIT_RETURN) {
1108 print Q<<EOF unless $PPCODE;
1112 print Q<<EOF unless $PPCODE;
1122 my $newXS = "newXS" ;
1125 # Build the prototype string for the xsub
1126 if ($ProtoThisXSUB) {
1127 $newXS = "newXSproto";
1129 if ($ProtoThisXSUB eq 2) {
1130 # User has specified empty prototype
1133 elsif ($ProtoThisXSUB ne 1) {
1134 # User has specified a prototype
1135 $proto = ', "' . $ProtoThisXSUB . '"';
1139 if ($min_args < $num_args) {
1141 $proto_arg[$min_args] .= ";" ;
1143 push @proto_arg, "$s\@"
1146 $proto = ', "' . join ("", @proto_arg) . '"';
1151 $XsubAliases{$pname} = 0
1152 unless defined $XsubAliases{$pname} ;
1153 while ( ($name, $value) = each %XsubAliases) {
1154 push(@InitFileCode, Q<<"EOF");
1155 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1156 # XSANY.any_i32 = $value ;
1158 push(@InitFileCode, Q<<"EOF") if $proto;
1159 # sv_setpv((SV*)cv$proto) ;
1165 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1169 # print initialization routine
1174 #XS(boot_$Module_cname)
1177 # char* file = __FILE__;
1181 print Q<<"EOF" if $WantVersionChk ;
1182 # XS_VERSION_BOOTCHECK ;
1186 print Q<<"EOF" if defined $XsubAliases ;
1192 print @InitFileCode;
1194 print Q<<"EOF" if defined $XsubAliases ;
1200 print "\n /* Initialisation Section */\n\n" ;
1203 print "\n /* End of Initialisation Section */\n\n" ;
1212 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1218 local($type, $num, $init) = @_;
1219 local($arg) = "ST(" . ($num - 1) . ")";
1221 eval qq/print " $init\\\n"/;
1226 # work out the line number
1227 my $line_no = $line_no[@line_no - @line -1] ;
1229 print STDERR "@_ in $filename, line $line_no\n" ;
1245 local($type, $num, $var) = @_;
1246 local($arg) = "ST(" . ($num - 1) . ")";
1247 local($argoff) = $num - 1;
1251 $type = TidyType($type) ;
1252 blurt("Error: '$type' not in typemap"), return
1253 unless defined($type_kind{$type});
1255 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1256 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1257 $tk = $type_kind{$type};
1258 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1260 blurt("Error: No INPUT definition for type '$type' found"), return
1261 unless defined $input_expr{$tk} ;
1262 $expr = $input_expr{$tk};
1263 if ($expr =~ /DO_ARRAY_ELEM/) {
1264 blurt("Error: '$subtype' not in typemap"), return
1265 unless defined($type_kind{$subtype});
1266 blurt("Error: No INPUT definition for type '$subtype' found"), return
1267 unless defined $input_expr{$type_kind{$subtype}} ;
1268 $subexpr = $input_expr{$type_kind{$subtype}};
1269 $subexpr =~ s/ntype/subtype/g;
1270 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1271 $subexpr =~ s/\n\t/\n\t\t/g;
1272 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1273 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1274 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1276 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1279 if (defined($defaults{$var})) {
1280 $expr =~ s/(\t+)/$1 /g;
1282 eval qq/print "\\t$var;\\n"/;
1283 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1284 } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1285 eval qq/print "\\t$var;\\n"/;
1286 $deferred .= eval qq/"\\n$expr;\\n"/;
1288 eval qq/print "$expr;\\n"/;
1292 sub generate_output {
1293 local($type, $num, $var, $do_setmagic) = @_;
1294 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1295 local($argoff) = $num - 1;
1298 $type = TidyType($type) ;
1299 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1300 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
1301 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1303 blurt("Error: '$type' not in typemap"), return
1304 unless defined($type_kind{$type});
1305 blurt("Error: No OUTPUT definition for type '$type' found"), return
1306 unless defined $output_expr{$type_kind{$type}} ;
1307 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1308 $ntype =~ s/\(\)//g;
1309 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1310 $expr = $output_expr{$type_kind{$type}};
1311 if ($expr =~ /DO_ARRAY_ELEM/) {
1312 blurt("Error: '$subtype' not in typemap"), return
1313 unless defined($type_kind{$subtype});
1314 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1315 unless defined $output_expr{$type_kind{$subtype}} ;
1316 $subexpr = $output_expr{$type_kind{$subtype}};
1317 $subexpr =~ s/ntype/subtype/g;
1318 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1319 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1320 $subexpr =~ s/\n\t/\n\t\t/g;
1321 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1322 eval "print qq\a$expr\a";
1323 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1325 elsif ($var eq 'RETVAL') {
1326 if ($expr =~ /^\t\$arg = new/) {
1327 # We expect that $arg has refcnt 1, so we need to
1329 eval "print qq\a$expr\a";
1330 print "\tsv_2mortal(ST(0));\n";
1331 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1333 elsif ($expr =~ /^\s*\$arg\s*=/) {
1334 # We expect that $arg has refcnt >=1, so we need
1335 # to mortalize it. However, the extension may have
1336 # returned the built-in perl value, which is
1337 # read-only, thus not mortalizable. However, it is
1338 # safe to leave it as it is, since it would be
1339 # ignored by REFCNT_dec. Builtin values have REFCNT==0.
1340 eval "print qq\a$expr\a";
1341 print "\tif (SvREFCNT(ST(0))) sv_2mortal(ST(0));\n";
1342 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1345 # Just hope that the entry would safely write it
1346 # over an already mortalized value. By
1347 # coincidence, something like $arg = &sv_undef
1349 print "\tST(0) = sv_newmortal();\n";
1350 eval "print qq\a$expr\a";
1351 # new mortals don't have set magic
1354 elsif ($arg =~ /^ST\(\d+\)$/) {
1355 eval "print qq\a$expr\a";
1356 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1365 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1371 # If this is VMS, the exit status has meaning to the shell, so we
1372 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1374 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1375 exit ($errors ? 1 : 0);