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';
93 $XSUBPP_version = "1.9507";
95 my ($Is_VMS, $SymSet);
98 # Establish set of global symbols with max length 28, since xsubpp
99 # will later add the 'XS_' prefix.
100 require ExtUtils::XSSymSet;
101 $SymSet = new ExtUtils::XSSymSet 28;
106 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-s pattern] [-typemap typemap]... file.xs\n";
108 $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
110 $OBJ = 1 if $Config{'ccflags'} =~ /PERL_OBJECT/i;
113 $WantPrototypes = -1 ;
114 $WantVersionChk = 1 ;
116 $WantLineNumbers = 1 ;
117 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
120 $spat = quotemeta shift, next SWITCH if $flag eq 's';
121 $cplusplus = 1, next SWITCH if $flag eq 'C++';
122 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
123 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
124 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
125 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
126 # XXX left this in for compat
127 $WantCAPI = 1, next SWITCH if $flag eq 'object_capi';
128 $except = " TRY", next SWITCH if $flag eq 'except';
129 push(@tm,shift), next SWITCH if $flag eq 'typemap';
130 $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
131 $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
132 (print "xsubpp version $XSUBPP_version\n"), exit
136 if ($WantPrototypes == -1)
137 { $WantPrototypes = 0}
142 @ARGV == 1 or die $usage;
143 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
144 or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
145 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
146 or ($dir, $filename) = ('.', $ARGV[0]);
150 ++ $IncludedFiles{$ARGV[0]} ;
152 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
153 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
158 $_[0] =~ s/^\s+|\s+$//go ;
165 # rationalise any '*' by joining them into bunches and removing whitespace
169 # change multiple whitespace into a single space
172 # trim leading & trailing whitespace
178 $typemap = shift @ARGV;
179 foreach $typemap (@tm) {
180 die "Can't find $typemap in $pwd\n" unless -r $typemap;
182 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
183 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
185 foreach $typemap (@tm) {
186 next unless -e $typemap ;
187 # skip directories, binary files etc.
188 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
190 open(TYPEMAP, $typemap)
191 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
197 my $line_no = $. + 1;
198 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
199 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
200 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
201 if ($mode eq 'Typemap') {
205 # skip blank lines and comment lines
206 next if /^$/ or /^#/ ;
207 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
208 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
209 $type = TidyType($type) ;
210 $type_kind{$type} = $kind ;
211 # prototype defaults to '$'
212 $proto = "\$" unless $proto ;
213 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
214 unless ValidProtoString($proto) ;
215 $proto_letter{$type} = C_string($proto) ;
220 elsif ($mode eq 'Input') {
222 $input_expr{$_} = '';
223 $current = \$input_expr{$_};
227 $output_expr{$_} = '';
228 $current = \$output_expr{$_};
234 foreach $key (keys %input_expr) {
235 $input_expr{$key} =~ s/\n+$//;
238 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
240 # Match an XS keyword
241 $BLOCK_re= '\s*(' . join('|', qw(
242 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
243 CLEANUP ALIAS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
244 SCOPE INTERFACE INTERFACE_MACRO C_ARGS
247 # Input: ($_, @line) == unparsed input.
248 # Output: ($_, @line) == (rest of line, following lines).
249 # Return: the matched keyword if found, otherwise 0
251 $_ = shift(@line) while !/\S/ && @line;
252 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
256 if ($WantLineNumbers) {
258 package xsubpp::counter;
260 my ($class, $cfile) = @_;
262 $SECTION_END_MARKER = "#line --- \"$cfile\"";
271 while ($$self =~ s/^([^\n]*\n)//) {
274 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
283 $self->PRINT(sprintf($fmt, @_));
287 # Not necessary if we're careful to end with a "\n"
293 my $cfile = $filename;
294 $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
295 tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
296 select PSEUDO_STDOUT;
300 # the "do" is required for right semantics
301 do { $_ = shift(@line) } while !/\S/ && @line;
303 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
304 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
305 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
308 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
314 while (!/\S/ && @line) {
318 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
325 sub process_keyword($)
330 &{"${kwd}_handler"}()
331 while $kwd = check_keyword($pattern) ;
335 blurt ("Error: `CASE:' after unconditional `CASE:'")
336 if $condnum && $cond eq '';
338 TrimWhitespace($cond);
339 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
344 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
345 last if /^\s*NOT_IMPLEMENTED_YET/;
346 next unless /\S/; # skip blank lines
351 # remove trailing semicolon if no initialisation
352 s/\s*;$//g unless /[=;+].*\S/ ;
354 # check for optional initialisation code
356 $var_init = $1 if s/\s*([=;+].*)$//s ;
357 $var_init =~ s/"/\\"/g;
360 my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
361 or blurt("Error: invalid argument declaration '$line'"), next;
363 # Check for duplicate definitions
364 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
365 if $arg_list{$var_name} ++ ;
367 $thisdone |= $var_name eq "THIS";
368 $retvaldone |= $var_name eq "RETVAL";
369 $var_types{$var_name} = $var_type;
370 print "\t" . &map_type($var_type);
371 $var_num = $args_match{$var_name};
373 $proto_arg[$var_num] = ProtoString($var_type)
376 $var_addr{$var_name} = 1;
377 $func_args =~ s/\b($var_name)\b/&$1/;
379 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/) {
380 print "\t$var_name;\n";
381 } elsif ($var_init =~ /\S/) {
382 &output_init($var_type, $var_num, $var_name, $var_init);
384 # generate initialization code
385 &generate_init($var_type, $var_num, $var_name);
393 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
395 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
396 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
399 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
400 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
401 if $outargs{$outarg} ++ ;
402 if (!$gotRETVAL and $outarg eq 'RETVAL') {
403 # deal with RETVAL last
404 $RETVAL_code = $outcode ;
408 blurt ("Error: OUTPUT $outarg not an argument"), next
409 unless defined($args_match{$outarg});
410 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
411 unless defined $var_types{$outarg} ;
412 $var_num = $args_match{$outarg};
414 print "\t$outcode\n";
415 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
417 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
422 sub C_ARGS_handler() {
423 my $in = merge_section();
429 sub INTERFACE_MACRO_handler() {
430 my $in = merge_section();
433 if ($in =~ /\s/) { # two
434 ($interface_macro, $interface_macro_set) = split ' ', $in;
436 $interface_macro = $in;
437 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
439 $interface = 1; # local
440 $Interfaces = 1; # global
443 sub INTERFACE_handler() {
444 my $in = merge_section();
448 foreach (split /[\s,]+/, $in) {
449 $Interfaces{$_} = $_;
452 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
454 $interface = 1; # local
455 $Interfaces = 1; # global
458 sub CLEANUP_handler() { print_section() }
459 sub PREINIT_handler() { print_section() }
460 sub INIT_handler() { print_section() }
469 # Parse alias definitions
471 # alias = value alias = value ...
473 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
475 $orig_alias = $alias ;
478 # check for optional package definition in the alias
479 $alias = $Packprefix . $alias if $alias !~ /::/ ;
481 # check for duplicate alias name & duplicate value
482 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
483 if defined $XsubAliases{$alias} ;
485 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
486 if $XsubAliasValues{$value} ;
489 $XsubAliases{$alias} = $value ;
490 $XsubAliasValues{$value} = $orig_alias ;
493 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
499 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
502 GetAliases($_) if $_ ;
506 sub REQUIRE_handler ()
508 # the rest of the current line should contain a version number
511 TrimWhitespace($Ver) ;
513 death ("Error: REQUIRE expects a version number")
516 # check that the version number is of the form n.n
517 death ("Error: REQUIRE: expected a number, got '$Ver'")
518 unless $Ver =~ /^\d+(\.\d*)?/ ;
520 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
521 unless $XSUBPP_version >= $Ver ;
524 sub VERSIONCHECK_handler ()
526 # the rest of the current line should contain either ENABLE or
531 # check for ENABLE/DISABLE
532 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
533 unless /^(ENABLE|DISABLE)/i ;
535 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
536 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
540 sub PROTOTYPE_handler ()
544 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
545 if $proto_in_this_xsub ++ ;
547 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
551 if ($_ eq 'DISABLE') {
554 elsif ($_ eq 'ENABLE') {
558 # remove any whitespace
560 death("Error: Invalid prototype '$_'")
561 unless ValidProtoString($_) ;
562 $ProtoThisXSUB = C_string($_) ;
566 # If no prototype specified, then assume empty prototype ""
567 $ProtoThisXSUB = 2 unless $specified ;
575 death("Error: Only 1 SCOPE declaration allowed per xsub")
576 if $scope_in_this_xsub ++ ;
578 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
581 if ($_ =~ /^DISABLE/i) {
584 elsif ($_ =~ /^ENABLE/i) {
591 sub PROTOTYPES_handler ()
593 # the rest of the current line should contain either ENABLE or
598 # check for ENABLE/DISABLE
599 death ("Error: PROTOTYPES: ENABLE/DISABLE")
600 unless /^(ENABLE|DISABLE)/i ;
602 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
603 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
608 sub INCLUDE_handler ()
610 # the rest of the current line should contain a valid filename
614 death("INCLUDE: filename missing")
617 death("INCLUDE: output pipe is illegal")
620 # simple minded recursion detector
621 death("INCLUDE loop detected")
622 if $IncludedFiles{$_} ;
624 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
626 # Save the current file context.
629 LastLine => $lastline,
630 LastLineNo => $lastline_no,
633 Filename => $filename,
640 open ($FH, "$_") or death("Cannot open '$_': $!") ;
644 #/* INCLUDE: Including '$_' from '$filename' */
650 # Prime the pump by reading the first
653 # skip leading blank lines
655 last unless /^\s*$/ ;
665 return 0 unless $XSStack[-1]{type} eq 'file' ;
667 my $data = pop @XSStack ;
668 my $ThisFile = $filename ;
669 my $isPipe = ($filename =~ /\|\s*$/) ;
671 -- $IncludedFiles{$filename}
676 $FH = $data->{Handle} ;
677 $filename = $data->{Filename} ;
678 $lastline = $data->{LastLine} ;
679 $lastline_no = $data->{LastLineNo} ;
680 @line = @{ $data->{Line} } ;
681 @line_no = @{ $data->{LineNo} } ;
683 if ($isPipe and $? ) {
685 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
691 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
698 sub ValidProtoString ($)
702 if ( $string =~ /^$proto_re+$/ ) {
713 $string =~ s[\\][\\\\]g ;
721 $proto_letter{$type} or "\$" ;
725 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
727 my ($cpp, $cpplevel);
729 if ($cpp =~ /^\#\s*if/) {
731 } elsif (!$cpplevel) {
732 Warn("Warning: #else/elif/endif without #if in this function");
733 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
734 if $XSStack[-1]{type} eq 'if';
736 } elsif ($cpp =~ /^\#\s*endif/) {
740 Warn("Warning: #if without #endif in this function") if $cpplevel;
753 open($FH, $filename) or die "cannot open $filename: $!\n";
755 # Identify the version of xsubpp used
758 * This file was generated automatically by xsubpp version $XSUBPP_version from the
759 * contents of $filename. Do not edit this file, edit $filename instead.
761 * ANY CHANGES MADE HERE WILL BE LOST!
768 print("#line 1 \"$filename\"\n")
772 last if ($Module, $Package, $Prefix) =
773 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
776 s/#if(?:def\s|\s+defined)\s*(\(__cplusplus\)|__cplusplus)/#if defined(__cplusplus) && !defined(PERL_OBJECT)/;
780 &Exit unless defined $_;
782 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
787 # Read next xsub into @line from ($lastline, <$FH>).
790 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
791 if !defined $lastline && $XSStack[-1]{type} eq 'if';
794 return PopFile() if !defined $lastline;
797 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
799 $Package = defined($2) ? $2 : ''; # keep -w happy
800 $Prefix = defined($3) ? $3 : ''; # keep -w happy
801 $Prefix = quotemeta $Prefix ;
802 ($Module_cname = $Module) =~ s/\W/_/g;
803 ($Packid = $Package) =~ tr/:/_/;
804 $Packprefix = $Package;
805 $Packprefix .= "::" if $Packprefix ne "";
810 if ($lastline !~ /^\s*#/ ||
812 # ANSI: if ifdef ifndef elif else endif define undef
814 # gcc: warning include_next
816 # others: ident (gcc notes that some cpps have this one)
817 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
818 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
819 push(@line, $lastline);
820 push(@line_no, $lastline_no) ;
823 # Read next line and continuation lines
824 last unless defined($lastline = <$FH>);
827 $lastline .= $tmp_line
828 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
831 $lastline =~ s/^\s+$//;
833 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
838 while (fetch_para()) {
839 # Print initial preprocessor statements and blank lines
840 while (@line && $line[0] !~ /^[^\#]/) {
841 my $line = shift(@line);
843 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
845 if ($statement eq 'if') {
846 $XSS_work_idx = @XSStack;
847 push(@XSStack, {type => 'if'});
849 death ("Error: `$statement' with no matching `if'")
850 if $XSStack[-1]{type} ne 'if';
851 if ($XSStack[-1]{varname}) {
852 push(@InitFileCode, "#endif\n");
853 push(@BootCode, "#endif");
856 my(@fns) = keys %{$XSStack[-1]{functions}};
857 if ($statement ne 'endif') {
858 # Hide the functions defined in other #if branches, and reset.
859 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
860 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
862 my($tmp) = pop(@XSStack);
863 0 while (--$XSS_work_idx
864 && $XSStack[$XSS_work_idx]{type} ne 'if');
865 # Keep all new defined functions
866 push(@fns, keys %{$tmp->{other_functions}});
867 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
872 next PARAGRAPH unless @line;
874 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
875 # We are inside an #if, but have not yet #defined its xsubpp variable.
876 print "#define $cpp_next_tmp 1\n\n";
877 push(@InitFileCode, "#if $cpp_next_tmp\n");
878 push(@BootCode, "#if $cpp_next_tmp");
879 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
882 death ("Code is not inside a function"
883 ." (maybe last function was ended by a blank line "
884 ." followed by a a statement on column one?)")
885 if $line[0] =~ /^\s/;
887 # initialize info arrays
898 undef($proto_in_this_xsub) ;
899 undef($scope_in_this_xsub) ;
901 $interface_macro = 'XSINTERFACE_FUNC' ;
902 $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
903 $ProtoThisXSUB = $WantPrototypes ;
907 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
908 &{"${kwd}_handler"}() ;
909 next PARAGRAPH unless @line ;
913 if (check_keyword("BOOT")) {
915 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
916 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
917 push (@BootCode, @line, "") ;
922 # extract return type, function name and arguments
923 ($ret_type) = TidyType($_);
925 # a function definition needs at least 2 lines
926 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
929 $static = 1 if $ret_type =~ s/^static\s+//;
931 $func_header = shift(@line);
932 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
933 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*$/s;
935 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
936 $class = "$4 $class" if $4;
937 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
938 ($clean_func_name = $func_name) =~ s/^$Prefix//;
939 $Full_func_name = "${Packid}_$clean_func_name";
940 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
942 # Check for duplicate function definition
943 for $tmp (@XSStack) {
944 next unless defined $tmp->{functions}{$Full_func_name};
945 Warn("Warning: duplicate function definition '$clean_func_name' detected");
948 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
949 %XsubAliases = %XsubAliasValues = %Interfaces = ();
952 @args = split(/\s*,\s*/, $orig_args);
953 if (defined($class)) {
954 my $arg0 = ((defined($static) or $func_name eq 'new')
956 unshift(@args, $arg0);
957 ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
959 $orig_args =~ s/"/\\"/g;
960 $min_args = $num_args = @args;
961 foreach $i (0..$num_args-1) {
962 if ($args[$i] =~ s/\.\.\.//) {
965 if ($args[$i] eq '' && $i == $num_args - 1) {
970 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
973 $defaults{$args[$i]} = $2;
974 $defaults{$args[$i]} =~ s/"/\\"/g;
976 $proto_arg[$i+1] = "\$" ;
978 if (defined($class)) {
979 $func_args = join(", ", @args[1..$#args]);
981 $func_args = join(", ", @args);
983 @args_match{@args} = 1..@args;
985 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
986 $CODE = grep(/^\s*CODE\s*:/, @line);
987 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
988 # to set explicit return values.
989 $EXPLICIT_RETURN = ($CODE &&
990 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
991 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
992 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
994 # print function header
996 #XS(XS_${Full_func_name})
1000 print Q<<"EOF" if $ALIAS ;
1003 print Q<<"EOF" if $INTERFACE ;
1004 # dXSFUNCTION($ret_type);
1007 $cond = ($min_args ? qq(items < $min_args) : 0);
1009 elsif ($min_args == $num_args) {
1010 $cond = qq(items != $min_args);
1013 $cond = qq(items < $min_args || items > $num_args);
1016 print Q<<"EOF" if $except;
1017 # char errbuf[1024];
1022 { print Q<<"EOF" if $cond }
1024 # Perl_croak(aTHX_ "Usage: %s($orig_args)", GvNAME(CvGV(cv)));
1027 { print Q<<"EOF" if $cond }
1029 # Perl_croak(aTHX_ "Usage: $pname($orig_args)");
1032 print Q<<"EOF" if $PPCODE;
1036 # Now do a block of some sort.
1039 $cond = ''; # last CASE: condidional
1040 push(@line, "$END:");
1041 push(@line_no, $line_no[-1]);
1045 &CASE_handler if check_keyword("CASE");
1050 # do initialization of input variables
1058 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|PROTOTYPE|SCOPE") ;
1060 print Q<<"EOF" if $ScopeThisXSUB;
1065 if (!$thisdone && defined($class)) {
1066 if (defined($static) or $func_name eq 'new') {
1068 $var_types{"CLASS"} = "char *";
1069 &generate_init("char *", 1, "CLASS");
1073 $var_types{"THIS"} = "$class *";
1074 &generate_init("$class *", 1, "THIS");
1079 if (/^\s*NOT_IMPLEMENTED_YET/) {
1080 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1083 if ($ret_type ne "void") {
1084 print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
1086 $args_match{"RETVAL"} = 0;
1087 $var_types{"RETVAL"} = $ret_type;
1092 process_keyword("INIT|ALIAS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
1094 if (check_keyword("PPCODE")) {
1096 death ("PPCODE must be last thing") if @line;
1097 print "\tLEAVE;\n" if $ScopeThisXSUB;
1098 print "\tPUTBACK;\n\treturn;\n";
1099 } elsif (check_keyword("CODE")) {
1101 } elsif (defined($class) and $func_name eq "DESTROY") {
1103 print "delete THIS;\n";
1106 if ($ret_type ne "void") {
1110 if (defined($static)) {
1111 if ($func_name eq 'new') {
1112 $func_name = "$class";
1116 } elsif (defined($class)) {
1117 if ($func_name eq 'new') {
1118 $func_name .= " $class";
1123 $func_name =~ s/^($spat)//
1125 $func_name = 'XSFUNCTION' if $interface;
1126 print "$func_name($func_args);\n";
1130 # do output variables
1132 undef $RETVAL_code ;
1134 process_keyword("OUTPUT|ALIAS|PROTOTYPE");
1136 # all OUTPUT done, so now push the return value on the stack
1137 if ($gotRETVAL && $RETVAL_code) {
1138 print "\t$RETVAL_code\n";
1139 } elsif ($gotRETVAL || $wantRETVAL) {
1140 # RETVAL almost never needs SvSETMAGIC()
1141 &generate_output($ret_type, 0, 'RETVAL', 0);
1145 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
1147 print Q<<"EOF" if $ScopeThisXSUB;
1150 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1154 # print function trailer
1158 print Q<<EOF if $except;
1161 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1164 if (check_keyword("CASE")) {
1165 blurt ("Error: No `CASE:' at top of function")
1167 $_ = "CASE: $_"; # Restore CASE: label
1170 last if $_ eq "$END:";
1171 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1174 print Q<<EOF if $except;
1176 # Perl_croak(aTHX_ errbuf);
1179 if ($ret_type ne "void" or $EXPLICIT_RETURN) {
1180 print Q<<EOF unless $PPCODE;
1184 print Q<<EOF unless $PPCODE;
1194 my $newXS = "newXS" ;
1197 # Build the prototype string for the xsub
1198 if ($ProtoThisXSUB) {
1199 $newXS = "newXSproto";
1201 if ($ProtoThisXSUB eq 2) {
1202 # User has specified empty prototype
1205 elsif ($ProtoThisXSUB ne 1) {
1206 # User has specified a prototype
1207 $proto = ', "' . $ProtoThisXSUB . '"';
1211 if ($min_args < $num_args) {
1213 $proto_arg[$min_args] .= ";" ;
1215 push @proto_arg, "$s\@"
1218 $proto = ', "' . join ("", @proto_arg) . '"';
1223 $XsubAliases{$pname} = 0
1224 unless defined $XsubAliases{$pname} ;
1225 while ( ($name, $value) = each %XsubAliases) {
1226 push(@InitFileCode, Q<<"EOF");
1227 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1228 # XSANY.any_i32 = $value ;
1230 push(@InitFileCode, Q<<"EOF") if $proto;
1231 # sv_setpv((SV*)cv$proto) ;
1235 elsif ($interface) {
1236 while ( ($name, $value) = each %Interfaces) {
1237 $name = "$Package\::$name" unless $name =~ /::/;
1238 push(@InitFileCode, Q<<"EOF");
1239 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1240 # $interface_macro_set(cv,$value) ;
1242 push(@InitFileCode, Q<<"EOF") if $proto;
1243 # sv_setpv((SV*)cv$proto) ;
1249 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1253 # print initialization routine
1262 #XS(boot_$Module_cname)
1268 # char* file = __FILE__;
1272 print Q<<"EOF" if $WantVersionChk ;
1273 # XS_VERSION_BOOTCHECK ;
1277 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1283 print @InitFileCode;
1285 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1291 print "\n /* Initialisation Section */\n\n" ;
1294 print "\n /* End of Initialisation Section */\n\n" ;
1303 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1308 local($type, $num, $var, $init) = @_;
1309 local($arg) = "ST(" . ($num - 1) . ")";
1311 if( $init =~ /^=/ ) {
1312 eval qq/print "\\t$var $init\\n"/;
1315 if( $init =~ s/^\+// && $num ) {
1316 &generate_init($type, $num, $var);
1318 eval qq/print "\\t$var;\\n"/;
1322 $deferred .= eval qq/"\\n\\t$init\\n"/;
1329 # work out the line number
1330 my $line_no = $line_no[@line_no - @line -1] ;
1332 print STDERR "@_ in $filename, line $line_no\n" ;
1348 local($type, $num, $var) = @_;
1349 local($arg) = "ST(" . ($num - 1) . ")";
1350 local($argoff) = $num - 1;
1354 $type = TidyType($type) ;
1355 blurt("Error: '$type' not in typemap"), return
1356 unless defined($type_kind{$type});
1358 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1359 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1360 $tk = $type_kind{$type};
1361 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1363 blurt("Error: No INPUT definition for type '$type' found"), return
1364 unless defined $input_expr{$tk} ;
1365 $expr = $input_expr{$tk};
1366 if ($expr =~ /DO_ARRAY_ELEM/) {
1367 blurt("Error: '$subtype' not in typemap"), return
1368 unless defined($type_kind{$subtype});
1369 blurt("Error: No INPUT definition for type '$subtype' found"), return
1370 unless defined $input_expr{$type_kind{$subtype}} ;
1371 $subexpr = $input_expr{$type_kind{$subtype}};
1372 $subexpr =~ s/ntype/subtype/g;
1373 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1374 $subexpr =~ s/\n\t/\n\t\t/g;
1375 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1376 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1377 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1379 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1382 if (defined($defaults{$var})) {
1383 $expr =~ s/(\t+)/$1 /g;
1385 eval qq/print "\\t$var;\\n"/;
1387 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1389 } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1390 eval qq/print "\\t$var;\\n"/;
1392 $deferred .= eval qq/"\\n$expr;\\n"/;
1395 eval qq/print "$expr;\\n"/;
1400 sub generate_output {
1401 local($type, $num, $var, $do_setmagic) = @_;
1402 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1403 local($argoff) = $num - 1;
1406 $type = TidyType($type) ;
1407 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1408 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
1409 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1411 blurt("Error: '$type' not in typemap"), return
1412 unless defined($type_kind{$type});
1413 blurt("Error: No OUTPUT definition for type '$type' found"), return
1414 unless defined $output_expr{$type_kind{$type}} ;
1415 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1416 $ntype =~ s/\(\)//g;
1417 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1418 $expr = $output_expr{$type_kind{$type}};
1419 if ($expr =~ /DO_ARRAY_ELEM/) {
1420 blurt("Error: '$subtype' not in typemap"), return
1421 unless defined($type_kind{$subtype});
1422 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1423 unless defined $output_expr{$type_kind{$subtype}} ;
1424 $subexpr = $output_expr{$type_kind{$subtype}};
1425 $subexpr =~ s/ntype/subtype/g;
1426 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1427 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1428 $subexpr =~ s/\n\t/\n\t\t/g;
1429 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1430 eval "print qq\a$expr\a";
1432 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1434 elsif ($var eq 'RETVAL') {
1435 if ($expr =~ /^\t\$arg = new/) {
1436 # We expect that $arg has refcnt 1, so we need to
1438 eval "print qq\a$expr\a";
1440 print "\tsv_2mortal(ST(0));\n";
1441 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1443 elsif ($expr =~ /^\s*\$arg\s*=/) {
1444 # We expect that $arg has refcnt >=1, so we need
1446 eval "print qq\a$expr\a";
1448 print "\tsv_2mortal(ST(0));\n";
1449 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1452 # Just hope that the entry would safely write it
1453 # over an already mortalized value. By
1454 # coincidence, something like $arg = &sv_undef
1456 print "\tST(0) = sv_newmortal();\n";
1457 eval "print qq\a$expr\a";
1459 # new mortals don't have set magic
1462 elsif ($arg =~ /^ST\(\d+\)$/) {
1463 eval "print qq\a$expr\a";
1465 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1474 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1480 # If this is VMS, the exit status has meaning to the shell, so we
1481 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1483 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1484 exit ($errors ? 1 : 0);