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 Retains '::' in type names so that C++ hierachical types can be mapped.
43 Adds exception handling stubs to the C code.
45 =item B<-typemap typemap>
47 Indicates that a user-supplied typemap should take precedence over the
48 default typemaps. This option may be used multiple times, with the last
49 typemap having the highest precedence.
53 Prints the I<xsubpp> version number to standard output, then exits.
57 By default I<xsubpp> will not automatically generate prototype code for
58 all xsubs. This flag will enable prototypes.
60 =item B<-noversioncheck>
62 Disables the run time test that determines if the object file (derived
63 from the C<.xs> file) and the C<.pm> files have the same version
66 =item B<-nolinenumbers>
68 Prevents the inclusion of `#line' directives in the output.
72 Disables certain optimizations. The only optimization that is currently
73 affected is the use of I<target>s by the output C code (see L<perlguts>).
74 This may significantly slow down the generated code, but this is the way
75 B<xsubpp> of 5.005 and earlier operated.
79 Disable recognition of C<IN>, C<OUT_LIST> and C<INOUT_LIST> declarations.
83 Disable recognition of ANSI-like descriptions of function signature.
89 No environment variables are used.
95 =head1 MODIFICATION HISTORY
97 See the file F<changes.pod>.
101 perl(1), perlxs(1), perlxstut(1)
107 use vars qw($cplusplus $hiertype);
116 $XSUBPP_version = "1.9508";
118 my ($Is_VMS, $SymSet);
121 # Establish set of global symbols with max length 28, since xsubpp
122 # will later add the 'XS_' prefix.
123 require ExtUtils::XSSymSet;
124 $SymSet = new ExtUtils::XSSymSet 28;
129 $usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-noinout] [-noargtypes] [-s pattern] [-typemap typemap]... file.xs\n";
131 $proto_re = "[" . quotemeta('\$%&*@;[]') . "]" ;
134 $WantPrototypes = -1 ;
135 $WantVersionChk = 1 ;
137 $WantLineNumbers = 1 ;
141 my $process_inout = 1;
142 my $process_argtypes = 1;
144 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
147 $spat = quotemeta shift, next SWITCH if $flag eq 's';
148 $cplusplus = 1, next SWITCH if $flag eq 'C++';
149 $hiertype = 1, next SWITCH if $flag eq 'hiertype';
150 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
151 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
152 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
153 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
154 # XXX left this in for compat
155 next SWITCH if $flag eq 'object_capi';
156 $except = " TRY", next SWITCH if $flag eq 'except';
157 push(@tm,shift), next SWITCH if $flag eq 'typemap';
158 $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
159 $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
160 $WantOptimize = 0, next SWITCH if $flag eq 'nooptimize';
161 $WantOptimize = 1, next SWITCH if $flag eq 'optimize';
162 $process_inout = 0, next SWITCH if $flag eq 'noinout';
163 $process_inout = 1, next SWITCH if $flag eq 'inout';
164 $process_argtypes = 0, next SWITCH if $flag eq 'noargtypes';
165 $process_argtypes = 1, next SWITCH if $flag eq 'argtypes';
166 (print "xsubpp version $XSUBPP_version\n"), exit
170 if ($WantPrototypes == -1)
171 { $WantPrototypes = 0}
176 @ARGV == 1 or die $usage;
177 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
178 or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
179 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
180 or ($dir, $filename) = ('.', $ARGV[0]);
184 ++ $IncludedFiles{$ARGV[0]} ;
186 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
187 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
192 $_[0] =~ s/^\s+|\s+$//go ;
199 # rationalise any '*' by joining them into bunches and removing whitespace
203 # change multiple whitespace into a single space
206 # trim leading & trailing whitespace
212 $typemap = shift @ARGV;
213 foreach $typemap (@tm) {
214 die "Can't find $typemap in $pwd\n" unless -r $typemap;
216 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
217 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
219 foreach $typemap (@tm) {
220 next unless -f $typemap ;
221 # skip directories, binary files etc.
222 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
224 open(TYPEMAP, $typemap)
225 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
231 my $line_no = $. + 1;
232 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
233 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
234 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
235 if ($mode eq 'Typemap') {
239 # skip blank lines and comment lines
240 next if /^$/ or /^#/ ;
241 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
242 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
243 $type = TidyType($type) ;
244 $type_kind{$type} = $kind ;
245 # prototype defaults to '$'
246 $proto = "\$" unless $proto ;
247 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
248 unless ValidProtoString($proto) ;
249 $proto_letter{$type} = C_string($proto) ;
254 elsif ($mode eq 'Input') {
256 $input_expr{$_} = '';
257 $current = \$input_expr{$_};
261 $output_expr{$_} = '';
262 $current = \$output_expr{$_};
268 foreach $key (keys %input_expr) {
269 $input_expr{$key} =~ s/;*\s+\z//;
272 $bal = qr[(?:(?>[^()]+)|\((??{ $bal })\))*]; # ()-balanced
273 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
274 $size = qr[,\s* (??{ $bal }) ]x; # Third arg (to setpvn)
276 foreach $key (keys %output_expr) {
279 my ($t, $with_size, $arg, $sarg) =
280 ($output_expr{$key} =~
281 m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
282 \s* \( \s* $cast \$arg \s* ,
283 \s* ( (??{ $bal }) ) # Set from
284 ( (??{ $size }) )? # Possible sizeof set-from
287 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
290 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
292 # Match an XS keyword
293 $BLOCK_re= '\s*(' . join('|', qw(
294 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
295 CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
296 SCOPE INTERFACE INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD
299 # Input: ($_, @line) == unparsed input.
300 # Output: ($_, @line) == (rest of line, following lines).
301 # Return: the matched keyword if found, otherwise 0
303 $_ = shift(@line) while !/\S/ && @line;
304 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
307 my ($C_group_rex, $C_arg);
308 # Group in C (no support for comments or literals)
309 $C_group_rex = qr/ [({\[]
310 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
312 # Chunk in C without comma at toplevel (no comments):
313 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
314 | (??{ $C_group_rex })
315 | " (?: (?> [^\\"]+ )
317 )* " # String literal
318 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
321 if ($WantLineNumbers) {
323 package xsubpp::counter;
325 my ($class, $cfile) = @_;
327 $SECTION_END_MARKER = "#line --- \"$cfile\"";
336 while ($$self =~ s/^([^\n]*\n)//) {
339 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
348 $self->PRINT(sprintf($fmt, @_));
352 # Not necessary if we're careful to end with a "\n"
358 my $cfile = $filename;
359 $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
360 tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
361 select PSEUDO_STDOUT;
365 # the "do" is required for right semantics
366 do { $_ = shift(@line) } while !/\S/ && @line;
368 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
369 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
370 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
373 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
379 while (!/\S/ && @line) {
383 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
390 sub process_keyword($)
395 &{"${kwd}_handler"}()
396 while $kwd = check_keyword($pattern) ;
400 blurt ("Error: `CASE:' after unconditional `CASE:'")
401 if $condnum && $cond eq '';
403 TrimWhitespace($cond);
404 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
409 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
410 last if /^\s*NOT_IMPLEMENTED_YET/;
411 next unless /\S/; # skip blank lines
416 # remove trailing semicolon if no initialisation
417 s/\s*;$//g unless /[=;+].*\S/ ;
419 # Process the length(foo) declarations
420 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
421 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
422 $lengthof{$2} = $name;
423 # $islengthof{$name} = $1;
424 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;";
427 # check for optional initialisation code
429 $var_init = $1 if s/\s*([=;+].*)$//s ;
430 $var_init =~ s/"/\\"/g;
433 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
434 or blurt("Error: invalid argument declaration '$line'"), next;
436 # Check for duplicate definitions
437 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
438 if $arg_list{$var_name}++
439 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
441 $thisdone |= $var_name eq "THIS";
442 $retvaldone |= $var_name eq "RETVAL";
443 $var_types{$var_name} = $var_type;
444 # XXXX This check is a safeguard against the unfinished conversion of
445 # generate_init(). When generate_init() is fixed,
446 # one can use 2-args map_type() unconditionally.
447 if ($var_type =~ / \( \s* \* \s* \) /x) {
448 # Function pointers are not yet supported with &output_init!
449 print "\t" . &map_type($var_type, $var_name);
452 print "\t" . &map_type($var_type);
455 $var_num = $args_match{$var_name};
457 $proto_arg[$var_num] = ProtoString($var_type)
459 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
460 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
461 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
462 and $var_init !~ /\S/) {
466 print "\t$var_name;\n";
468 } elsif ($var_init =~ /\S/) {
469 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
471 # generate initialization code
472 &generate_init($var_type, $var_num, $var_name, $name_printed);
480 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
482 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
483 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
486 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
487 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
488 if $outargs{$outarg} ++ ;
489 if (!$gotRETVAL and $outarg eq 'RETVAL') {
490 # deal with RETVAL last
491 $RETVAL_code = $outcode ;
495 blurt ("Error: OUTPUT $outarg not an argument"), next
496 unless defined($args_match{$outarg});
497 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
498 unless defined $var_types{$outarg} ;
499 $var_num = $args_match{$outarg};
501 print "\t$outcode\n";
502 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
504 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
506 delete $in_out{$outarg} # No need to auto-OUTPUT
507 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
511 sub C_ARGS_handler() {
512 my $in = merge_section();
518 sub INTERFACE_MACRO_handler() {
519 my $in = merge_section();
522 if ($in =~ /\s/) { # two
523 ($interface_macro, $interface_macro_set) = split ' ', $in;
525 $interface_macro = $in;
526 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
528 $interface = 1; # local
529 $Interfaces = 1; # global
532 sub INTERFACE_handler() {
533 my $in = merge_section();
537 foreach (split /[\s,]+/, $in) {
538 $Interfaces{$_} = $_;
541 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
543 $interface = 1; # local
544 $Interfaces = 1; # global
547 sub CLEANUP_handler() { print_section() }
548 sub PREINIT_handler() { print_section() }
549 sub POSTCALL_handler() { print_section() }
550 sub INIT_handler() { print_section() }
559 # Parse alias definitions
561 # alias = value alias = value ...
563 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
565 $orig_alias = $alias ;
568 # check for optional package definition in the alias
569 $alias = $Packprefix . $alias if $alias !~ /::/ ;
571 # check for duplicate alias name & duplicate value
572 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
573 if defined $XsubAliases{$alias} ;
575 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
576 if $XsubAliasValues{$value} ;
579 $XsubAliases{$alias} = $value ;
580 $XsubAliasValues{$value} = $orig_alias ;
583 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
589 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
592 push @Attributes, $_;
598 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
601 GetAliases($_) if $_ ;
605 sub OVERLOAD_handler()
607 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
610 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
611 $Overload = 1 unless $Overload;
612 my $overload = "$Package\::(".$1 ;
614 " newXS(\"$overload\", XS_$Full_func_name, file$proto);\n");
620 sub REQUIRE_handler ()
622 # the rest of the current line should contain a version number
625 TrimWhitespace($Ver) ;
627 death ("Error: REQUIRE expects a version number")
630 # check that the version number is of the form n.n
631 death ("Error: REQUIRE: expected a number, got '$Ver'")
632 unless $Ver =~ /^\d+(\.\d*)?/ ;
634 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
635 unless $XSUBPP_version >= $Ver ;
638 sub VERSIONCHECK_handler ()
640 # the rest of the current line should contain either ENABLE or
645 # check for ENABLE/DISABLE
646 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
647 unless /^(ENABLE|DISABLE)/i ;
649 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
650 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
654 sub PROTOTYPE_handler ()
658 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
659 if $proto_in_this_xsub ++ ;
661 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
665 if ($_ eq 'DISABLE') {
668 elsif ($_ eq 'ENABLE') {
672 # remove any whitespace
674 death("Error: Invalid prototype '$_'")
675 unless ValidProtoString($_) ;
676 $ProtoThisXSUB = C_string($_) ;
680 # If no prototype specified, then assume empty prototype ""
681 $ProtoThisXSUB = 2 unless $specified ;
689 death("Error: Only 1 SCOPE declaration allowed per xsub")
690 if $scope_in_this_xsub ++ ;
692 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
695 if ($_ =~ /^DISABLE/i) {
698 elsif ($_ =~ /^ENABLE/i) {
705 sub PROTOTYPES_handler ()
707 # the rest of the current line should contain either ENABLE or
712 # check for ENABLE/DISABLE
713 death ("Error: PROTOTYPES: ENABLE/DISABLE")
714 unless /^(ENABLE|DISABLE)/i ;
716 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
717 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
722 sub INCLUDE_handler ()
724 # the rest of the current line should contain a valid filename
728 death("INCLUDE: filename missing")
731 death("INCLUDE: output pipe is illegal")
734 # simple minded recursion detector
735 death("INCLUDE loop detected")
736 if $IncludedFiles{$_} ;
738 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
740 # Save the current file context.
743 LastLine => $lastline,
744 LastLineNo => $lastline_no,
747 Filename => $filename,
754 open ($FH, "$_") or death("Cannot open '$_': $!") ;
758 #/* INCLUDE: Including '$_' from '$filename' */
764 # Prime the pump by reading the first
767 # skip leading blank lines
769 last unless /^\s*$/ ;
779 return 0 unless $XSStack[-1]{type} eq 'file' ;
781 my $data = pop @XSStack ;
782 my $ThisFile = $filename ;
783 my $isPipe = ($filename =~ /\|\s*$/) ;
785 -- $IncludedFiles{$filename}
790 $FH = $data->{Handle} ;
791 $filename = $data->{Filename} ;
792 $lastline = $data->{LastLine} ;
793 $lastline_no = $data->{LastLineNo} ;
794 @line = @{ $data->{Line} } ;
795 @line_no = @{ $data->{LineNo} } ;
797 if ($isPipe and $? ) {
799 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
805 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
812 sub ValidProtoString ($)
816 if ( $string =~ /^$proto_re+$/ ) {
827 $string =~ s[\\][\\\\]g ;
835 $proto_letter{$type} or "\$" ;
839 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
841 my ($cpp, $cpplevel);
843 if ($cpp =~ /^\#\s*if/) {
845 } elsif (!$cpplevel) {
846 Warn("Warning: #else/elif/endif without #if in this function");
847 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
848 if $XSStack[-1]{type} eq 'if';
850 } elsif ($cpp =~ /^\#\s*endif/) {
854 Warn("Warning: #if without #endif in this function") if $cpplevel;
867 open($FH, $filename) or die "cannot open $filename: $!\n";
869 # Identify the version of xsubpp used
872 * This file was generated automatically by xsubpp version $XSUBPP_version from the
873 * contents of $filename. Do not edit this file, edit $filename instead.
875 * ANY CHANGES MADE HERE WILL BE LOST!
882 print("#line 1 \"$filename\"\n")
888 my $podstartline = $.;
891 print("/* Skipped embedded POD. */\n");
892 printf("#line %d \"$filename\"\n", $. + 1)
898 # At this point $. is at end of file so die won't state the start
899 # of the problem, and as we haven't yet read any lines &death won't
900 # show the correct line in the message either.
901 die ("Error: Unterminated pod in $filename, line $podstartline\n")
904 last if ($Module, $Package, $Prefix) =
905 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
909 &Exit unless defined $_;
911 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
916 # Read next xsub into @line from ($lastline, <$FH>).
919 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
920 if !defined $lastline && $XSStack[-1]{type} eq 'if';
923 return PopFile() if !defined $lastline;
926 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
928 $Package = defined($2) ? $2 : ''; # keep -w happy
929 $Prefix = defined($3) ? $3 : ''; # keep -w happy
930 $Prefix = quotemeta $Prefix ;
931 ($Module_cname = $Module) =~ s/\W/_/g;
932 ($Packid = $Package) =~ tr/:/_/;
933 $Packprefix = $Package;
934 $Packprefix .= "::" if $Packprefix ne "";
940 while ($lastline =~ /^=/) {
941 while ($lastline = <$FH>) {
942 last if ($lastline =~ /^=cut\s*$/);
944 death ("Error: Unterminated pod") unless $lastline;
947 $lastline =~ s/^\s+$//;
949 if ($lastline !~ /^\s*#/ ||
951 # ANSI: if ifdef ifndef elif else endif define undef
953 # gcc: warning include_next
955 # others: ident (gcc notes that some cpps have this one)
956 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
957 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
958 push(@line, $lastline);
959 push(@line_no, $lastline_no) ;
962 # Read next line and continuation lines
963 last unless defined($lastline = <$FH>);
966 $lastline .= $tmp_line
967 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
970 $lastline =~ s/^\s+$//;
972 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
977 while (fetch_para()) {
978 # Print initial preprocessor statements and blank lines
979 while (@line && $line[0] !~ /^[^\#]/) {
980 my $line = shift(@line);
982 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
984 if ($statement eq 'if') {
985 $XSS_work_idx = @XSStack;
986 push(@XSStack, {type => 'if'});
988 death ("Error: `$statement' with no matching `if'")
989 if $XSStack[-1]{type} ne 'if';
990 if ($XSStack[-1]{varname}) {
991 push(@InitFileCode, "#endif\n");
992 push(@BootCode, "#endif");
995 my(@fns) = keys %{$XSStack[-1]{functions}};
996 if ($statement ne 'endif') {
997 # Hide the functions defined in other #if branches, and reset.
998 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
999 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
1001 my($tmp) = pop(@XSStack);
1002 0 while (--$XSS_work_idx
1003 && $XSStack[$XSS_work_idx]{type} ne 'if');
1004 # Keep all new defined functions
1005 push(@fns, keys %{$tmp->{other_functions}});
1006 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
1011 next PARAGRAPH unless @line;
1013 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
1014 # We are inside an #if, but have not yet #defined its xsubpp variable.
1015 print "#define $cpp_next_tmp 1\n\n";
1016 push(@InitFileCode, "#if $cpp_next_tmp\n");
1017 push(@BootCode, "#if $cpp_next_tmp");
1018 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
1021 death ("Code is not inside a function"
1022 ." (maybe last function was ended by a blank line "
1023 ." followed by a statement on column one?)")
1024 if $line[0] =~ /^\s/;
1026 # initialize info arrays
1033 undef($wantRETVAL) ;
1034 undef($RETVAL_no_return) ;
1037 undef(@fake_INPUT_pre) ; # For length(s) generated variables
1038 undef(@fake_INPUT) ;
1039 undef($processing_arg_with_types) ;
1040 undef(%argtype_seen) ;
1044 # undef(%islengthof) ;
1045 undef($proto_in_this_xsub) ;
1046 undef($scope_in_this_xsub) ;
1048 undef($prepush_done);
1049 $interface_macro = 'XSINTERFACE_FUNC' ;
1050 $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
1051 $ProtoThisXSUB = $WantPrototypes ;
1056 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
1057 &{"${kwd}_handler"}() ;
1058 next PARAGRAPH unless @line ;
1062 if (check_keyword("BOOT")) {
1064 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
1065 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
1066 push (@BootCode, @line, "") ;
1071 # extract return type, function name and arguments
1072 ($ret_type) = TidyType($_);
1073 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
1075 # Allow one-line ANSI-like declaration
1077 if $process_argtypes
1078 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
1080 # a function definition needs at least 2 lines
1081 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
1084 $static = 1 if $ret_type =~ s/^static\s+//;
1086 $func_header = shift(@line);
1087 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
1088 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
1090 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
1091 $class = "$4 $class" if $4;
1092 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
1093 ($clean_func_name = $func_name) =~ s/^$Prefix//;
1094 $Full_func_name = "${Packid}_$clean_func_name";
1095 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
1097 # Check for duplicate function definition
1098 for $tmp (@XSStack) {
1099 next unless defined $tmp->{functions}{$Full_func_name};
1100 Warn("Warning: duplicate function definition '$clean_func_name' detected");
1103 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
1104 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
1107 $orig_args =~ s/\\\s*/ /g; # process line continuations
1109 my %only_C_inlist; # Not in the signature of Perl function
1110 if ($process_argtypes and $orig_args =~ /\S/) {
1111 my $args = "$orig_args ,";
1112 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
1113 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
1117 my ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
1118 my ($pre, $name) = ($arg =~ /(.*?) \s*
1119 \b ( \w+ | length\( \s*\w+\s* \) )
1121 next unless length $pre;
1124 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//) {
1126 $out_type = $type if $type ne 'IN';
1127 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1128 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1131 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
1132 $name = "XSauto_length_of_$1";
1134 die "Default value on length() argument: `$_'"
1137 if (length $pre or $islength) { # Has a type
1139 push @fake_INPUT_pre, $arg;
1141 push @fake_INPUT, $arg;
1143 # warn "pushing '$arg'\n";
1144 $argtype_seen{$name}++;
1145 $_ = "$name$default"; # Assigns to @args
1147 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
1148 push @outlist, $name if $out_type =~ /OUTLIST$/;
1149 $in_out{$name} = $out_type if $out_type;
1152 @args = split(/\s*,\s*/, $orig_args);
1153 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
1156 @args = split(/\s*,\s*/, $orig_args);
1158 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\s+//) {
1160 next if $out_type eq 'IN';
1161 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
1162 push @outlist, $name if $out_type =~ /OUTLIST$/;
1163 $in_out{$_} = $out_type;
1167 if (defined($class)) {
1168 my $arg0 = ((defined($static) or $func_name eq 'new')
1169 ? "CLASS" : "THIS");
1170 unshift(@args, $arg0);
1171 ($report_args = "$arg0, $report_args") =~ s/^\w+, $/$arg0/;
1176 my $report_args = '';
1177 foreach $i (0 .. $#args) {
1178 if ($args[$i] =~ s/\.\.\.//) {
1180 if ($args[$i] eq '' && $i == $#args) {
1181 $report_args .= ", ...";
1186 if ($only_C_inlist{$args[$i]}) {
1187 push @args_num, undef;
1189 push @args_num, ++$num_args;
1190 $report_args .= ", $args[$i]";
1192 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
1195 $defaults{$args[$i]} = $2;
1196 $defaults{$args[$i]} =~ s/"/\\"/g;
1198 $proto_arg[$i+1] = "\$" ;
1200 $min_args = $num_args - $extra_args;
1201 $report_args =~ s/"/\\"/g;
1202 $report_args =~ s/^,\s+//;
1203 my @func_args = @args;
1204 shift @func_args if defined($class);
1207 s/^/&/ if $in_out{$_};
1209 $func_args = join(", ", @func_args);
1210 @args_match{@args} = @args_num;
1212 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
1213 $CODE = grep(/^\s*CODE\s*:/, @line);
1214 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
1215 # to set explicit return values.
1216 $EXPLICIT_RETURN = ($CODE &&
1217 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
1218 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
1219 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
1221 $xsreturn = 1 if $EXPLICIT_RETURN;
1223 # print function header
1225 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
1226 #XS(XS_${Full_func_name})
1230 print Q<<"EOF" if $ALIAS ;
1233 print Q<<"EOF" if $INTERFACE ;
1234 # dXSFUNCTION($ret_type);
1237 $cond = ($min_args ? qq(items < $min_args) : 0);
1239 elsif ($min_args == $num_args) {
1240 $cond = qq(items != $min_args);
1243 $cond = qq(items < $min_args || items > $num_args);
1246 print Q<<"EOF" if $except;
1247 # char errbuf[1024];
1252 { print Q<<"EOF" if $cond }
1254 # Perl_croak(aTHX_ "Usage: %s($report_args)", GvNAME(CvGV(cv)));
1257 { print Q<<"EOF" if $cond }
1259 # Perl_croak(aTHX_ "Usage: $pname($report_args)");
1262 #gcc -Wall: if an xsub has no arguments and PPCODE is used
1263 #it is likely none of ST, XSRETURN or XSprePUSH macros are used
1264 #hence `ax' (setup by dXSARGS) is unused
1265 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
1266 #but such a move could break third-party extensions
1267 print Q<<"EOF" if $PPCODE and $num_args == 0;
1268 # PERL_UNUSED_VAR(ax); /* -Wall */
1271 print Q<<"EOF" if $PPCODE;
1275 # Now do a block of some sort.
1278 $cond = ''; # last CASE: condidional
1279 push(@line, "$END:");
1280 push(@line_no, $line_no[-1]);
1284 &CASE_handler if check_keyword("CASE");
1289 # do initialization of input variables
1297 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD") ;
1299 print Q<<"EOF" if $ScopeThisXSUB;
1304 if (!$thisdone && defined($class)) {
1305 if (defined($static) or $func_name eq 'new') {
1307 $var_types{"CLASS"} = "char *";
1308 &generate_init("char *", 1, "CLASS");
1312 $var_types{"THIS"} = "$class *";
1313 &generate_init("$class *", 1, "THIS");
1318 if (/^\s*NOT_IMPLEMENTED_YET/) {
1319 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1322 if ($ret_type ne "void") {
1323 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
1325 $args_match{"RETVAL"} = 0;
1326 $var_types{"RETVAL"} = $ret_type;
1327 print "\tdXSTARG;\n"
1328 if $WantOptimize and $targetable{$type_kind{$ret_type}};
1331 if (@fake_INPUT or @fake_INPUT_pre) {
1332 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
1334 $processing_arg_with_types = 1;
1339 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD") ;
1341 if (check_keyword("PPCODE")) {
1343 death ("PPCODE must be last thing") if @line;
1344 print "\tLEAVE;\n" if $ScopeThisXSUB;
1345 print "\tPUTBACK;\n\treturn;\n";
1346 } elsif (check_keyword("CODE")) {
1348 } elsif (defined($class) and $func_name eq "DESTROY") {
1350 print "delete THIS;\n";
1353 if ($ret_type ne "void") {
1357 if (defined($static)) {
1358 if ($func_name eq 'new') {
1359 $func_name = "$class";
1363 } elsif (defined($class)) {
1364 if ($func_name eq 'new') {
1365 $func_name .= " $class";
1370 $func_name =~ s/^($spat)//
1372 $func_name = 'XSFUNCTION' if $interface;
1373 print "$func_name($func_args);\n";
1377 # do output variables
1378 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
1379 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
1380 # $wantRETVAL set if 'RETVAL =' autogenerated
1381 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
1383 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
1385 &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
1386 for grep $in_out{$_} =~ /OUT$/, keys %in_out;
1388 # all OUTPUT done, so now push the return value on the stack
1389 if ($gotRETVAL && $RETVAL_code) {
1390 print "\t$RETVAL_code\n";
1391 } elsif ($gotRETVAL || $wantRETVAL) {
1392 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
1394 my $type = $ret_type;
1396 # 0: type, 1: with_size, 2: how, 3: how_size
1397 if ($t and not $t->[1] and $t->[0] eq 'p') {
1398 # PUSHp corresponds to setpvn. Treate setpv directly
1399 my $what = eval qq("$t->[2]");
1402 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
1406 my $what = eval qq("$t->[2]");
1410 $size = '' unless defined $size;
1411 $size = eval qq("$size");
1413 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
1417 # RETVAL almost never needs SvSETMAGIC()
1418 &generate_output($ret_type, 0, 'RETVAL', 0);
1422 $xsreturn = 1 if $ret_type ne "void";
1423 my $num = $xsreturn;
1425 print "\tXSprePUSH;" if $c and not $prepush_done;
1426 print "\tEXTEND(SP,$c);\n" if $c;
1428 generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
1431 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD") ;
1433 print Q<<"EOF" if $ScopeThisXSUB;
1436 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1440 # print function trailer
1444 print Q<<EOF if $except;
1447 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1450 if (check_keyword("CASE")) {
1451 blurt ("Error: No `CASE:' at top of function")
1453 $_ = "CASE: $_"; # Restore CASE: label
1456 last if $_ eq "$END:";
1457 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1460 print Q<<EOF if $except;
1462 # Perl_croak(aTHX_ errbuf);
1466 print Q<<EOF unless $PPCODE;
1467 # XSRETURN($xsreturn);
1470 print Q<<EOF unless $PPCODE;
1480 my $newXS = "newXS" ;
1483 # Build the prototype string for the xsub
1484 if ($ProtoThisXSUB) {
1485 $newXS = "newXSproto";
1487 if ($ProtoThisXSUB eq 2) {
1488 # User has specified empty prototype
1491 elsif ($ProtoThisXSUB ne 1) {
1492 # User has specified a prototype
1493 $proto = ', "' . $ProtoThisXSUB . '"';
1497 if ($min_args < $num_args) {
1499 $proto_arg[$min_args] .= ";" ;
1501 push @proto_arg, "$s\@"
1504 $proto = ', "' . join ("", @proto_arg) . '"';
1509 $XsubAliases{$pname} = 0
1510 unless defined $XsubAliases{$pname} ;
1511 while ( ($name, $value) = each %XsubAliases) {
1512 push(@InitFileCode, Q<<"EOF");
1513 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1514 # XSANY.any_i32 = $value ;
1516 push(@InitFileCode, Q<<"EOF") if $proto;
1517 # sv_setpv((SV*)cv$proto) ;
1521 elsif (@Attributes) {
1522 push(@InitFileCode, Q<<"EOF");
1523 # cv = newXS(\"$pname\", XS_$Full_func_name, file);
1524 # apply_attrs_string("$Package", cv, "@Attributes", 0);
1527 elsif ($interface) {
1528 while ( ($name, $value) = each %Interfaces) {
1529 $name = "$Package\::$name" unless $name =~ /::/;
1530 push(@InitFileCode, Q<<"EOF");
1531 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1532 # $interface_macro_set(cv,$value) ;
1534 push(@InitFileCode, Q<<"EOF") if $proto;
1535 # sv_setpv((SV*)cv$proto) ;
1541 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1545 # print initialization routine
1554 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1555 #XS(boot_$Module_cname)
1563 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1564 #so `file' is unused
1565 print Q<<"EOF" if $Full_func_name;
1566 # char* file = __FILE__;
1571 print Q<<"EOF" if $WantVersionChk ;
1572 # XS_VERSION_BOOTCHECK ;
1576 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1582 print Q<<"EOF" if ($Overload);
1584 # /* create the package stash */
1585 # HV *hv = get_hv(\"$Package\::OVERLOAD\",TRUE);
1586 # SV *sv = *hv_fetch(hv,"register",8,1);
1589 # /* Make it findable via fetchmethod */
1590 # newXS(\"$Package\::()\", NULL, file);
1594 print @InitFileCode;
1596 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1602 print "\n /* Initialisation Section */\n\n" ;
1605 print "\n /* End of Initialisation Section */\n\n" ;
1614 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1619 local($type, $num, $var, $init, $name_printed) = @_;
1620 local($arg) = "ST(" . ($num - 1) . ")";
1622 if( $init =~ /^=/ ) {
1623 if ($name_printed) {
1624 eval qq/print " $init\\n"/;
1626 eval qq/print "\\t$var $init\\n"/;
1630 if( $init =~ s/^\+// && $num ) {
1631 &generate_init($type, $num, $var, $name_printed);
1632 } elsif ($name_printed) {
1636 eval qq/print "\\t$var;\\n"/;
1640 $deferred .= eval qq/"\\n\\t$init\\n"/;
1647 # work out the line number
1648 my $line_no = $line_no[@line_no - @line -1] ;
1650 print STDERR "@_ in $filename, line $line_no\n" ;
1666 local($type, $num, $var) = @_;
1667 local($arg) = "ST(" . ($num - 1) . ")";
1668 local($argoff) = $num - 1;
1672 $type = TidyType($type) ;
1673 blurt("Error: '$type' not in typemap"), return
1674 unless defined($type_kind{$type});
1676 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1677 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1678 $tk = $type_kind{$type};
1679 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1680 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1681 print "\t$var" unless $name_printed;
1682 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1683 die "default value not supported with length(NAME) supplied"
1684 if defined $defaults{$var};
1687 $type =~ tr/:/_/ unless $hiertype;
1688 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1689 unless defined $input_expr{$tk} ;
1690 $expr = $input_expr{$tk};
1691 if ($expr =~ /DO_ARRAY_ELEM/) {
1692 blurt("Error: '$subtype' not in typemap"), return
1693 unless defined($type_kind{$subtype});
1694 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1695 unless defined $input_expr{$type_kind{$subtype}} ;
1696 $subexpr = $input_expr{$type_kind{$subtype}};
1697 $subexpr =~ s/\$type/\$subtype/g;
1698 $subexpr =~ s/ntype/subtype/g;
1699 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1700 $subexpr =~ s/\n\t/\n\t\t/g;
1701 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1702 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1703 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1705 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1708 if (defined($defaults{$var})) {
1709 $expr =~ s/(\t+)/$1 /g;
1711 if ($name_printed) {
1714 eval qq/print "\\t$var;\\n"/;
1717 if ($defaults{$var} eq 'NO_INIT') {
1718 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1720 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1723 } elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1724 if ($name_printed) {
1727 eval qq/print "\\t$var;\\n"/;
1730 $deferred .= eval qq/"\\n$expr;\\n"/;
1733 die "panic: do not know how to handle this branch for function pointers"
1735 eval qq/print "$expr;\\n"/;
1740 sub generate_output {
1741 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1742 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1743 local($argoff) = $num - 1;
1746 $type = TidyType($type) ;
1747 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1748 print "\t$arg = sv_newmortal();\n";
1749 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1750 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1752 blurt("Error: '$type' not in typemap"), return
1753 unless defined($type_kind{$type});
1754 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1755 unless defined $output_expr{$type_kind{$type}} ;
1756 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1757 $ntype =~ s/\(\)//g;
1758 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1759 $expr = $output_expr{$type_kind{$type}};
1760 if ($expr =~ /DO_ARRAY_ELEM/) {
1761 blurt("Error: '$subtype' not in typemap"), return
1762 unless defined($type_kind{$subtype});
1763 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1764 unless defined $output_expr{$type_kind{$subtype}} ;
1765 $subexpr = $output_expr{$type_kind{$subtype}};
1766 $subexpr =~ s/ntype/subtype/g;
1767 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1768 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1769 $subexpr =~ s/\n\t/\n\t\t/g;
1770 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1771 eval "print qq\a$expr\a";
1773 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1775 elsif ($var eq 'RETVAL') {
1776 if ($expr =~ /^\t\$arg = new/) {
1777 # We expect that $arg has refcnt 1, so we need to
1779 eval "print qq\a$expr\a";
1781 print "\tsv_2mortal(ST($num));\n";
1782 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1784 elsif ($expr =~ /^\s*\$arg\s*=/) {
1785 # We expect that $arg has refcnt >=1, so we need
1787 eval "print qq\a$expr\a";
1789 print "\tsv_2mortal(ST(0));\n";
1790 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1793 # Just hope that the entry would safely write it
1794 # over an already mortalized value. By
1795 # coincidence, something like $arg = &sv_undef
1797 print "\tST(0) = sv_newmortal();\n";
1798 eval "print qq\a$expr\a";
1800 # new mortals don't have set magic
1804 print "\tPUSHs(sv_newmortal());\n";
1806 eval "print qq\a$expr\a";
1808 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1810 elsif ($arg =~ /^ST\(\d+\)$/) {
1811 eval "print qq\a$expr\a";
1813 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1819 my($type, $varname) = @_;
1821 # C++ has :: in types too so skip this
1822 $type =~ tr/:/_/ unless $hiertype;
1823 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1825 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1826 (substr $type, pos $type, 0) = " $varname ";
1828 $type .= "\t$varname";
1836 # If this is VMS, the exit status has meaning to the shell, so we
1837 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1839 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1840 exit ($errors ? 1 : 0);