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*$/s;
937 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
938 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
939 ($clean_func_name = $func_name) =~ s/^$Prefix//;
940 $Full_func_name = "${Packid}_$clean_func_name";
941 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
943 # Check for duplicate function definition
944 for $tmp (@XSStack) {
945 next unless defined $tmp->{functions}{$Full_func_name};
946 Warn("Warning: duplicate function definition '$clean_func_name' detected");
949 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
950 %XsubAliases = %XsubAliasValues = %Interfaces = ();
953 @args = split(/\s*,\s*/, $orig_args);
954 if (defined($class)) {
955 my $arg0 = ((defined($static) or $func_name eq 'new')
957 unshift(@args, $arg0);
958 ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
960 $orig_args =~ s/"/\\"/g;
961 $min_args = $num_args = @args;
962 foreach $i (0..$num_args-1) {
963 if ($args[$i] =~ s/\.\.\.//) {
966 if ($args[$i] eq '' && $i == $num_args - 1) {
971 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
974 $defaults{$args[$i]} = $2;
975 $defaults{$args[$i]} =~ s/"/\\"/g;
977 $proto_arg[$i+1] = "\$" ;
979 if (defined($class)) {
980 $func_args = join(", ", @args[1..$#args]);
982 $func_args = join(", ", @args);
984 @args_match{@args} = 1..@args;
986 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
987 $CODE = grep(/^\s*CODE\s*:/, @line);
988 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
989 # to set explicit return values.
990 $EXPLICIT_RETURN = ($CODE &&
991 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
992 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
993 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
995 # print function header
997 #XS(XS_${Full_func_name})
1001 print Q<<"EOF" if $ALIAS ;
1004 print Q<<"EOF" if $INTERFACE ;
1005 # dXSFUNCTION($ret_type);
1008 $cond = ($min_args ? qq(items < $min_args) : 0);
1010 elsif ($min_args == $num_args) {
1011 $cond = qq(items != $min_args);
1014 $cond = qq(items < $min_args || items > $num_args);
1017 print Q<<"EOF" if $except;
1018 # char errbuf[1024];
1023 { print Q<<"EOF" if $cond }
1025 # croak("Usage: %s($orig_args)", GvNAME(CvGV(cv)));
1028 { print Q<<"EOF" if $cond }
1030 # croak("Usage: $pname($orig_args)");
1033 print Q<<"EOF" if $PPCODE;
1037 # Now do a block of some sort.
1040 $cond = ''; # last CASE: condidional
1041 push(@line, "$END:");
1042 push(@line_no, $line_no[-1]);
1046 &CASE_handler if check_keyword("CASE");
1051 # do initialization of input variables
1059 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|PROTOTYPE|SCOPE") ;
1061 print Q<<"EOF" if $ScopeThisXSUB;
1066 if (!$thisdone && defined($class)) {
1067 if (defined($static) or $func_name eq 'new') {
1069 $var_types{"CLASS"} = "char *";
1070 &generate_init("char *", 1, "CLASS");
1074 $var_types{"THIS"} = "$class *";
1075 &generate_init("$class *", 1, "THIS");
1080 if (/^\s*NOT_IMPLEMENTED_YET/) {
1081 print "\n\tcroak(\"$pname: not implemented yet\");\n";
1084 if ($ret_type ne "void") {
1085 print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
1087 $args_match{"RETVAL"} = 0;
1088 $var_types{"RETVAL"} = $ret_type;
1093 process_keyword("INIT|ALIAS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
1095 if (check_keyword("PPCODE")) {
1097 death ("PPCODE must be last thing") if @line;
1098 print "\tLEAVE;\n" if $ScopeThisXSUB;
1099 print "\tPUTBACK;\n\treturn;\n";
1100 } elsif (check_keyword("CODE")) {
1102 } elsif (defined($class) and $func_name eq "DESTROY") {
1104 print "delete THIS;\n";
1107 if ($ret_type ne "void") {
1111 if (defined($static)) {
1112 if ($func_name eq 'new') {
1113 $func_name = "$class";
1117 } elsif (defined($class)) {
1118 if ($func_name eq 'new') {
1119 $func_name .= " $class";
1124 $func_name =~ s/^($spat)//
1126 $func_name = 'XSFUNCTION' if $interface;
1127 print "$func_name($func_args);\n";
1131 # do output variables
1133 undef $RETVAL_code ;
1135 process_keyword("OUTPUT|ALIAS|PROTOTYPE");
1137 # all OUTPUT done, so now push the return value on the stack
1138 if ($gotRETVAL && $RETVAL_code) {
1139 print "\t$RETVAL_code\n";
1140 } elsif ($gotRETVAL || $wantRETVAL) {
1141 # RETVAL almost never needs SvSETMAGIC()
1142 &generate_output($ret_type, 0, 'RETVAL', 0);
1146 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
1148 print Q<<"EOF" if $ScopeThisXSUB;
1151 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1155 # print function trailer
1159 print Q<<EOF if $except;
1162 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1165 if (check_keyword("CASE")) {
1166 blurt ("Error: No `CASE:' at top of function")
1168 $_ = "CASE: $_"; # Restore CASE: label
1171 last if $_ eq "$END:";
1172 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1175 print Q<<EOF if $except;
1180 if ($ret_type ne "void" or $EXPLICIT_RETURN) {
1181 print Q<<EOF unless $PPCODE;
1185 print Q<<EOF unless $PPCODE;
1195 my $newXS = "newXS" ;
1198 # Build the prototype string for the xsub
1199 if ($ProtoThisXSUB) {
1200 $newXS = "newXSproto";
1202 if ($ProtoThisXSUB eq 2) {
1203 # User has specified empty prototype
1206 elsif ($ProtoThisXSUB ne 1) {
1207 # User has specified a prototype
1208 $proto = ', "' . $ProtoThisXSUB . '"';
1212 if ($min_args < $num_args) {
1214 $proto_arg[$min_args] .= ";" ;
1216 push @proto_arg, "$s\@"
1219 $proto = ', "' . join ("", @proto_arg) . '"';
1224 $XsubAliases{$pname} = 0
1225 unless defined $XsubAliases{$pname} ;
1226 while ( ($name, $value) = each %XsubAliases) {
1227 push(@InitFileCode, Q<<"EOF");
1228 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1229 # XSANY.any_i32 = $value ;
1231 push(@InitFileCode, Q<<"EOF") if $proto;
1232 # sv_setpv((SV*)cv$proto) ;
1236 elsif ($interface) {
1237 while ( ($name, $value) = each %Interfaces) {
1238 $name = "$Package\::$name" unless $name =~ /::/;
1239 push(@InitFileCode, Q<<"EOF");
1240 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1241 # $interface_macro_set(cv,$value) ;
1243 push(@InitFileCode, Q<<"EOF") if $proto;
1244 # sv_setpv((SV*)cv$proto) ;
1250 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1254 # print initialization routine
1261 #XS(boot__CAPI_entry)
1264 # char* file = __FILE__;
1272 #XS(boot_$Module_cname)
1275 # char* file = __FILE__;
1280 print Q<<"EOF" if $WantVersionChk ;
1281 # XS_VERSION_BOOTCHECK ;
1285 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1291 print @InitFileCode;
1293 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1299 print "\n /* Initialisation Section */\n\n" ;
1302 print "\n /* End of Initialisation Section */\n\n" ;
1315 ##define XSCAPI(name) void name(CV* cv, void* pPerl)
1320 #XSCAPI(boot_$Module_cname)
1322 # SetCPerlObj(pPerl);
1323 # boot__CAPI_entry(cv);
1329 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1335 local($type, $num, $init) = @_;
1336 local($arg) = "ST(" . ($num - 1) . ")";
1338 eval qq/print " $init\\\n"/;
1343 # work out the line number
1344 my $line_no = $line_no[@line_no - @line -1] ;
1346 print STDERR "@_ in $filename, line $line_no\n" ;
1362 local($type, $num, $var) = @_;
1363 local($arg) = "ST(" . ($num - 1) . ")";
1364 local($argoff) = $num - 1;
1368 $type = TidyType($type) ;
1369 blurt("Error: '$type' not in typemap"), return
1370 unless defined($type_kind{$type});
1372 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1373 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1374 $tk = $type_kind{$type};
1375 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1377 blurt("Error: No INPUT definition for type '$type' found"), return
1378 unless defined $input_expr{$tk} ;
1379 $expr = $input_expr{$tk};
1380 if ($expr =~ /DO_ARRAY_ELEM/) {
1381 blurt("Error: '$subtype' not in typemap"), return
1382 unless defined($type_kind{$subtype});
1383 blurt("Error: No INPUT definition for type '$subtype' found"), return
1384 unless defined $input_expr{$type_kind{$subtype}} ;
1385 $subexpr = $input_expr{$type_kind{$subtype}};
1386 $subexpr =~ s/ntype/subtype/g;
1387 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1388 $subexpr =~ s/\n\t/\n\t\t/g;
1389 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1390 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1391 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1393 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1396 if (defined($defaults{$var})) {
1397 $expr =~ s/(\t+)/$1 /g;
1399 eval qq/print "\\t$var;\\n"/;
1400 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1401 } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1402 eval qq/print "\\t$var;\\n"/;
1403 $deferred .= eval qq/"\\n$expr;\\n"/;
1405 eval qq/print "$expr;\\n"/;
1409 sub generate_output {
1410 local($type, $num, $var, $do_setmagic) = @_;
1411 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1412 local($argoff) = $num - 1;
1415 $type = TidyType($type) ;
1416 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1417 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
1418 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1420 blurt("Error: '$type' not in typemap"), return
1421 unless defined($type_kind{$type});
1422 blurt("Error: No OUTPUT definition for type '$type' found"), return
1423 unless defined $output_expr{$type_kind{$type}} ;
1424 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1425 $ntype =~ s/\(\)//g;
1426 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1427 $expr = $output_expr{$type_kind{$type}};
1428 if ($expr =~ /DO_ARRAY_ELEM/) {
1429 blurt("Error: '$subtype' not in typemap"), return
1430 unless defined($type_kind{$subtype});
1431 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1432 unless defined $output_expr{$type_kind{$subtype}} ;
1433 $subexpr = $output_expr{$type_kind{$subtype}};
1434 $subexpr =~ s/ntype/subtype/g;
1435 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1436 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1437 $subexpr =~ s/\n\t/\n\t\t/g;
1438 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1439 eval "print qq\a$expr\a";
1440 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1442 elsif ($var eq 'RETVAL') {
1443 if ($expr =~ /^\t\$arg = new/) {
1444 # We expect that $arg has refcnt 1, so we need to
1446 eval "print qq\a$expr\a";
1447 print "\tsv_2mortal(ST(0));\n";
1448 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1450 elsif ($expr =~ /^\s*\$arg\s*=/) {
1451 # We expect that $arg has refcnt >=1, so we need
1452 # to mortalize it. However, the extension may have
1453 # returned the built-in perl value, which is
1454 # read-only, thus not mortalizable. However, it is
1455 # safe to leave it as it is, since it would be
1456 # ignored by REFCNT_dec. Builtin values have REFCNT==0.
1457 eval "print qq\a$expr\a";
1458 print "\tif (SvREFCNT(ST(0))) sv_2mortal(ST(0));\n";
1459 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1462 # Just hope that the entry would safely write it
1463 # over an already mortalized value. By
1464 # coincidence, something like $arg = &sv_undef
1466 print "\tST(0) = sv_newmortal();\n";
1467 eval "print qq\a$expr\a";
1468 # new mortals don't have set magic
1471 elsif ($arg =~ /^ST\(\d+\)$/) {
1472 eval "print qq\a$expr\a";
1473 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1482 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1488 # If this is VMS, the exit status has meaning to the shell, so we
1489 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1491 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1492 exit ($errors ? 1 : 0);