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<-nooptimize>] [B<-typemap typemap>] ... file.xs
13 This compiler is typically run by the makefiles created by L<ExtUtils::MakeMaker>.
15 I<xsubpp> will compile XS code into C code by embedding the constructs
16 necessary to let C functions manipulate Perl values and creates the glue
17 necessary to let Perl access those functions. The compiler uses typemaps to
18 determine how to map C function parameters and variables to Perl values.
20 The compiler will search for typemap files called I<typemap>. It will use
21 the following search path to find default typemaps, with the rightmost
22 typemap taking precedence.
24 ../../../typemap:../../typemap:../typemap:typemap
28 Note that the C<XSOPT> MakeMaker option may be used to add these options to
29 any makefiles generated by MakeMaker.
35 Adds ``extern "C"'' to the C code.
39 Adds exception handling stubs to the C code.
41 =item B<-typemap typemap>
43 Indicates that a user-supplied typemap should take precedence over the
44 default typemaps. This option may be used multiple times, with the last
45 typemap having the highest precedence.
49 Prints the I<xsubpp> version number to standard output, then exits.
53 By default I<xsubpp> will not automatically generate prototype code for
54 all xsubs. This flag will enable prototypes.
56 =item B<-noversioncheck>
58 Disables the run time test that determines if the object file (derived
59 from the C<.xs> file) and the C<.pm> files have the same version
62 =item B<-nolinenumbers>
64 Prevents the inclusion of `#line' directives in the output.
68 Disables certain optimizations. The only optimization that is currently
69 affected is the use of I<target>s by the output C code (see L<perlguts>).
70 This may significantly slow down the generated code, but this is the way
71 B<xsubpp> of 5.005 and earlier operated.
77 No environment variables are used.
83 =head1 MODIFICATION HISTORY
85 See the file F<changes.pod>.
89 perl(1), perlxs(1), perlxstut(1)
95 use vars '$cplusplus';
104 $XSUBPP_version = "1.9507";
106 my ($Is_VMS, $SymSet);
109 # Establish set of global symbols with max length 28, since xsubpp
110 # will later add the 'XS_' prefix.
111 require ExtUtils::XSSymSet;
112 $SymSet = new ExtUtils::XSSymSet 28;
117 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-s pattern] [-typemap typemap]... file.xs\n";
119 $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
121 $OBJ = 1 if $Config{'ccflags'} =~ /PERL_OBJECT/i;
124 $WantPrototypes = -1 ;
125 $WantVersionChk = 1 ;
127 $WantLineNumbers = 1 ;
129 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
132 $spat = quotemeta shift, next SWITCH if $flag eq 's';
133 $cplusplus = 1, next SWITCH if $flag eq 'C++';
134 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
135 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
136 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
137 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
138 # XXX left this in for compat
139 $WantCAPI = 1, next SWITCH if $flag eq 'object_capi';
140 $except = " TRY", next SWITCH if $flag eq 'except';
141 push(@tm,shift), next SWITCH if $flag eq 'typemap';
142 $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
143 $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
144 $WantOptimize = 0, next SWITCH if $flag eq 'nooptimize';
145 $WantOptimize = 1, next SWITCH if $flag eq 'optimize';
146 (print "xsubpp version $XSUBPP_version\n"), exit
150 if ($WantPrototypes == -1)
151 { $WantPrototypes = 0}
156 @ARGV == 1 or die $usage;
157 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
158 or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
159 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
160 or ($dir, $filename) = ('.', $ARGV[0]);
164 ++ $IncludedFiles{$ARGV[0]} ;
166 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
167 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
172 $_[0] =~ s/^\s+|\s+$//go ;
179 # rationalise any '*' by joining them into bunches and removing whitespace
183 # change multiple whitespace into a single space
186 # trim leading & trailing whitespace
192 $typemap = shift @ARGV;
193 foreach $typemap (@tm) {
194 die "Can't find $typemap in $pwd\n" unless -r $typemap;
196 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
197 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
199 foreach $typemap (@tm) {
200 next unless -e $typemap ;
201 # skip directories, binary files etc.
202 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
204 open(TYPEMAP, $typemap)
205 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
211 my $line_no = $. + 1;
212 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
213 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
214 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
215 if ($mode eq 'Typemap') {
219 # skip blank lines and comment lines
220 next if /^$/ or /^#/ ;
221 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
222 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
223 $type = TidyType($type) ;
224 $type_kind{$type} = $kind ;
225 # prototype defaults to '$'
226 $proto = "\$" unless $proto ;
227 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
228 unless ValidProtoString($proto) ;
229 $proto_letter{$type} = C_string($proto) ;
234 elsif ($mode eq 'Input') {
236 $input_expr{$_} = '';
237 $current = \$input_expr{$_};
241 $output_expr{$_} = '';
242 $current = \$output_expr{$_};
248 foreach $key (keys %input_expr) {
249 $input_expr{$key} =~ s/\n+$//;
252 $bal = qr[(?:(?>[^()]+)|\((?p{ $bal })\))*]; # ()-balanced
253 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
254 $size = qr[,\s* (?p{ $bal }) ]x; # Third arg (to setpvn)
256 foreach $key (keys %output_expr) {
259 my ($t, $with_size, $arg, $sarg) =
260 ($output_expr{$key} =~
261 m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
262 \s* \( \s* $cast \$arg \s* ,
263 \s* ( (?p{ $bal }) ) # Set from
264 ( (?p{ $size }) )? # Possible sizeof set-from
267 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
270 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
272 # Match an XS keyword
273 $BLOCK_re= '\s*(' . join('|', qw(
274 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
275 CLEANUP ALIAS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
276 SCOPE INTERFACE INTERFACE_MACRO C_ARGS
279 # Input: ($_, @line) == unparsed input.
280 # Output: ($_, @line) == (rest of line, following lines).
281 # Return: the matched keyword if found, otherwise 0
283 $_ = shift(@line) while !/\S/ && @line;
284 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
288 if ($WantLineNumbers) {
290 package xsubpp::counter;
292 my ($class, $cfile) = @_;
294 $SECTION_END_MARKER = "#line --- \"$cfile\"";
303 while ($$self =~ s/^([^\n]*\n)//) {
306 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
315 $self->PRINT(sprintf($fmt, @_));
319 # Not necessary if we're careful to end with a "\n"
325 my $cfile = $filename;
326 $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
327 tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
328 select PSEUDO_STDOUT;
332 # the "do" is required for right semantics
333 do { $_ = shift(@line) } while !/\S/ && @line;
335 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
336 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
337 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
340 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
346 while (!/\S/ && @line) {
350 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
357 sub process_keyword($)
362 &{"${kwd}_handler"}()
363 while $kwd = check_keyword($pattern) ;
367 blurt ("Error: `CASE:' after unconditional `CASE:'")
368 if $condnum && $cond eq '';
370 TrimWhitespace($cond);
371 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
376 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
377 last if /^\s*NOT_IMPLEMENTED_YET/;
378 next unless /\S/; # skip blank lines
383 # remove trailing semicolon if no initialisation
384 s/\s*;$//g unless /[=;+].*\S/ ;
386 # check for optional initialisation code
388 $var_init = $1 if s/\s*([=;+].*)$//s ;
389 $var_init =~ s/"/\\"/g;
392 my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
393 or blurt("Error: invalid argument declaration '$line'"), next;
395 # Check for duplicate definitions
396 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
397 if $arg_list{$var_name} ++ ;
399 $thisdone |= $var_name eq "THIS";
400 $retvaldone |= $var_name eq "RETVAL";
401 $var_types{$var_name} = $var_type;
402 # XXXX This check is a safeguard against the unfinished conversion of
403 # generate_init(). When generate_init() is fixed,
404 # one can use 2-args map_type() unconditionally.
405 if ($var_type =~ / \( \s* \* \s* \) /x) {
406 # Function pointers are not yet supported with &output_init!
407 print "\t" . &map_type($var_type, $var_name);
410 print "\t" . &map_type($var_type);
413 $var_num = $args_match{$var_name};
415 $proto_arg[$var_num] = ProtoString($var_type)
418 $var_addr{$var_name} = 1;
419 $func_args =~ s/\b($var_name)\b/&$1/;
421 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/) {
425 print "\t$var_name;\n";
427 } elsif ($var_init =~ /\S/) {
428 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
430 # generate initialization code
431 &generate_init($var_type, $var_num, $var_name, $name_printed);
439 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
441 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
442 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
445 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
446 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
447 if $outargs{$outarg} ++ ;
448 if (!$gotRETVAL and $outarg eq 'RETVAL') {
449 # deal with RETVAL last
450 $RETVAL_code = $outcode ;
454 blurt ("Error: OUTPUT $outarg not an argument"), next
455 unless defined($args_match{$outarg});
456 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
457 unless defined $var_types{$outarg} ;
458 $var_num = $args_match{$outarg};
460 print "\t$outcode\n";
461 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
463 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
468 sub C_ARGS_handler() {
469 my $in = merge_section();
475 sub INTERFACE_MACRO_handler() {
476 my $in = merge_section();
479 if ($in =~ /\s/) { # two
480 ($interface_macro, $interface_macro_set) = split ' ', $in;
482 $interface_macro = $in;
483 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
485 $interface = 1; # local
486 $Interfaces = 1; # global
489 sub INTERFACE_handler() {
490 my $in = merge_section();
494 foreach (split /[\s,]+/, $in) {
495 $Interfaces{$_} = $_;
498 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
500 $interface = 1; # local
501 $Interfaces = 1; # global
504 sub CLEANUP_handler() { print_section() }
505 sub PREINIT_handler() { print_section() }
506 sub INIT_handler() { print_section() }
515 # Parse alias definitions
517 # alias = value alias = value ...
519 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
521 $orig_alias = $alias ;
524 # check for optional package definition in the alias
525 $alias = $Packprefix . $alias if $alias !~ /::/ ;
527 # check for duplicate alias name & duplicate value
528 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
529 if defined $XsubAliases{$alias} ;
531 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
532 if $XsubAliasValues{$value} ;
535 $XsubAliases{$alias} = $value ;
536 $XsubAliasValues{$value} = $orig_alias ;
539 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
545 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
548 GetAliases($_) if $_ ;
552 sub REQUIRE_handler ()
554 # the rest of the current line should contain a version number
557 TrimWhitespace($Ver) ;
559 death ("Error: REQUIRE expects a version number")
562 # check that the version number is of the form n.n
563 death ("Error: REQUIRE: expected a number, got '$Ver'")
564 unless $Ver =~ /^\d+(\.\d*)?/ ;
566 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
567 unless $XSUBPP_version >= $Ver ;
570 sub VERSIONCHECK_handler ()
572 # the rest of the current line should contain either ENABLE or
577 # check for ENABLE/DISABLE
578 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
579 unless /^(ENABLE|DISABLE)/i ;
581 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
582 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
586 sub PROTOTYPE_handler ()
590 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
591 if $proto_in_this_xsub ++ ;
593 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
597 if ($_ eq 'DISABLE') {
600 elsif ($_ eq 'ENABLE') {
604 # remove any whitespace
606 death("Error: Invalid prototype '$_'")
607 unless ValidProtoString($_) ;
608 $ProtoThisXSUB = C_string($_) ;
612 # If no prototype specified, then assume empty prototype ""
613 $ProtoThisXSUB = 2 unless $specified ;
621 death("Error: Only 1 SCOPE declaration allowed per xsub")
622 if $scope_in_this_xsub ++ ;
624 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
627 if ($_ =~ /^DISABLE/i) {
630 elsif ($_ =~ /^ENABLE/i) {
637 sub PROTOTYPES_handler ()
639 # the rest of the current line should contain either ENABLE or
644 # check for ENABLE/DISABLE
645 death ("Error: PROTOTYPES: ENABLE/DISABLE")
646 unless /^(ENABLE|DISABLE)/i ;
648 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
649 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
654 sub INCLUDE_handler ()
656 # the rest of the current line should contain a valid filename
660 death("INCLUDE: filename missing")
663 death("INCLUDE: output pipe is illegal")
666 # simple minded recursion detector
667 death("INCLUDE loop detected")
668 if $IncludedFiles{$_} ;
670 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
672 # Save the current file context.
675 LastLine => $lastline,
676 LastLineNo => $lastline_no,
679 Filename => $filename,
686 open ($FH, "$_") or death("Cannot open '$_': $!") ;
690 #/* INCLUDE: Including '$_' from '$filename' */
696 # Prime the pump by reading the first
699 # skip leading blank lines
701 last unless /^\s*$/ ;
711 return 0 unless $XSStack[-1]{type} eq 'file' ;
713 my $data = pop @XSStack ;
714 my $ThisFile = $filename ;
715 my $isPipe = ($filename =~ /\|\s*$/) ;
717 -- $IncludedFiles{$filename}
722 $FH = $data->{Handle} ;
723 $filename = $data->{Filename} ;
724 $lastline = $data->{LastLine} ;
725 $lastline_no = $data->{LastLineNo} ;
726 @line = @{ $data->{Line} } ;
727 @line_no = @{ $data->{LineNo} } ;
729 if ($isPipe and $? ) {
731 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
737 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
744 sub ValidProtoString ($)
748 if ( $string =~ /^$proto_re+$/ ) {
759 $string =~ s[\\][\\\\]g ;
767 $proto_letter{$type} or "\$" ;
771 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
773 my ($cpp, $cpplevel);
775 if ($cpp =~ /^\#\s*if/) {
777 } elsif (!$cpplevel) {
778 Warn("Warning: #else/elif/endif without #if in this function");
779 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
780 if $XSStack[-1]{type} eq 'if';
782 } elsif ($cpp =~ /^\#\s*endif/) {
786 Warn("Warning: #if without #endif in this function") if $cpplevel;
799 open($FH, $filename) or die "cannot open $filename: $!\n";
801 # Identify the version of xsubpp used
804 * This file was generated automatically by xsubpp version $XSUBPP_version from the
805 * contents of $filename. Do not edit this file, edit $filename instead.
807 * ANY CHANGES MADE HERE WILL BE LOST!
814 print("#line 1 \"$filename\"\n")
818 last if ($Module, $Package, $Prefix) =
819 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
822 s/#if(?:def\s|\s+defined)\s*(\(__cplusplus\)|__cplusplus)/#if defined(__cplusplus) && !defined(PERL_OBJECT)/;
826 &Exit unless defined $_;
828 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
833 # Read next xsub into @line from ($lastline, <$FH>).
836 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
837 if !defined $lastline && $XSStack[-1]{type} eq 'if';
840 return PopFile() if !defined $lastline;
843 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
845 $Package = defined($2) ? $2 : ''; # keep -w happy
846 $Prefix = defined($3) ? $3 : ''; # keep -w happy
847 $Prefix = quotemeta $Prefix ;
848 ($Module_cname = $Module) =~ s/\W/_/g;
849 ($Packid = $Package) =~ tr/:/_/;
850 $Packprefix = $Package;
851 $Packprefix .= "::" if $Packprefix ne "";
856 if ($lastline !~ /^\s*#/ ||
858 # ANSI: if ifdef ifndef elif else endif define undef
860 # gcc: warning include_next
862 # others: ident (gcc notes that some cpps have this one)
863 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
864 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
865 push(@line, $lastline);
866 push(@line_no, $lastline_no) ;
869 # Read next line and continuation lines
870 last unless defined($lastline = <$FH>);
873 $lastline .= $tmp_line
874 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
877 $lastline =~ s/^\s+$//;
879 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
884 while (fetch_para()) {
885 # Print initial preprocessor statements and blank lines
886 while (@line && $line[0] !~ /^[^\#]/) {
887 my $line = shift(@line);
889 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
891 if ($statement eq 'if') {
892 $XSS_work_idx = @XSStack;
893 push(@XSStack, {type => 'if'});
895 death ("Error: `$statement' with no matching `if'")
896 if $XSStack[-1]{type} ne 'if';
897 if ($XSStack[-1]{varname}) {
898 push(@InitFileCode, "#endif\n");
899 push(@BootCode, "#endif");
902 my(@fns) = keys %{$XSStack[-1]{functions}};
903 if ($statement ne 'endif') {
904 # Hide the functions defined in other #if branches, and reset.
905 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
906 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
908 my($tmp) = pop(@XSStack);
909 0 while (--$XSS_work_idx
910 && $XSStack[$XSS_work_idx]{type} ne 'if');
911 # Keep all new defined functions
912 push(@fns, keys %{$tmp->{other_functions}});
913 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
918 next PARAGRAPH unless @line;
920 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
921 # We are inside an #if, but have not yet #defined its xsubpp variable.
922 print "#define $cpp_next_tmp 1\n\n";
923 push(@InitFileCode, "#if $cpp_next_tmp\n");
924 push(@BootCode, "#if $cpp_next_tmp");
925 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
928 death ("Code is not inside a function"
929 ." (maybe last function was ended by a blank line "
930 ." followed by a a statement on column one?)")
931 if $line[0] =~ /^\s/;
933 # initialize info arrays
944 undef($proto_in_this_xsub) ;
945 undef($scope_in_this_xsub) ;
947 $interface_macro = 'XSINTERFACE_FUNC' ;
948 $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
949 $ProtoThisXSUB = $WantPrototypes ;
953 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
954 &{"${kwd}_handler"}() ;
955 next PARAGRAPH unless @line ;
959 if (check_keyword("BOOT")) {
961 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
962 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
963 push (@BootCode, @line, "") ;
968 # extract return type, function name and arguments
969 ($ret_type) = TidyType($_);
971 # a function definition needs at least 2 lines
972 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
975 $static = 1 if $ret_type =~ s/^static\s+//;
977 $func_header = shift(@line);
978 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
979 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*$/s;
981 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
982 $class = "$4 $class" if $4;
983 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
984 ($clean_func_name = $func_name) =~ s/^$Prefix//;
985 $Full_func_name = "${Packid}_$clean_func_name";
986 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
988 # Check for duplicate function definition
989 for $tmp (@XSStack) {
990 next unless defined $tmp->{functions}{$Full_func_name};
991 Warn("Warning: duplicate function definition '$clean_func_name' detected");
994 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
995 %XsubAliases = %XsubAliasValues = %Interfaces = ();
998 my $temp_args = $orig_args;
999 $temp_args =~ s/\\\s*//g;
1000 @args = split(/\s*,\s*/, $temp_args);
1001 if (defined($class)) {
1002 my $arg0 = ((defined($static) or $func_name eq 'new')
1003 ? "CLASS" : "THIS");
1004 unshift(@args, $arg0);
1005 ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
1007 $orig_args =~ s/"/\\"/g;
1008 $min_args = $num_args = @args;
1009 foreach $i (0..$num_args-1) {
1010 if ($args[$i] =~ s/\.\.\.//) {
1013 if ($args[$i] eq '' && $i == $num_args - 1) {
1018 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
1021 $defaults{$args[$i]} = $2;
1022 $defaults{$args[$i]} =~ s/"/\\"/g;
1024 $proto_arg[$i+1] = "\$" ;
1026 if (defined($class)) {
1027 $func_args = join(", ", @args[1..$#args]);
1029 $func_args = join(", ", @args);
1031 @args_match{@args} = 1..@args;
1033 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
1034 $CODE = grep(/^\s*CODE\s*:/, @line);
1035 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
1036 # to set explicit return values.
1037 $EXPLICIT_RETURN = ($CODE &&
1038 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
1039 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
1040 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
1042 # print function header
1044 #XS(XS_${Full_func_name})
1048 print Q<<"EOF" if $ALIAS ;
1051 print Q<<"EOF" if $INTERFACE ;
1052 # dXSFUNCTION($ret_type);
1055 $cond = ($min_args ? qq(items < $min_args) : 0);
1057 elsif ($min_args == $num_args) {
1058 $cond = qq(items != $min_args);
1061 $cond = qq(items < $min_args || items > $num_args);
1064 print Q<<"EOF" if $except;
1065 # char errbuf[1024];
1070 { print Q<<"EOF" if $cond }
1072 # Perl_croak(aTHX_ "Usage: %s($orig_args)", GvNAME(CvGV(cv)));
1075 { print Q<<"EOF" if $cond }
1077 # Perl_croak(aTHX_ "Usage: $pname($orig_args)");
1080 print Q<<"EOF" if $PPCODE;
1084 # Now do a block of some sort.
1087 $cond = ''; # last CASE: condidional
1088 push(@line, "$END:");
1089 push(@line_no, $line_no[-1]);
1093 &CASE_handler if check_keyword("CASE");
1098 # do initialization of input variables
1106 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|PROTOTYPE|SCOPE") ;
1108 print Q<<"EOF" if $ScopeThisXSUB;
1113 if (!$thisdone && defined($class)) {
1114 if (defined($static) or $func_name eq 'new') {
1116 $var_types{"CLASS"} = "char *";
1117 &generate_init("char *", 1, "CLASS");
1121 $var_types{"THIS"} = "$class *";
1122 &generate_init("$class *", 1, "THIS");
1127 if (/^\s*NOT_IMPLEMENTED_YET/) {
1128 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1131 if ($ret_type ne "void") {
1132 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
1134 $args_match{"RETVAL"} = 0;
1135 $var_types{"RETVAL"} = $ret_type;
1136 print "\tdXSTARG;\n"
1137 if $WantOptimize and $targetable{$type_kind{$ret_type}};
1142 process_keyword("INIT|ALIAS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
1144 if (check_keyword("PPCODE")) {
1146 death ("PPCODE must be last thing") if @line;
1147 print "\tLEAVE;\n" if $ScopeThisXSUB;
1148 print "\tPUTBACK;\n\treturn;\n";
1149 } elsif (check_keyword("CODE")) {
1151 } elsif (defined($class) and $func_name eq "DESTROY") {
1153 print "delete THIS;\n";
1156 if ($ret_type ne "void") {
1160 if (defined($static)) {
1161 if ($func_name eq 'new') {
1162 $func_name = "$class";
1166 } elsif (defined($class)) {
1167 if ($func_name eq 'new') {
1168 $func_name .= " $class";
1173 $func_name =~ s/^($spat)//
1175 $func_name = 'XSFUNCTION' if $interface;
1176 print "$func_name($func_args);\n";
1180 # do output variables
1182 undef $RETVAL_code ;
1184 process_keyword("OUTPUT|ALIAS|PROTOTYPE");
1186 # all OUTPUT done, so now push the return value on the stack
1187 if ($gotRETVAL && $RETVAL_code) {
1188 print "\t$RETVAL_code\n";
1189 } elsif ($gotRETVAL || $wantRETVAL) {
1190 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
1192 my $type = $ret_type;
1194 # 0: type, 1: with_size, 2: how, 3: how_size
1195 if ($t and not $t->[1] and $t->[0] eq 'p') {
1196 # PUSHp corresponds to setpvn. Treate setpv directly
1197 my $what = eval qq("$t->[2]");
1200 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
1203 my $what = eval qq("$t->[2]");
1207 $size = '' unless defined $size;
1208 $size = eval qq("$size");
1210 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
1213 # RETVAL almost never needs SvSETMAGIC()
1214 &generate_output($ret_type, 0, 'RETVAL', 0);
1219 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
1221 print Q<<"EOF" if $ScopeThisXSUB;
1224 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1228 # print function trailer
1232 print Q<<EOF if $except;
1235 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1238 if (check_keyword("CASE")) {
1239 blurt ("Error: No `CASE:' at top of function")
1241 $_ = "CASE: $_"; # Restore CASE: label
1244 last if $_ eq "$END:";
1245 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1248 print Q<<EOF if $except;
1250 # Perl_croak(aTHX_ errbuf);
1253 if ($ret_type ne "void" or $EXPLICIT_RETURN) {
1254 print Q<<EOF unless $PPCODE;
1258 print Q<<EOF unless $PPCODE;
1268 my $newXS = "newXS" ;
1271 # Build the prototype string for the xsub
1272 if ($ProtoThisXSUB) {
1273 $newXS = "newXSproto";
1275 if ($ProtoThisXSUB eq 2) {
1276 # User has specified empty prototype
1279 elsif ($ProtoThisXSUB ne 1) {
1280 # User has specified a prototype
1281 $proto = ', "' . $ProtoThisXSUB . '"';
1285 if ($min_args < $num_args) {
1287 $proto_arg[$min_args] .= ";" ;
1289 push @proto_arg, "$s\@"
1292 $proto = ', "' . join ("", @proto_arg) . '"';
1297 $XsubAliases{$pname} = 0
1298 unless defined $XsubAliases{$pname} ;
1299 while ( ($name, $value) = each %XsubAliases) {
1300 push(@InitFileCode, Q<<"EOF");
1301 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1302 # XSANY.any_i32 = $value ;
1304 push(@InitFileCode, Q<<"EOF") if $proto;
1305 # sv_setpv((SV*)cv$proto) ;
1309 elsif ($interface) {
1310 while ( ($name, $value) = each %Interfaces) {
1311 $name = "$Package\::$name" unless $name =~ /::/;
1312 push(@InitFileCode, Q<<"EOF");
1313 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1314 # $interface_macro_set(cv,$value) ;
1316 push(@InitFileCode, Q<<"EOF") if $proto;
1317 # sv_setpv((SV*)cv$proto) ;
1323 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1327 # print initialization routine
1336 #XS(boot_$Module_cname)
1342 # char* file = __FILE__;
1346 print Q<<"EOF" if $WantVersionChk ;
1347 # XS_VERSION_BOOTCHECK ;
1351 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1357 print @InitFileCode;
1359 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1365 print "\n /* Initialisation Section */\n\n" ;
1368 print "\n /* End of Initialisation Section */\n\n" ;
1377 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1382 local($type, $num, $var, $init, $name_printed) = @_;
1383 local($arg) = "ST(" . ($num - 1) . ")";
1385 if( $init =~ /^=/ ) {
1386 if ($name_printed) {
1387 eval qq/print " $init\\n"/;
1389 eval qq/print "\\t$var $init\\n"/;
1393 if( $init =~ s/^\+// && $num ) {
1394 &generate_init($type, $num, $var, $name_printed);
1395 } elsif ($name_printed) {
1399 eval qq/print "\\t$var;\\n"/;
1403 $deferred .= eval qq/"\\n\\t$init\\n"/;
1410 # work out the line number
1411 my $line_no = $line_no[@line_no - @line -1] ;
1413 print STDERR "@_ in $filename, line $line_no\n" ;
1429 local($type, $num, $var) = @_;
1430 local($arg) = "ST(" . ($num - 1) . ")";
1431 local($argoff) = $num - 1;
1435 $type = TidyType($type) ;
1436 blurt("Error: '$type' not in typemap"), return
1437 unless defined($type_kind{$type});
1439 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1440 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1441 $tk = $type_kind{$type};
1442 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1444 blurt("Error: No INPUT definition for type '$type' found"), return
1445 unless defined $input_expr{$tk} ;
1446 $expr = $input_expr{$tk};
1447 if ($expr =~ /DO_ARRAY_ELEM/) {
1448 blurt("Error: '$subtype' not in typemap"), return
1449 unless defined($type_kind{$subtype});
1450 blurt("Error: No INPUT definition for type '$subtype' found"), return
1451 unless defined $input_expr{$type_kind{$subtype}} ;
1452 $subexpr = $input_expr{$type_kind{$subtype}};
1453 $subexpr =~ s/ntype/subtype/g;
1454 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1455 $subexpr =~ s/\n\t/\n\t\t/g;
1456 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1457 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1458 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1460 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1463 if (defined($defaults{$var})) {
1464 $expr =~ s/(\t+)/$1 /g;
1466 if ($name_printed) {
1469 eval qq/print "\\t$var;\\n"/;
1472 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1474 } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1475 if ($name_printed) {
1478 eval qq/print "\\t$var;\\n"/;
1481 $deferred .= eval qq/"\\n$expr;\\n"/;
1484 die "panic: do not know how to handle this branch for function pointers"
1486 eval qq/print "$expr;\\n"/;
1491 sub generate_output {
1492 local($type, $num, $var, $do_setmagic) = @_;
1493 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1494 local($argoff) = $num - 1;
1497 $type = TidyType($type) ;
1498 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1499 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1500 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1502 blurt("Error: '$type' not in typemap"), return
1503 unless defined($type_kind{$type});
1504 blurt("Error: No OUTPUT definition for type '$type' found"), return
1505 unless defined $output_expr{$type_kind{$type}} ;
1506 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1507 $ntype =~ s/\(\)//g;
1508 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1509 $expr = $output_expr{$type_kind{$type}};
1510 if ($expr =~ /DO_ARRAY_ELEM/) {
1511 blurt("Error: '$subtype' not in typemap"), return
1512 unless defined($type_kind{$subtype});
1513 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1514 unless defined $output_expr{$type_kind{$subtype}} ;
1515 $subexpr = $output_expr{$type_kind{$subtype}};
1516 $subexpr =~ s/ntype/subtype/g;
1517 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1518 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1519 $subexpr =~ s/\n\t/\n\t\t/g;
1520 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1521 eval "print qq\a$expr\a";
1523 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1525 elsif ($var eq 'RETVAL') {
1526 if ($expr =~ /^\t\$arg = new/) {
1527 # We expect that $arg has refcnt 1, so we need to
1529 eval "print qq\a$expr\a";
1531 print "\tsv_2mortal(ST(0));\n";
1532 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1534 elsif ($expr =~ /^\s*\$arg\s*=/) {
1535 # We expect that $arg has refcnt >=1, so we need
1537 eval "print qq\a$expr\a";
1539 print "\tsv_2mortal(ST(0));\n";
1540 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1543 # Just hope that the entry would safely write it
1544 # over an already mortalized value. By
1545 # coincidence, something like $arg = &sv_undef
1547 print "\tST(0) = sv_newmortal();\n";
1548 eval "print qq\a$expr\a";
1550 # new mortals don't have set magic
1553 elsif ($arg =~ /^ST\(\d+\)$/) {
1554 eval "print qq\a$expr\a";
1556 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1562 my($type, $varname) = @_;
1565 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1567 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1568 (substr $type, pos $type, 0) = " $varname ";
1570 $type .= "\t$varname";
1578 # If this is VMS, the exit status has meaning to the shell, so we
1579 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1581 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1582 exit ($errors ? 1 : 0);