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[(?:(?>[^()]+)|\((??{ $bal })\))*]; # ()-balanced
253 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
254 $size = qr[,\s* (??{ $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* ( (??{ $bal }) ) # Set from
264 ( (??{ $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 POSTCALL
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;
287 my ($C_group_rex, $C_arg);
288 # Group in C (no support for comments or literals)
289 $C_group_rex = qr/ [({\[]
290 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
292 # Chunk in C without comma at toplevel (no comments):
293 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
294 | (??{ $C_group_rex })
295 | " (?: (?> [^\\"]+ )
297 )* " # String literal
298 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
301 if ($WantLineNumbers) {
303 package xsubpp::counter;
305 my ($class, $cfile) = @_;
307 $SECTION_END_MARKER = "#line --- \"$cfile\"";
316 while ($$self =~ s/^([^\n]*\n)//) {
319 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
328 $self->PRINT(sprintf($fmt, @_));
332 # Not necessary if we're careful to end with a "\n"
338 my $cfile = $filename;
339 $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
340 tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
341 select PSEUDO_STDOUT;
345 # the "do" is required for right semantics
346 do { $_ = shift(@line) } while !/\S/ && @line;
348 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
349 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
350 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
353 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
359 while (!/\S/ && @line) {
363 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
370 sub process_keyword($)
375 &{"${kwd}_handler"}()
376 while $kwd = check_keyword($pattern) ;
380 blurt ("Error: `CASE:' after unconditional `CASE:'")
381 if $condnum && $cond eq '';
383 TrimWhitespace($cond);
384 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
388 my $process_inout = 1;
389 my $process_argtypes = 1;
392 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
393 last if /^\s*NOT_IMPLEMENTED_YET/;
394 next unless /\S/; # skip blank lines
399 # remove trailing semicolon if no initialisation
400 s/\s*;$//g unless /[=;+].*\S/ ;
402 # check for optional initialisation code
404 $var_init = $1 if s/\s*([=;+].*)$//s ;
405 $var_init =~ s/"/\\"/g;
408 my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
409 or blurt("Error: invalid argument declaration '$line'"), next;
411 # Check for duplicate definitions
412 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
413 if $arg_list{$var_name}++
414 or defined $arg_types{$var_name} and not $processing_arg_with_types;
416 $thisdone |= $var_name eq "THIS";
417 $retvaldone |= $var_name eq "RETVAL";
418 $var_types{$var_name} = $var_type;
419 # XXXX This check is a safeguard against the unfinished conversion of
420 # generate_init(). When generate_init() is fixed,
421 # one can use 2-args map_type() unconditionally.
422 if ($var_type =~ / \( \s* \* \s* \) /x) {
423 # Function pointers are not yet supported with &output_init!
424 print "\t" . &map_type($var_type, $var_name);
427 print "\t" . &map_type($var_type);
430 $var_num = $args_match{$var_name};
432 $proto_arg[$var_num] = ProtoString($var_type)
435 $var_addr{$var_name} = 1;
436 $func_args =~ s/\b($var_name)\b/&$1/;
438 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
439 or $in_out{$var_name} and $in_out{$var_name} eq 'OUTLIST'
440 and $var_init !~ /\S/) {
444 print "\t$var_name;\n";
446 } elsif ($var_init =~ /\S/) {
447 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
449 # generate initialization code
450 &generate_init($var_type, $var_num, $var_name, $name_printed);
458 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
460 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
461 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
464 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
465 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
466 if $outargs{$outarg} ++ ;
467 if (!$gotRETVAL and $outarg eq 'RETVAL') {
468 # deal with RETVAL last
469 $RETVAL_code = $outcode ;
473 blurt ("Error: OUTPUT $outarg not an argument"), next
474 unless defined($args_match{$outarg});
475 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
476 unless defined $var_types{$outarg} ;
477 $var_num = $args_match{$outarg};
479 print "\t$outcode\n";
480 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
482 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
487 sub C_ARGS_handler() {
488 my $in = merge_section();
494 sub INTERFACE_MACRO_handler() {
495 my $in = merge_section();
498 if ($in =~ /\s/) { # two
499 ($interface_macro, $interface_macro_set) = split ' ', $in;
501 $interface_macro = $in;
502 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
504 $interface = 1; # local
505 $Interfaces = 1; # global
508 sub INTERFACE_handler() {
509 my $in = merge_section();
513 foreach (split /[\s,]+/, $in) {
514 $Interfaces{$_} = $_;
517 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
519 $interface = 1; # local
520 $Interfaces = 1; # global
523 sub CLEANUP_handler() { print_section() }
524 sub PREINIT_handler() { print_section() }
525 sub POSTCALL_handler() { print_section() }
526 sub INIT_handler() { print_section() }
535 # Parse alias definitions
537 # alias = value alias = value ...
539 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
541 $orig_alias = $alias ;
544 # check for optional package definition in the alias
545 $alias = $Packprefix . $alias if $alias !~ /::/ ;
547 # check for duplicate alias name & duplicate value
548 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
549 if defined $XsubAliases{$alias} ;
551 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
552 if $XsubAliasValues{$value} ;
555 $XsubAliases{$alias} = $value ;
556 $XsubAliasValues{$value} = $orig_alias ;
559 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
565 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
568 GetAliases($_) if $_ ;
572 sub REQUIRE_handler ()
574 # the rest of the current line should contain a version number
577 TrimWhitespace($Ver) ;
579 death ("Error: REQUIRE expects a version number")
582 # check that the version number is of the form n.n
583 death ("Error: REQUIRE: expected a number, got '$Ver'")
584 unless $Ver =~ /^\d+(\.\d*)?/ ;
586 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
587 unless $XSUBPP_version >= $Ver ;
590 sub VERSIONCHECK_handler ()
592 # the rest of the current line should contain either ENABLE or
597 # check for ENABLE/DISABLE
598 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
599 unless /^(ENABLE|DISABLE)/i ;
601 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
602 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
606 sub PROTOTYPE_handler ()
610 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
611 if $proto_in_this_xsub ++ ;
613 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
617 if ($_ eq 'DISABLE') {
620 elsif ($_ eq 'ENABLE') {
624 # remove any whitespace
626 death("Error: Invalid prototype '$_'")
627 unless ValidProtoString($_) ;
628 $ProtoThisXSUB = C_string($_) ;
632 # If no prototype specified, then assume empty prototype ""
633 $ProtoThisXSUB = 2 unless $specified ;
641 death("Error: Only 1 SCOPE declaration allowed per xsub")
642 if $scope_in_this_xsub ++ ;
644 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
647 if ($_ =~ /^DISABLE/i) {
650 elsif ($_ =~ /^ENABLE/i) {
657 sub PROTOTYPES_handler ()
659 # the rest of the current line should contain either ENABLE or
664 # check for ENABLE/DISABLE
665 death ("Error: PROTOTYPES: ENABLE/DISABLE")
666 unless /^(ENABLE|DISABLE)/i ;
668 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
669 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
674 sub INCLUDE_handler ()
676 # the rest of the current line should contain a valid filename
680 death("INCLUDE: filename missing")
683 death("INCLUDE: output pipe is illegal")
686 # simple minded recursion detector
687 death("INCLUDE loop detected")
688 if $IncludedFiles{$_} ;
690 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
692 # Save the current file context.
695 LastLine => $lastline,
696 LastLineNo => $lastline_no,
699 Filename => $filename,
706 open ($FH, "$_") or death("Cannot open '$_': $!") ;
710 #/* INCLUDE: Including '$_' from '$filename' */
716 # Prime the pump by reading the first
719 # skip leading blank lines
721 last unless /^\s*$/ ;
731 return 0 unless $XSStack[-1]{type} eq 'file' ;
733 my $data = pop @XSStack ;
734 my $ThisFile = $filename ;
735 my $isPipe = ($filename =~ /\|\s*$/) ;
737 -- $IncludedFiles{$filename}
742 $FH = $data->{Handle} ;
743 $filename = $data->{Filename} ;
744 $lastline = $data->{LastLine} ;
745 $lastline_no = $data->{LastLineNo} ;
746 @line = @{ $data->{Line} } ;
747 @line_no = @{ $data->{LineNo} } ;
749 if ($isPipe and $? ) {
751 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
757 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
764 sub ValidProtoString ($)
768 if ( $string =~ /^$proto_re+$/ ) {
779 $string =~ s[\\][\\\\]g ;
787 $proto_letter{$type} or "\$" ;
791 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
793 my ($cpp, $cpplevel);
795 if ($cpp =~ /^\#\s*if/) {
797 } elsif (!$cpplevel) {
798 Warn("Warning: #else/elif/endif without #if in this function");
799 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
800 if $XSStack[-1]{type} eq 'if';
802 } elsif ($cpp =~ /^\#\s*endif/) {
806 Warn("Warning: #if without #endif in this function") if $cpplevel;
819 open($FH, $filename) or die "cannot open $filename: $!\n";
821 # Identify the version of xsubpp used
824 * This file was generated automatically by xsubpp version $XSUBPP_version from the
825 * contents of $filename. Do not edit this file, edit $filename instead.
827 * ANY CHANGES MADE HERE WILL BE LOST!
834 print("#line 1 \"$filename\"\n")
838 last if ($Module, $Package, $Prefix) =
839 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
842 s/#if(?:def\s|\s+defined)\s*(\(__cplusplus\)|__cplusplus)/#if defined(__cplusplus) && !defined(PERL_OBJECT)/;
846 &Exit unless defined $_;
848 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
853 # Read next xsub into @line from ($lastline, <$FH>).
856 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
857 if !defined $lastline && $XSStack[-1]{type} eq 'if';
860 return PopFile() if !defined $lastline;
863 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
865 $Package = defined($2) ? $2 : ''; # keep -w happy
866 $Prefix = defined($3) ? $3 : ''; # keep -w happy
867 $Prefix = quotemeta $Prefix ;
868 ($Module_cname = $Module) =~ s/\W/_/g;
869 ($Packid = $Package) =~ tr/:/_/;
870 $Packprefix = $Package;
871 $Packprefix .= "::" if $Packprefix ne "";
876 if ($lastline !~ /^\s*#/ ||
878 # ANSI: if ifdef ifndef elif else endif define undef
880 # gcc: warning include_next
882 # others: ident (gcc notes that some cpps have this one)
883 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
884 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
885 push(@line, $lastline);
886 push(@line_no, $lastline_no) ;
889 # Read next line and continuation lines
890 last unless defined($lastline = <$FH>);
893 $lastline .= $tmp_line
894 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
897 $lastline =~ s/^\s+$//;
899 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
904 while (fetch_para()) {
905 # Print initial preprocessor statements and blank lines
906 while (@line && $line[0] !~ /^[^\#]/) {
907 my $line = shift(@line);
909 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
911 if ($statement eq 'if') {
912 $XSS_work_idx = @XSStack;
913 push(@XSStack, {type => 'if'});
915 death ("Error: `$statement' with no matching `if'")
916 if $XSStack[-1]{type} ne 'if';
917 if ($XSStack[-1]{varname}) {
918 push(@InitFileCode, "#endif\n");
919 push(@BootCode, "#endif");
922 my(@fns) = keys %{$XSStack[-1]{functions}};
923 if ($statement ne 'endif') {
924 # Hide the functions defined in other #if branches, and reset.
925 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
926 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
928 my($tmp) = pop(@XSStack);
929 0 while (--$XSS_work_idx
930 && $XSStack[$XSS_work_idx]{type} ne 'if');
931 # Keep all new defined functions
932 push(@fns, keys %{$tmp->{other_functions}});
933 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
938 next PARAGRAPH unless @line;
940 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
941 # We are inside an #if, but have not yet #defined its xsubpp variable.
942 print "#define $cpp_next_tmp 1\n\n";
943 push(@InitFileCode, "#if $cpp_next_tmp\n");
944 push(@BootCode, "#if $cpp_next_tmp");
945 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
948 death ("Code is not inside a function"
949 ." (maybe last function was ended by a blank line "
950 ." followed by a a statement on column one?)")
951 if $line[0] =~ /^\s/;
953 # initialize info arrays
962 undef($RETVAL_no_return) ;
965 undef(@arg_with_types) ;
966 undef($processing_arg_with_types) ;
970 undef($proto_in_this_xsub) ;
971 undef($scope_in_this_xsub) ;
973 undef($prepush_done);
974 $interface_macro = 'XSINTERFACE_FUNC' ;
975 $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
976 $ProtoThisXSUB = $WantPrototypes ;
981 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
982 &{"${kwd}_handler"}() ;
983 next PARAGRAPH unless @line ;
987 if (check_keyword("BOOT")) {
989 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
990 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
991 push (@BootCode, @line, "") ;
996 # extract return type, function name and arguments
997 ($ret_type) = TidyType($_);
998 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
1000 # a function definition needs at least 2 lines
1001 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
1004 $static = 1 if $ret_type =~ s/^static\s+//;
1006 $func_header = shift(@line);
1007 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
1008 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
1010 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
1011 $class = "$4 $class" if $4;
1012 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
1013 ($clean_func_name = $func_name) =~ s/^$Prefix//;
1014 $Full_func_name = "${Packid}_$clean_func_name";
1015 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
1017 # Check for duplicate function definition
1018 for $tmp (@XSStack) {
1019 next unless defined $tmp->{functions}{$Full_func_name};
1020 Warn("Warning: duplicate function definition '$clean_func_name' detected");
1023 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
1024 %XsubAliases = %XsubAliasValues = %Interfaces = ();
1027 $orig_args =~ s/\\\s*/ /g; # process line continuations
1030 if ($process_argtypes and $orig_args =~ /\S/) {
1031 my $args = "$orig_args ,";
1032 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
1033 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
1039 ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
1040 my ($pre, $name) = ($arg =~ /(.*?) \s* \b(\w+) \s* $ /x);
1041 next unless length $pre;
1044 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST)\s+//) {
1046 $out_type = $type if $type ne 'IN';
1047 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST)\s+//;
1049 if (/\W/) { # Has a type
1050 push @arg_with_types, $arg;
1051 # warn "pushing '$arg'\n";
1052 $arg_types{$name} = $arg;
1053 $_ = "$name$default";
1055 $out_vars{$_} = 1 if $out_type eq 'OUTLIST';
1056 push @in_out, $name if $out_type;
1057 $in_out{$name} = $out_type if $out_type;
1060 @args = split(/\s*,\s*/, $orig_args);
1061 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
1064 @args = split(/\s*,\s*/, $orig_args);
1066 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST)\s+//) {
1068 next if $out_type eq 'IN';
1069 $out_vars{$_} = 1 if $out_type eq 'OUTLIST';
1070 push @in_out, $name;
1071 $in_out{$_} = $out_type;
1075 if (defined($class)) {
1076 my $arg0 = ((defined($static) or $func_name eq 'new')
1077 ? "CLASS" : "THIS");
1078 unshift(@args, $arg0);
1079 ($report_args = "$arg0, $report_args") =~ s/^\w+, $/$arg0/;
1084 my $report_args = '';
1085 foreach $i (0 .. $#args) {
1086 if ($args[$i] =~ s/\.\.\.//) {
1088 if ($args[$i] eq '' && $i == $#args) {
1089 $report_args .= ", ...";
1094 if ($out_vars{$args[$i]}) {
1095 push @args_num, undef;
1097 push @args_num, ++$num_args;
1098 $report_args .= ", $args[$i]";
1100 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
1103 $defaults{$args[$i]} = $2;
1104 $defaults{$args[$i]} =~ s/"/\\"/g;
1106 $proto_arg[$i+1] = "\$" ;
1108 $min_args = $num_args - $extra_args;
1109 $report_args =~ s/"/\\"/g;
1110 $report_args =~ s/^,\s+//;
1111 my @func_args = @args;
1112 shift @func_args if defined($class);
1115 s/^/&/ if $in_out{$_};
1117 $func_args = join(", ", @func_args);
1118 @args_match{@args} = @args_num;
1120 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
1121 $CODE = grep(/^\s*CODE\s*:/, @line);
1122 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
1123 # to set explicit return values.
1124 $EXPLICIT_RETURN = ($CODE &&
1125 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
1126 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
1127 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
1129 $xsreturn = 1 if $EXPLICIT_RETURN;
1131 # print function header
1133 #XS(XS_${Full_func_name})
1137 print Q<<"EOF" if $ALIAS ;
1140 print Q<<"EOF" if $INTERFACE ;
1141 # dXSFUNCTION($ret_type);
1144 $cond = ($min_args ? qq(items < $min_args) : 0);
1146 elsif ($min_args == $num_args) {
1147 $cond = qq(items != $min_args);
1150 $cond = qq(items < $min_args || items > $num_args);
1153 print Q<<"EOF" if $except;
1154 # char errbuf[1024];
1159 { print Q<<"EOF" if $cond }
1161 # Perl_croak(aTHX_ "Usage: %s($report_args)", GvNAME(CvGV(cv)));
1164 { print Q<<"EOF" if $cond }
1166 # Perl_croak(aTHX_ "Usage: $pname($report_args)");
1169 print Q<<"EOF" if $PPCODE;
1173 # Now do a block of some sort.
1176 $cond = ''; # last CASE: condidional
1177 push(@line, "$END:");
1178 push(@line_no, $line_no[-1]);
1182 &CASE_handler if check_keyword("CASE");
1187 # do initialization of input variables
1195 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|PROTOTYPE|SCOPE") ;
1197 print Q<<"EOF" if $ScopeThisXSUB;
1202 if (!$thisdone && defined($class)) {
1203 if (defined($static) or $func_name eq 'new') {
1205 $var_types{"CLASS"} = "char *";
1206 &generate_init("char *", 1, "CLASS");
1210 $var_types{"THIS"} = "$class *";
1211 &generate_init("$class *", 1, "THIS");
1216 if (/^\s*NOT_IMPLEMENTED_YET/) {
1217 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1220 if ($ret_type ne "void") {
1221 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
1223 $args_match{"RETVAL"} = 0;
1224 $var_types{"RETVAL"} = $ret_type;
1225 print "\tdXSTARG;\n"
1226 if $WantOptimize and $targetable{$type_kind{$ret_type}};
1229 if (@arg_with_types) {
1230 unshift @line, @arg_with_types, $_;
1232 $processing_arg_with_types = 1;
1237 process_keyword("INIT|ALIAS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS") ;
1239 if (check_keyword("PPCODE")) {
1241 death ("PPCODE must be last thing") if @line;
1242 print "\tLEAVE;\n" if $ScopeThisXSUB;
1243 print "\tPUTBACK;\n\treturn;\n";
1244 } elsif (check_keyword("CODE")) {
1246 } elsif (defined($class) and $func_name eq "DESTROY") {
1248 print "delete THIS;\n";
1251 if ($ret_type ne "void") {
1255 if (defined($static)) {
1256 if ($func_name eq 'new') {
1257 $func_name = "$class";
1261 } elsif (defined($class)) {
1262 if ($func_name eq 'new') {
1263 $func_name .= " $class";
1268 $func_name =~ s/^($spat)//
1270 $func_name = 'XSFUNCTION' if $interface;
1271 print "$func_name($func_args);\n";
1275 # do output variables
1276 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
1277 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
1278 # $wantRETVAL set if 'RETVAL =' autogenerated
1279 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
1281 process_keyword("POSTCALL|OUTPUT|ALIAS|PROTOTYPE");
1283 # all OUTPUT done, so now push the return value on the stack
1284 if ($gotRETVAL && $RETVAL_code) {
1285 print "\t$RETVAL_code\n";
1286 } elsif ($gotRETVAL || $wantRETVAL) {
1287 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
1289 my $type = $ret_type;
1291 # 0: type, 1: with_size, 2: how, 3: how_size
1292 if ($t and not $t->[1] and $t->[0] eq 'p') {
1293 # PUSHp corresponds to setpvn. Treate setpv directly
1294 my $what = eval qq("$t->[2]");
1297 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
1301 my $what = eval qq("$t->[2]");
1305 $size = '' unless defined $size;
1306 $size = eval qq("$size");
1308 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
1312 # RETVAL almost never needs SvSETMAGIC()
1313 &generate_output($ret_type, 0, 'RETVAL', 0);
1317 $xsreturn = 1 if $ret_type ne "void";
1318 my $num = $xsreturn;
1320 print "\tXSprePUSH;" if $c and not $prepush_done;
1321 print "\tEXTEND(SP,$c);\n" if $c;
1323 generate_output($var_types{$_}, $num++, $_, 0, 1) for @in_out;
1326 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
1328 print Q<<"EOF" if $ScopeThisXSUB;
1331 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1335 # print function trailer
1339 print Q<<EOF if $except;
1342 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1345 if (check_keyword("CASE")) {
1346 blurt ("Error: No `CASE:' at top of function")
1348 $_ = "CASE: $_"; # Restore CASE: label
1351 last if $_ eq "$END:";
1352 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1355 print Q<<EOF if $except;
1357 # Perl_croak(aTHX_ errbuf);
1361 print Q<<EOF unless $PPCODE;
1362 # XSRETURN($xsreturn);
1365 print Q<<EOF unless $PPCODE;
1375 my $newXS = "newXS" ;
1378 # Build the prototype string for the xsub
1379 if ($ProtoThisXSUB) {
1380 $newXS = "newXSproto";
1382 if ($ProtoThisXSUB eq 2) {
1383 # User has specified empty prototype
1386 elsif ($ProtoThisXSUB ne 1) {
1387 # User has specified a prototype
1388 $proto = ', "' . $ProtoThisXSUB . '"';
1392 if ($min_args < $num_args) {
1394 $proto_arg[$min_args] .= ";" ;
1396 push @proto_arg, "$s\@"
1399 $proto = ', "' . join ("", @proto_arg) . '"';
1404 $XsubAliases{$pname} = 0
1405 unless defined $XsubAliases{$pname} ;
1406 while ( ($name, $value) = each %XsubAliases) {
1407 push(@InitFileCode, Q<<"EOF");
1408 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1409 # XSANY.any_i32 = $value ;
1411 push(@InitFileCode, Q<<"EOF") if $proto;
1412 # sv_setpv((SV*)cv$proto) ;
1416 elsif ($interface) {
1417 while ( ($name, $value) = each %Interfaces) {
1418 $name = "$Package\::$name" unless $name =~ /::/;
1419 push(@InitFileCode, Q<<"EOF");
1420 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1421 # $interface_macro_set(cv,$value) ;
1423 push(@InitFileCode, Q<<"EOF") if $proto;
1424 # sv_setpv((SV*)cv$proto) ;
1430 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1434 # print initialization routine
1443 #XS(boot_$Module_cname)
1449 # char* file = __FILE__;
1453 print Q<<"EOF" if $WantVersionChk ;
1454 # XS_VERSION_BOOTCHECK ;
1458 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1464 print @InitFileCode;
1466 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1472 print "\n /* Initialisation Section */\n\n" ;
1475 print "\n /* End of Initialisation Section */\n\n" ;
1484 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1489 local($type, $num, $var, $init, $name_printed) = @_;
1490 local($arg) = "ST(" . ($num - 1) . ")";
1492 if( $init =~ /^=/ ) {
1493 if ($name_printed) {
1494 eval qq/print " $init\\n"/;
1496 eval qq/print "\\t$var $init\\n"/;
1500 if( $init =~ s/^\+// && $num ) {
1501 &generate_init($type, $num, $var, $name_printed);
1502 } elsif ($name_printed) {
1506 eval qq/print "\\t$var;\\n"/;
1510 $deferred .= eval qq/"\\n\\t$init\\n"/;
1517 # work out the line number
1518 my $line_no = $line_no[@line_no - @line -1] ;
1520 print STDERR "@_ in $filename, line $line_no\n" ;
1536 local($type, $num, $var) = @_;
1537 local($arg) = "ST(" . ($num - 1) . ")";
1538 local($argoff) = $num - 1;
1542 $type = TidyType($type) ;
1543 blurt("Error: '$type' not in typemap"), return
1544 unless defined($type_kind{$type});
1546 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1547 $ntype =~ s/^\s*const\b\s*//;
1548 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1549 $tk = $type_kind{$type};
1550 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1552 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1553 unless defined $input_expr{$tk} ;
1554 $expr = $input_expr{$tk};
1555 if ($expr =~ /DO_ARRAY_ELEM/) {
1556 blurt("Error: '$subtype' not in typemap"), return
1557 unless defined($type_kind{$subtype});
1558 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1559 unless defined $input_expr{$type_kind{$subtype}} ;
1560 $subexpr = $input_expr{$type_kind{$subtype}};
1561 $subexpr =~ s/ntype/subtype/g;
1562 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1563 $subexpr =~ s/\n\t/\n\t\t/g;
1564 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1565 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1566 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1568 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1571 if (defined($defaults{$var})) {
1572 $expr =~ s/(\t+)/$1 /g;
1574 if ($name_printed) {
1577 eval qq/print "\\t$var;\\n"/;
1580 if ($defaults{$var} eq 'NO_INIT') {
1581 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1583 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1586 } elsif ($ScopeThisXSUB or $expr !~ /^\t\$var =/) {
1587 if ($name_printed) {
1590 eval qq/print "\\t$var;\\n"/;
1593 $deferred .= eval qq/"\\n$expr;\\n"/;
1596 die "panic: do not know how to handle this branch for function pointers"
1598 eval qq/print "$expr;\\n"/;
1603 sub generate_output {
1604 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1605 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1606 local($argoff) = $num - 1;
1609 $type = TidyType($type) ;
1610 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1611 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1612 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1614 blurt("Error: '$type' not in typemap"), return
1615 unless defined($type_kind{$type});
1616 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1617 unless defined $output_expr{$type_kind{$type}} ;
1618 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1619 $ntype =~ s/\(\)//g;
1620 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1621 $expr = $output_expr{$type_kind{$type}};
1622 if ($expr =~ /DO_ARRAY_ELEM/) {
1623 blurt("Error: '$subtype' not in typemap"), return
1624 unless defined($type_kind{$subtype});
1625 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1626 unless defined $output_expr{$type_kind{$subtype}} ;
1627 $subexpr = $output_expr{$type_kind{$subtype}};
1628 $subexpr =~ s/ntype/subtype/g;
1629 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1630 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1631 $subexpr =~ s/\n\t/\n\t\t/g;
1632 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1633 eval "print qq\a$expr\a";
1635 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1637 elsif ($var eq 'RETVAL') {
1638 if ($expr =~ /^\t\$arg = new/) {
1639 # We expect that $arg has refcnt 1, so we need to
1641 eval "print qq\a$expr\a";
1643 print "\tsv_2mortal(ST($num));\n";
1644 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1646 elsif ($expr =~ /^\s*\$arg\s*=/) {
1647 # We expect that $arg has refcnt >=1, so we need
1649 eval "print qq\a$expr\a";
1651 print "\tsv_2mortal(ST(0));\n";
1652 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1655 # Just hope that the entry would safely write it
1656 # over an already mortalized value. By
1657 # coincidence, something like $arg = &sv_undef
1659 print "\tST(0) = sv_newmortal();\n";
1660 eval "print qq\a$expr\a";
1662 # new mortals don't have set magic
1666 print "\tPUSHs(sv_newmortal());\n";
1668 eval "print qq\a$expr\a";
1670 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1672 elsif ($arg =~ /^ST\(\d+\)$/) {
1673 eval "print qq\a$expr\a";
1675 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1681 my($type, $varname) = @_;
1684 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1686 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1687 (substr $type, pos $type, 0) = " $varname ";
1689 $type .= "\t$varname";
1697 # If this is VMS, the exit status has meaning to the shell, so we
1698 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1700 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1701 exit ($errors ? 1 : 0);