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>] [B<-object_capi>]... 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.
64 Compile code as C in a PERL_OBJECT environment.
70 No environment variables are used.
76 =head1 MODIFICATION HISTORY
78 See the file F<changes.pod>.
82 perl(1), perlxs(1), perlxstut(1)
88 use vars '$cplusplus';
96 $XSUBPP_version = "1.9507";
98 my ($Is_VMS, $SymSet);
101 # Establish set of global symbols with max length 28, since xsubpp
102 # will later add the 'XS_' prefix.
103 require ExtUtils::XSSymSet;
104 $SymSet = new ExtUtils::XSSymSet 28;
109 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-s pattern] [-typemap typemap]... file.xs\n";
111 $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
113 $OBJ = 1 if $Config{'ccflags'} =~ /PERL_OBJECT/i;
116 $WantPrototypes = -1 ;
117 $WantVersionChk = 1 ;
119 $WantLineNumbers = 1 ;
120 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
123 $spat = quotemeta shift, next SWITCH if $flag eq 's';
124 $cplusplus = 1, next SWITCH if $flag eq 'C++';
125 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
126 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
127 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
128 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
129 $WantCAPI = 1, next SWITCH if $flag eq 'object_capi';
130 $except = " TRY", next SWITCH if $flag eq 'except';
131 push(@tm,shift), next SWITCH if $flag eq 'typemap';
132 $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
133 $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
134 (print "xsubpp version $XSUBPP_version\n"), exit
138 if ($WantPrototypes == -1)
139 { $WantPrototypes = 0}
144 @ARGV == 1 or die $usage;
145 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
146 or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
147 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
148 or ($dir, $filename) = ('.', $ARGV[0]);
152 ++ $IncludedFiles{$ARGV[0]} ;
154 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
155 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
160 $_[0] =~ s/^\s+|\s+$//go ;
167 # rationalise any '*' by joining them into bunches and removing whitespace
171 # change multiple whitespace into a single space
174 # trim leading & trailing whitespace
180 $typemap = shift @ARGV;
181 foreach $typemap (@tm) {
182 die "Can't find $typemap in $pwd\n" unless -r $typemap;
184 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
185 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
187 foreach $typemap (@tm) {
188 next unless -e $typemap ;
189 # skip directories, binary files etc.
190 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
192 open(TYPEMAP, $typemap)
193 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
199 my $line_no = $. + 1;
200 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
201 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
202 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
203 if ($mode eq 'Typemap') {
207 # skip blank lines and comment lines
208 next if /^$/ or /^#/ ;
209 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
210 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
211 $type = TidyType($type) ;
212 $type_kind{$type} = $kind ;
213 # prototype defaults to '$'
214 $proto = "\$" unless $proto ;
215 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
216 unless ValidProtoString($proto) ;
217 $proto_letter{$type} = C_string($proto) ;
222 elsif ($mode eq 'Input') {
224 $input_expr{$_} = '';
225 $current = \$input_expr{$_};
229 $output_expr{$_} = '';
230 $current = \$output_expr{$_};
236 foreach $key (keys %input_expr) {
237 $input_expr{$key} =~ s/\n+$//;
240 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
242 # Match an XS keyword
243 $BLOCK_re= '\s*(' . join('|', qw(
244 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
245 CLEANUP ALIAS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
246 SCOPE INTERFACE INTERFACE_MACRO C_ARGS
249 # Input: ($_, @line) == unparsed input.
250 # Output: ($_, @line) == (rest of line, following lines).
251 # Return: the matched keyword if found, otherwise 0
253 $_ = shift(@line) while !/\S/ && @line;
254 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
258 if ($WantLineNumbers) {
260 package xsubpp::counter;
262 my ($class, $cfile) = @_;
264 $SECTION_END_MARKER = "#line --- \"$cfile\"";
273 while ($$self =~ s/^([^\n]*\n)//) {
276 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
285 $self->PRINT(sprintf($fmt, @_));
289 # Not necessary if we're careful to end with a "\n"
295 my $cfile = $filename;
296 $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
297 tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
298 select PSEUDO_STDOUT;
302 # the "do" is required for right semantics
303 do { $_ = shift(@line) } while !/\S/ && @line;
305 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
306 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
307 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
310 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
316 while (!/\S/ && @line) {
320 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
327 sub process_keyword($)
332 &{"${kwd}_handler"}()
333 while $kwd = check_keyword($pattern) ;
337 blurt ("Error: `CASE:' after unconditional `CASE:'")
338 if $condnum && $cond eq '';
340 TrimWhitespace($cond);
341 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
346 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
347 last if /^\s*NOT_IMPLEMENTED_YET/;
348 next unless /\S/; # skip blank lines
353 # remove trailing semicolon if no initialisation
354 s/\s*;$//g unless /=/ ;
356 # check for optional initialisation code
358 $var_init = $1 if s/\s*(=.*)$//s ;
359 $var_init =~ s/"/\\"/g;
362 my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
363 or blurt("Error: invalid argument declaration '$line'"), next;
365 # Check for duplicate definitions
366 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
367 if $arg_list{$var_name} ++ ;
369 $thisdone |= $var_name eq "THIS";
370 $retvaldone |= $var_name eq "RETVAL";
371 $var_types{$var_name} = $var_type;
372 print "\t" . &map_type($var_type);
373 $var_num = $args_match{$var_name};
375 $proto_arg[$var_num] = ProtoString($var_type)
378 $var_addr{$var_name} = 1;
379 $func_args =~ s/\b($var_name)\b/&$1/;
381 if ($var_init =~ /^=\s*NO_INIT\s*;?\s*$/) {
382 print "\t$var_name;\n";
383 } elsif ($var_init =~ /\S/) {
384 &output_init($var_type, $var_num, "$var_name $var_init");
386 # generate initialization code
387 &generate_init($var_type, $var_num, $var_name);
395 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
397 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
398 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
401 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
402 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
403 if $outargs{$outarg} ++ ;
404 if (!$gotRETVAL and $outarg eq 'RETVAL') {
405 # deal with RETVAL last
406 $RETVAL_code = $outcode ;
410 blurt ("Error: OUTPUT $outarg not an argument"), next
411 unless defined($args_match{$outarg});
412 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
413 unless defined $var_types{$outarg} ;
414 $var_num = $args_match{$outarg};
416 print "\t$outcode\n";
417 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
419 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
424 sub C_ARGS_handler() {
425 my $in = merge_section();
431 sub INTERFACE_MACRO_handler() {
432 my $in = merge_section();
435 if ($in =~ /\s/) { # two
436 ($interface_macro, $interface_macro_set) = split ' ', $in;
438 $interface_macro = $in;
439 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
441 $interface = 1; # local
442 $Interfaces = 1; # global
445 sub INTERFACE_handler() {
446 my $in = merge_section();
450 foreach (split /[\s,]+/, $in) {
451 $Interfaces{$_} = $_;
454 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
456 $interface = 1; # local
457 $Interfaces = 1; # global
460 sub CLEANUP_handler() { print_section() }
461 sub PREINIT_handler() { print_section() }
462 sub INIT_handler() { print_section() }
471 # Parse alias definitions
473 # alias = value alias = value ...
475 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
477 $orig_alias = $alias ;
480 # check for optional package definition in the alias
481 $alias = $Packprefix . $alias if $alias !~ /::/ ;
483 # check for duplicate alias name & duplicate value
484 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
485 if defined $XsubAliases{$alias} ;
487 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
488 if $XsubAliasValues{$value} ;
491 $XsubAliases{$alias} = $value ;
492 $XsubAliasValues{$value} = $orig_alias ;
495 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
501 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
504 GetAliases($_) if $_ ;
508 sub REQUIRE_handler ()
510 # the rest of the current line should contain a version number
513 TrimWhitespace($Ver) ;
515 death ("Error: REQUIRE expects a version number")
518 # check that the version number is of the form n.n
519 death ("Error: REQUIRE: expected a number, got '$Ver'")
520 unless $Ver =~ /^\d+(\.\d*)?/ ;
522 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
523 unless $XSUBPP_version >= $Ver ;
526 sub VERSIONCHECK_handler ()
528 # the rest of the current line should contain either ENABLE or
533 # check for ENABLE/DISABLE
534 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
535 unless /^(ENABLE|DISABLE)/i ;
537 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
538 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
542 sub PROTOTYPE_handler ()
546 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
547 if $proto_in_this_xsub ++ ;
549 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
553 if ($_ eq 'DISABLE') {
556 elsif ($_ eq 'ENABLE') {
560 # remove any whitespace
562 death("Error: Invalid prototype '$_'")
563 unless ValidProtoString($_) ;
564 $ProtoThisXSUB = C_string($_) ;
568 # If no prototype specified, then assume empty prototype ""
569 $ProtoThisXSUB = 2 unless $specified ;
577 death("Error: Only 1 SCOPE declaration allowed per xsub")
578 if $scope_in_this_xsub ++ ;
580 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
583 if ($_ =~ /^DISABLE/i) {
586 elsif ($_ =~ /^ENABLE/i) {
593 sub PROTOTYPES_handler ()
595 # the rest of the current line should contain either ENABLE or
600 # check for ENABLE/DISABLE
601 death ("Error: PROTOTYPES: ENABLE/DISABLE")
602 unless /^(ENABLE|DISABLE)/i ;
604 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
605 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
610 sub INCLUDE_handler ()
612 # the rest of the current line should contain a valid filename
616 death("INCLUDE: filename missing")
619 death("INCLUDE: output pipe is illegal")
622 # simple minded recursion detector
623 death("INCLUDE loop detected")
624 if $IncludedFiles{$_} ;
626 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
628 # Save the current file context.
631 LastLine => $lastline,
632 LastLineNo => $lastline_no,
635 Filename => $filename,
642 open ($FH, "$_") or death("Cannot open '$_': $!") ;
646 #/* INCLUDE: Including '$_' from '$filename' */
652 # Prime the pump by reading the first
655 # skip leading blank lines
657 last unless /^\s*$/ ;
667 return 0 unless $XSStack[-1]{type} eq 'file' ;
669 my $data = pop @XSStack ;
670 my $ThisFile = $filename ;
671 my $isPipe = ($filename =~ /\|\s*$/) ;
673 -- $IncludedFiles{$filename}
678 $FH = $data->{Handle} ;
679 $filename = $data->{Filename} ;
680 $lastline = $data->{LastLine} ;
681 $lastline_no = $data->{LastLineNo} ;
682 @line = @{ $data->{Line} } ;
683 @line_no = @{ $data->{LineNo} } ;
685 if ($isPipe and $? ) {
687 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
693 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
700 sub ValidProtoString ($)
704 if ( $string =~ /^$proto_re+$/ ) {
715 $string =~ s[\\][\\\\]g ;
723 $proto_letter{$type} or "\$" ;
727 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
729 my ($cpp, $cpplevel);
731 if ($cpp =~ /^\#\s*if/) {
733 } elsif (!$cpplevel) {
734 Warn("Warning: #else/elif/endif without #if in this function");
735 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
736 if $XSStack[-1]{type} eq 'if';
738 } elsif ($cpp =~ /^\#\s*endif/) {
742 Warn("Warning: #if without #endif in this function") if $cpplevel;
755 open($FH, $filename) or die "cannot open $filename: $!\n";
757 # Identify the version of xsubpp used
760 * This file was generated automatically by xsubpp version $XSUBPP_version from the
761 * contents of $filename. Do not edit this file, edit $filename instead.
763 * ANY CHANGES MADE HERE WILL BE LOST!
770 print("#line 1 \"$filename\"\n")
774 last if ($Module, $Package, $Prefix) =
775 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
778 s/#if(?:def|\s+defined)\s+(\(__cplusplus\)|__cplusplus)/#if defined(__cplusplus) && !defined(PERL_OBJECT)/;
782 &Exit unless defined $_;
784 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
789 # Read next xsub into @line from ($lastline, <$FH>).
792 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
793 if !defined $lastline && $XSStack[-1]{type} eq 'if';
796 return PopFile() if !defined $lastline;
799 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
801 $Package = defined($2) ? $2 : ''; # keep -w happy
802 $Prefix = defined($3) ? $3 : ''; # keep -w happy
803 $Prefix = quotemeta $Prefix ;
804 ($Module_cname = $Module) =~ s/\W/_/g;
805 ($Packid = $Package) =~ tr/:/_/;
806 $Packprefix = $Package;
807 $Packprefix .= "::" if $Packprefix ne "";
812 if ($lastline !~ /^\s*#/ ||
814 # ANSI: if ifdef ifndef elif else endif define undef
816 # gcc: warning include_next
818 # others: ident (gcc notes that some cpps have this one)
819 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
820 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
821 push(@line, $lastline);
822 push(@line_no, $lastline_no) ;
825 # Read next line and continuation lines
826 last unless defined($lastline = <$FH>);
829 $lastline .= $tmp_line
830 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
833 $lastline =~ s/^\s+$//;
835 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
840 while (fetch_para()) {
841 # Print initial preprocessor statements and blank lines
842 while (@line && $line[0] !~ /^[^\#]/) {
843 my $line = shift(@line);
845 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
847 if ($statement eq 'if') {
848 $XSS_work_idx = @XSStack;
849 push(@XSStack, {type => 'if'});
851 death ("Error: `$statement' with no matching `if'")
852 if $XSStack[-1]{type} ne 'if';
853 if ($XSStack[-1]{varname}) {
854 push(@InitFileCode, "#endif\n");
855 push(@BootCode, "#endif");
858 my(@fns) = keys %{$XSStack[-1]{functions}};
859 if ($statement ne 'endif') {
860 # Hide the functions defined in other #if branches, and reset.
861 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
862 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
864 my($tmp) = pop(@XSStack);
865 0 while (--$XSS_work_idx
866 && $XSStack[$XSS_work_idx]{type} ne 'if');
867 # Keep all new defined functions
868 push(@fns, keys %{$tmp->{other_functions}});
869 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
874 next PARAGRAPH unless @line;
876 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
877 # We are inside an #if, but have not yet #defined its xsubpp variable.
878 print "#define $cpp_next_tmp 1\n\n";
879 push(@InitFileCode, "#if $cpp_next_tmp\n");
880 push(@BootCode, "#if $cpp_next_tmp");
881 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
884 death ("Code is not inside a function"
885 ." (maybe last function was ended by a blank line "
886 ." followed by a a statement on column one?)")
887 if $line[0] =~ /^\s/;
889 # initialize info arrays
900 undef($proto_in_this_xsub) ;
901 undef($scope_in_this_xsub) ;
903 $interface_macro = 'XSINTERFACE_FUNC' ;
904 $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
905 $ProtoThisXSUB = $WantPrototypes ;
909 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
910 &{"${kwd}_handler"}() ;
911 next PARAGRAPH unless @line ;
915 if (check_keyword("BOOT")) {
917 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
918 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
919 push (@BootCode, @line, "") ;
924 # extract return type, function name and arguments
925 ($ret_type) = TidyType($_);
927 # a function definition needs at least 2 lines
928 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
931 $static = 1 if $ret_type =~ s/^static\s+//;
933 $func_header = shift(@line);
934 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
935 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*$/s;
937 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
938 $class = "$4 $class" if $4;
939 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
940 ($clean_func_name = $func_name) =~ s/^$Prefix//;
941 $Full_func_name = "${Packid}_$clean_func_name";
942 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
944 # Check for duplicate function definition
945 for $tmp (@XSStack) {
946 next unless defined $tmp->{functions}{$Full_func_name};
947 Warn("Warning: duplicate function definition '$clean_func_name' detected");
950 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
951 %XsubAliases = %XsubAliasValues = %Interfaces = ();
954 @args = split(/\s*,\s*/, $orig_args);
955 if (defined($class)) {
956 my $arg0 = ((defined($static) or $func_name eq 'new')
958 unshift(@args, $arg0);
959 ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
961 $orig_args =~ s/"/\\"/g;
962 $min_args = $num_args = @args;
963 foreach $i (0..$num_args-1) {
964 if ($args[$i] =~ s/\.\.\.//) {
967 if ($args[$i] eq '' && $i == $num_args - 1) {
972 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
975 $defaults{$args[$i]} = $2;
976 $defaults{$args[$i]} =~ s/"/\\"/g;
978 $proto_arg[$i+1] = "\$" ;
980 if (defined($class)) {
981 $func_args = join(", ", @args[1..$#args]);
983 $func_args = join(", ", @args);
985 @args_match{@args} = 1..@args;
987 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
988 $CODE = grep(/^\s*CODE\s*:/, @line);
989 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
990 # to set explicit return values.
991 $EXPLICIT_RETURN = ($CODE &&
992 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
993 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
994 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
996 # print function header
998 #XS(XS_${Full_func_name})
1002 print Q<<"EOF" if $ALIAS ;
1005 print Q<<"EOF" if $INTERFACE ;
1006 # dXSFUNCTION($ret_type);
1009 $cond = ($min_args ? qq(items < $min_args) : 0);
1011 elsif ($min_args == $num_args) {
1012 $cond = qq(items != $min_args);
1015 $cond = qq(items < $min_args || items > $num_args);
1018 print Q<<"EOF" if $except;
1019 # char errbuf[1024];
1024 { print Q<<"EOF" if $cond }
1026 # croak("Usage: %s($orig_args)", GvNAME(CvGV(cv)));
1029 { print Q<<"EOF" if $cond }
1031 # croak("Usage: $pname($orig_args)");
1034 print Q<<"EOF" if $PPCODE;
1038 # Now do a block of some sort.
1041 $cond = ''; # last CASE: condidional
1042 push(@line, "$END:");
1043 push(@line_no, $line_no[-1]);
1047 &CASE_handler if check_keyword("CASE");
1052 # do initialization of input variables
1060 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|PROTOTYPE|SCOPE") ;
1062 print Q<<"EOF" if $ScopeThisXSUB;
1067 if (!$thisdone && defined($class)) {
1068 if (defined($static) or $func_name eq 'new') {
1070 $var_types{"CLASS"} = "char *";
1071 &generate_init("char *", 1, "CLASS");
1075 $var_types{"THIS"} = "$class *";
1076 &generate_init("$class *", 1, "THIS");
1081 if (/^\s*NOT_IMPLEMENTED_YET/) {
1082 print "\n\tcroak(\"$pname: not implemented yet\");\n";
1085 if ($ret_type ne "void") {
1086 print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
1088 $args_match{"RETVAL"} = 0;
1089 $var_types{"RETVAL"} = $ret_type;
1094 process_keyword("INIT|ALIAS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
1096 if (check_keyword("PPCODE")) {
1098 death ("PPCODE must be last thing") if @line;
1099 print "\tLEAVE;\n" if $ScopeThisXSUB;
1100 print "\tPUTBACK;\n\treturn;\n";
1101 } elsif (check_keyword("CODE")) {
1103 } elsif (defined($class) and $func_name eq "DESTROY") {
1105 print "delete THIS;\n";
1108 if ($ret_type ne "void") {
1112 if (defined($static)) {
1113 if ($func_name eq 'new') {
1114 $func_name = "$class";
1118 } elsif (defined($class)) {
1119 if ($func_name eq 'new') {
1120 $func_name .= " $class";
1125 $func_name =~ s/^($spat)//
1127 $func_name = 'XSFUNCTION' if $interface;
1128 print "$func_name($func_args);\n";
1132 # do output variables
1134 undef $RETVAL_code ;
1136 process_keyword("OUTPUT|ALIAS|PROTOTYPE");
1138 # all OUTPUT done, so now push the return value on the stack
1139 if ($gotRETVAL && $RETVAL_code) {
1140 print "\t$RETVAL_code\n";
1141 } elsif ($gotRETVAL || $wantRETVAL) {
1142 # RETVAL almost never needs SvSETMAGIC()
1143 &generate_output($ret_type, 0, 'RETVAL', 0);
1147 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
1149 print Q<<"EOF" if $ScopeThisXSUB;
1152 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1156 # print function trailer
1160 print Q<<EOF if $except;
1163 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1166 if (check_keyword("CASE")) {
1167 blurt ("Error: No `CASE:' at top of function")
1169 $_ = "CASE: $_"; # Restore CASE: label
1172 last if $_ eq "$END:";
1173 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1176 print Q<<EOF if $except;
1181 if ($ret_type ne "void" or $EXPLICIT_RETURN) {
1182 print Q<<EOF unless $PPCODE;
1186 print Q<<EOF unless $PPCODE;
1196 my $newXS = "newXS" ;
1199 # Build the prototype string for the xsub
1200 if ($ProtoThisXSUB) {
1201 $newXS = "newXSproto";
1203 if ($ProtoThisXSUB eq 2) {
1204 # User has specified empty prototype
1207 elsif ($ProtoThisXSUB ne 1) {
1208 # User has specified a prototype
1209 $proto = ', "' . $ProtoThisXSUB . '"';
1213 if ($min_args < $num_args) {
1215 $proto_arg[$min_args] .= ";" ;
1217 push @proto_arg, "$s\@"
1220 $proto = ', "' . join ("", @proto_arg) . '"';
1225 $XsubAliases{$pname} = 0
1226 unless defined $XsubAliases{$pname} ;
1227 while ( ($name, $value) = each %XsubAliases) {
1228 push(@InitFileCode, Q<<"EOF");
1229 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1230 # XSANY.any_i32 = $value ;
1232 push(@InitFileCode, Q<<"EOF") if $proto;
1233 # sv_setpv((SV*)cv$proto) ;
1237 elsif ($interface) {
1238 while ( ($name, $value) = each %Interfaces) {
1239 $name = "$Package\::$name" unless $name =~ /::/;
1240 push(@InitFileCode, Q<<"EOF");
1241 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1242 # $interface_macro_set(cv,$value) ;
1244 push(@InitFileCode, Q<<"EOF") if $proto;
1245 # sv_setpv((SV*)cv$proto) ;
1251 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1255 # print initialization routine
1262 #XS(boot__CAPI_entry)
1265 # char* file = __FILE__;
1273 #XS(boot_$Module_cname)
1276 # char* file = __FILE__;
1281 print Q<<"EOF" if $WantVersionChk ;
1282 # XS_VERSION_BOOTCHECK ;
1286 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1292 print @InitFileCode;
1294 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1300 print "\n /* Initialisation Section */\n\n" ;
1303 print "\n /* End of Initialisation Section */\n\n" ;
1316 ##define XSCAPI(name) void name(CV* cv, void* pPerl)
1321 #XSCAPI(boot_$Module_cname)
1323 # SetCPerlObj(pPerl);
1324 # boot__CAPI_entry(cv);
1330 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1336 local($type, $num, $init) = @_;
1337 local($arg) = "ST(" . ($num - 1) . ")";
1339 eval qq/print " $init\\\n"/;
1344 # work out the line number
1345 my $line_no = $line_no[@line_no - @line -1] ;
1347 print STDERR "@_ in $filename, line $line_no\n" ;
1363 local($type, $num, $var) = @_;
1364 local($arg) = "ST(" . ($num - 1) . ")";
1365 local($argoff) = $num - 1;
1369 $type = TidyType($type) ;
1370 blurt("Error: '$type' not in typemap"), return
1371 unless defined($type_kind{$type});
1373 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1374 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1375 $tk = $type_kind{$type};
1376 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1378 blurt("Error: No INPUT definition for type '$type' found"), return
1379 unless defined $input_expr{$tk} ;
1380 $expr = $input_expr{$tk};
1381 if ($expr =~ /DO_ARRAY_ELEM/) {
1382 blurt("Error: '$subtype' not in typemap"), return
1383 unless defined($type_kind{$subtype});
1384 blurt("Error: No INPUT definition for type '$subtype' found"), return
1385 unless defined $input_expr{$type_kind{$subtype}} ;
1386 $subexpr = $input_expr{$type_kind{$subtype}};
1387 $subexpr =~ s/ntype/subtype/g;
1388 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1389 $subexpr =~ s/\n\t/\n\t\t/g;
1390 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1391 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1392 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1394 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1397 if (defined($defaults{$var})) {
1398 $expr =~ s/(\t+)/$1 /g;
1400 eval qq/print "\\t$var;\\n"/;
1401 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1402 } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1403 eval qq/print "\\t$var;\\n"/;
1404 $deferred .= eval qq/"\\n$expr;\\n"/;
1406 eval qq/print "$expr;\\n"/;
1410 sub generate_output {
1411 local($type, $num, $var, $do_setmagic) = @_;
1412 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1413 local($argoff) = $num - 1;
1416 $type = TidyType($type) ;
1417 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1418 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
1419 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1421 blurt("Error: '$type' not in typemap"), return
1422 unless defined($type_kind{$type});
1423 blurt("Error: No OUTPUT definition for type '$type' found"), return
1424 unless defined $output_expr{$type_kind{$type}} ;
1425 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1426 $ntype =~ s/\(\)//g;
1427 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1428 $expr = $output_expr{$type_kind{$type}};
1429 if ($expr =~ /DO_ARRAY_ELEM/) {
1430 blurt("Error: '$subtype' not in typemap"), return
1431 unless defined($type_kind{$subtype});
1432 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1433 unless defined $output_expr{$type_kind{$subtype}} ;
1434 $subexpr = $output_expr{$type_kind{$subtype}};
1435 $subexpr =~ s/ntype/subtype/g;
1436 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1437 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1438 $subexpr =~ s/\n\t/\n\t\t/g;
1439 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1440 eval "print qq\a$expr\a";
1441 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1443 elsif ($var eq 'RETVAL') {
1444 if ($expr =~ /^\t\$arg = new/) {
1445 # We expect that $arg has refcnt 1, so we need to
1447 eval "print qq\a$expr\a";
1448 print "\tsv_2mortal(ST(0));\n";
1449 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1451 elsif ($expr =~ /^\s*\$arg\s*=/) {
1452 # We expect that $arg has refcnt >=1, so we need
1453 # to mortalize it. However, the extension may have
1454 # returned the built-in perl value, which is
1455 # read-only, thus not mortalizable. However, it is
1456 # safe to leave it as it is, since it would be
1457 # ignored by REFCNT_dec. Builtin values have REFCNT==0.
1458 eval "print qq\a$expr\a";
1459 print "\tif (SvREFCNT(ST(0))) sv_2mortal(ST(0));\n";
1460 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1463 # Just hope that the entry would safely write it
1464 # over an already mortalized value. By
1465 # coincidence, something like $arg = &sv_undef
1467 print "\tST(0) = sv_newmortal();\n";
1468 eval "print qq\a$expr\a";
1469 # new mortals don't have set magic
1472 elsif ($arg =~ /^ST\(\d+\)$/) {
1473 eval "print qq\a$expr\a";
1474 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1483 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1489 # If this is VMS, the exit status has meaning to the shell, so we
1490 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1492 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1493 exit ($errors ? 1 : 0);