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 ;
140 $Fallback = 'PL_sv_undef';
142 my $process_inout = 1;
143 my $process_argtypes = 1;
145 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
148 $spat = quotemeta shift, next SWITCH if $flag eq 's';
149 $cplusplus = 1, next SWITCH if $flag eq 'C++';
150 $hiertype = 1, next SWITCH if $flag eq 'hiertype';
151 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
152 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
153 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
154 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
155 # XXX left this in for compat
156 next SWITCH if $flag eq 'object_capi';
157 $except = " TRY", next SWITCH if $flag eq 'except';
158 push(@tm,shift), next SWITCH if $flag eq 'typemap';
159 $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
160 $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
161 $WantOptimize = 0, next SWITCH if $flag eq 'nooptimize';
162 $WantOptimize = 1, next SWITCH if $flag eq 'optimize';
163 $process_inout = 0, next SWITCH if $flag eq 'noinout';
164 $process_inout = 1, next SWITCH if $flag eq 'inout';
165 $process_argtypes = 0, next SWITCH if $flag eq 'noargtypes';
166 $process_argtypes = 1, next SWITCH if $flag eq 'argtypes';
167 (print "xsubpp version $XSUBPP_version\n"), exit
171 if ($WantPrototypes == -1)
172 { $WantPrototypes = 0}
177 @ARGV == 1 or die $usage;
178 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
179 or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
180 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
181 or ($dir, $filename) = ('.', $ARGV[0]);
185 ++ $IncludedFiles{$ARGV[0]} ;
187 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
188 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
193 $_[0] =~ s/^\s+|\s+$//go ;
200 # rationalise any '*' by joining them into bunches and removing whitespace
204 # change multiple whitespace into a single space
207 # trim leading & trailing whitespace
213 $typemap = shift @ARGV;
214 foreach $typemap (@tm) {
215 die "Can't find $typemap in $pwd\n" unless -r $typemap;
217 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
218 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
220 foreach $typemap (@tm) {
221 next unless -f $typemap ;
222 # skip directories, binary files etc.
223 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
225 open(TYPEMAP, $typemap)
226 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
232 my $line_no = $. + 1;
233 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
234 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
235 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
236 if ($mode eq 'Typemap') {
240 # skip blank lines and comment lines
241 next if /^$/ or /^#/ ;
242 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
243 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
244 $type = TidyType($type) ;
245 $type_kind{$type} = $kind ;
246 # prototype defaults to '$'
247 $proto = "\$" unless $proto ;
248 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
249 unless ValidProtoString($proto) ;
250 $proto_letter{$type} = C_string($proto) ;
255 elsif ($mode eq 'Input') {
257 $input_expr{$_} = '';
258 $current = \$input_expr{$_};
262 $output_expr{$_} = '';
263 $current = \$output_expr{$_};
269 foreach $key (keys %input_expr) {
270 $input_expr{$key} =~ s/;*\s+\z//;
273 $bal = qr[(?:(?>[^()]+)|\((??{ $bal })\))*]; # ()-balanced
274 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
275 $size = qr[,\s* (??{ $bal }) ]x; # Third arg (to setpvn)
277 foreach $key (keys %output_expr) {
280 my ($t, $with_size, $arg, $sarg) =
281 ($output_expr{$key} =~
282 m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
283 \s* \( \s* $cast \$arg \s* ,
284 \s* ( (??{ $bal }) ) # Set from
285 ( (??{ $size }) )? # Possible sizeof set-from
288 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
291 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
293 # Match an XS keyword
294 $BLOCK_re= '\s*(' . join('|', qw(
295 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
296 CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
297 SCOPE INTERFACE INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
300 # Input: ($_, @line) == unparsed input.
301 # Output: ($_, @line) == (rest of line, following lines).
302 # Return: the matched keyword if found, otherwise 0
304 $_ = shift(@line) while !/\S/ && @line;
305 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
308 my ($C_group_rex, $C_arg);
309 # Group in C (no support for comments or literals)
310 $C_group_rex = qr/ [({\[]
311 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
313 # Chunk in C without comma at toplevel (no comments):
314 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
315 | (??{ $C_group_rex })
316 | " (?: (?> [^\\"]+ )
318 )* " # String literal
319 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
322 if ($WantLineNumbers) {
324 package xsubpp::counter;
326 my ($class, $cfile) = @_;
328 $SECTION_END_MARKER = "#line --- \"$cfile\"";
337 while ($$self =~ s/^([^\n]*\n)//) {
340 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
349 $self->PRINT(sprintf($fmt, @_));
353 # Not necessary if we're careful to end with a "\n"
359 my $cfile = $filename;
360 $cfile =~ s/\.xs$/.c/i or $cfile .= ".c";
361 tie(*PSEUDO_STDOUT, 'xsubpp::counter', $cfile);
362 select PSEUDO_STDOUT;
366 # the "do" is required for right semantics
367 do { $_ = shift(@line) } while !/\S/ && @line;
369 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
370 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
371 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
374 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
380 while (!/\S/ && @line) {
384 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
391 sub process_keyword($)
396 &{"${kwd}_handler"}()
397 while $kwd = check_keyword($pattern) ;
401 blurt ("Error: `CASE:' after unconditional `CASE:'")
402 if $condnum && $cond eq '';
404 TrimWhitespace($cond);
405 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
410 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
411 last if /^\s*NOT_IMPLEMENTED_YET/;
412 next unless /\S/; # skip blank lines
417 # remove trailing semicolon if no initialisation
418 s/\s*;$//g unless /[=;+].*\S/ ;
420 # Process the length(foo) declarations
421 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
422 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
423 $lengthof{$2} = $name;
424 # $islengthof{$name} = $1;
425 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;";
428 # check for optional initialisation code
430 $var_init = $1 if s/\s*([=;+].*)$//s ;
431 $var_init =~ s/"/\\"/g;
434 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
435 or blurt("Error: invalid argument declaration '$line'"), next;
437 # Check for duplicate definitions
438 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
439 if $arg_list{$var_name}++
440 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
442 $thisdone |= $var_name eq "THIS";
443 $retvaldone |= $var_name eq "RETVAL";
444 $var_types{$var_name} = $var_type;
445 # XXXX This check is a safeguard against the unfinished conversion of
446 # generate_init(). When generate_init() is fixed,
447 # one can use 2-args map_type() unconditionally.
448 if ($var_type =~ / \( \s* \* \s* \) /x) {
449 # Function pointers are not yet supported with &output_init!
450 print "\t" . &map_type($var_type, $var_name);
453 print "\t" . &map_type($var_type);
456 $var_num = $args_match{$var_name};
458 $proto_arg[$var_num] = ProtoString($var_type)
460 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
461 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
462 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
463 and $var_init !~ /\S/) {
467 print "\t$var_name;\n";
469 } elsif ($var_init =~ /\S/) {
470 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
472 # generate initialization code
473 &generate_init($var_type, $var_num, $var_name, $name_printed);
481 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
483 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
484 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
487 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
488 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
489 if $outargs{$outarg} ++ ;
490 if (!$gotRETVAL and $outarg eq 'RETVAL') {
491 # deal with RETVAL last
492 $RETVAL_code = $outcode ;
496 blurt ("Error: OUTPUT $outarg not an argument"), next
497 unless defined($args_match{$outarg});
498 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
499 unless defined $var_types{$outarg} ;
500 $var_num = $args_match{$outarg};
502 print "\t$outcode\n";
503 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
505 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
507 delete $in_out{$outarg} # No need to auto-OUTPUT
508 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
512 sub C_ARGS_handler() {
513 my $in = merge_section();
519 sub INTERFACE_MACRO_handler() {
520 my $in = merge_section();
523 if ($in =~ /\s/) { # two
524 ($interface_macro, $interface_macro_set) = split ' ', $in;
526 $interface_macro = $in;
527 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
529 $interface = 1; # local
530 $Interfaces = 1; # global
533 sub INTERFACE_handler() {
534 my $in = merge_section();
538 foreach (split /[\s,]+/, $in) {
539 $Interfaces{$_} = $_;
542 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
544 $interface = 1; # local
545 $Interfaces = 1; # global
548 sub CLEANUP_handler() { print_section() }
549 sub PREINIT_handler() { print_section() }
550 sub POSTCALL_handler() { print_section() }
551 sub INIT_handler() { print_section() }
560 # Parse alias definitions
562 # alias = value alias = value ...
564 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
566 $orig_alias = $alias ;
569 # check for optional package definition in the alias
570 $alias = $Packprefix . $alias if $alias !~ /::/ ;
572 # check for duplicate alias name & duplicate value
573 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
574 if defined $XsubAliases{$alias} ;
576 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
577 if $XsubAliasValues{$value} ;
580 $XsubAliases{$alias} = $value ;
581 $XsubAliasValues{$value} = $orig_alias ;
584 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
590 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
593 push @Attributes, $_;
599 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
602 GetAliases($_) if $_ ;
606 sub OVERLOAD_handler()
608 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
611 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
612 $Overload = 1 unless $Overload;
613 my $overload = "$Package\::(".$1 ;
615 " newXS(\"$overload\", XS_$Full_func_name, file$proto);\n");
621 sub FALLBACK_handler()
623 # the rest of the current line should contain either TRUE,
628 TRUE => "PL_sv_yes", 1 => "PL_sv_yes",
629 FALSE => "PL_sv_no", 0 => "PL_sv_no",
630 UNDEF => "PL_sv_undef",
633 # check for valid FALLBACK value
634 death ("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_} ;
636 $Fallback = $map{uc $_} ;
639 sub REQUIRE_handler ()
641 # the rest of the current line should contain a version number
644 TrimWhitespace($Ver) ;
646 death ("Error: REQUIRE expects a version number")
649 # check that the version number is of the form n.n
650 death ("Error: REQUIRE: expected a number, got '$Ver'")
651 unless $Ver =~ /^\d+(\.\d*)?/ ;
653 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
654 unless $XSUBPP_version >= $Ver ;
657 sub VERSIONCHECK_handler ()
659 # the rest of the current line should contain either ENABLE or
664 # check for ENABLE/DISABLE
665 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
666 unless /^(ENABLE|DISABLE)/i ;
668 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
669 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
673 sub PROTOTYPE_handler ()
677 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
678 if $proto_in_this_xsub ++ ;
680 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
684 if ($_ eq 'DISABLE') {
687 elsif ($_ eq 'ENABLE') {
691 # remove any whitespace
693 death("Error: Invalid prototype '$_'")
694 unless ValidProtoString($_) ;
695 $ProtoThisXSUB = C_string($_) ;
699 # If no prototype specified, then assume empty prototype ""
700 $ProtoThisXSUB = 2 unless $specified ;
708 death("Error: Only 1 SCOPE declaration allowed per xsub")
709 if $scope_in_this_xsub ++ ;
711 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
714 if ($_ =~ /^DISABLE/i) {
717 elsif ($_ =~ /^ENABLE/i) {
724 sub PROTOTYPES_handler ()
726 # the rest of the current line should contain either ENABLE or
731 # check for ENABLE/DISABLE
732 death ("Error: PROTOTYPES: ENABLE/DISABLE")
733 unless /^(ENABLE|DISABLE)/i ;
735 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
736 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
741 sub INCLUDE_handler ()
743 # the rest of the current line should contain a valid filename
747 death("INCLUDE: filename missing")
750 death("INCLUDE: output pipe is illegal")
753 # simple minded recursion detector
754 death("INCLUDE loop detected")
755 if $IncludedFiles{$_} ;
757 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
759 # Save the current file context.
762 LastLine => $lastline,
763 LastLineNo => $lastline_no,
766 Filename => $filename,
773 open ($FH, "$_") or death("Cannot open '$_': $!") ;
777 #/* INCLUDE: Including '$_' from '$filename' */
783 # Prime the pump by reading the first
786 # skip leading blank lines
788 last unless /^\s*$/ ;
798 return 0 unless $XSStack[-1]{type} eq 'file' ;
800 my $data = pop @XSStack ;
801 my $ThisFile = $filename ;
802 my $isPipe = ($filename =~ /\|\s*$/) ;
804 -- $IncludedFiles{$filename}
809 $FH = $data->{Handle} ;
810 $filename = $data->{Filename} ;
811 $lastline = $data->{LastLine} ;
812 $lastline_no = $data->{LastLineNo} ;
813 @line = @{ $data->{Line} } ;
814 @line_no = @{ $data->{LineNo} } ;
816 if ($isPipe and $? ) {
818 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
824 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
831 sub ValidProtoString ($)
835 if ( $string =~ /^$proto_re+$/ ) {
846 $string =~ s[\\][\\\\]g ;
854 $proto_letter{$type} or "\$" ;
858 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
860 my ($cpp, $cpplevel);
862 if ($cpp =~ /^\#\s*if/) {
864 } elsif (!$cpplevel) {
865 Warn("Warning: #else/elif/endif without #if in this function");
866 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
867 if $XSStack[-1]{type} eq 'if';
869 } elsif ($cpp =~ /^\#\s*endif/) {
873 Warn("Warning: #if without #endif in this function") if $cpplevel;
886 open($FH, $filename) or die "cannot open $filename: $!\n";
888 # Identify the version of xsubpp used
891 * This file was generated automatically by xsubpp version $XSUBPP_version from the
892 * contents of $filename. Do not edit this file, edit $filename instead.
894 * ANY CHANGES MADE HERE WILL BE LOST!
901 print("#line 1 \"$filename\"\n")
907 my $podstartline = $.;
910 # We can't just write out a /* */ comment, as our embedded
911 # POD might itself be in a comment. We can't put a /**/
912 # comment inside #if 0, as the C standard says that the source
913 # file is decomposed into preprocessing characters in the stage
914 # before preprocessing commands are executed.
915 # I don't want to leave the text as barewords, because the spec
916 # isn't clear whether macros are expanded before or after
917 # preprocessing commands are executed, and someone pathological
918 # may just have defined one of the 3 words as a macro that does
919 # something strange. Multiline strings are illegal in C, so
920 # the "" we write must be a string literal. And they aren't
921 # concatenated until 2 steps later, so we are safe.
922 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
923 printf("#line %d \"$filename\"\n", $. + 1)
929 # At this point $. is at end of file so die won't state the start
930 # of the problem, and as we haven't yet read any lines &death won't
931 # show the correct line in the message either.
932 die ("Error: Unterminated pod in $filename, line $podstartline\n")
935 last if ($Module, $Package, $Prefix) =
936 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
940 &Exit unless defined $_;
942 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
947 # Read next xsub into @line from ($lastline, <$FH>).
950 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
951 if !defined $lastline && $XSStack[-1]{type} eq 'if';
954 return PopFile() if !defined $lastline;
957 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
959 $Package = defined($2) ? $2 : ''; # keep -w happy
960 $Prefix = defined($3) ? $3 : ''; # keep -w happy
961 $Prefix = quotemeta $Prefix ;
962 ($Module_cname = $Module) =~ s/\W/_/g;
963 ($Packid = $Package) =~ tr/:/_/;
964 $Packprefix = $Package;
965 $Packprefix .= "::" if $Packprefix ne "";
971 while ($lastline =~ /^=/) {
972 while ($lastline = <$FH>) {
973 last if ($lastline =~ /^=cut\s*$/);
975 death ("Error: Unterminated pod") unless $lastline;
978 $lastline =~ s/^\s+$//;
980 if ($lastline !~ /^\s*#/ ||
982 # ANSI: if ifdef ifndef elif else endif define undef
984 # gcc: warning include_next
986 # others: ident (gcc notes that some cpps have this one)
987 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
988 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
989 push(@line, $lastline);
990 push(@line_no, $lastline_no) ;
993 # Read next line and continuation lines
994 last unless defined($lastline = <$FH>);
997 $lastline .= $tmp_line
998 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
1001 $lastline =~ s/^\s+$//;
1003 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
1008 while (fetch_para()) {
1009 # Print initial preprocessor statements and blank lines
1010 while (@line && $line[0] !~ /^[^\#]/) {
1011 my $line = shift(@line);
1013 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
1015 if ($statement eq 'if') {
1016 $XSS_work_idx = @XSStack;
1017 push(@XSStack, {type => 'if'});
1019 death ("Error: `$statement' with no matching `if'")
1020 if $XSStack[-1]{type} ne 'if';
1021 if ($XSStack[-1]{varname}) {
1022 push(@InitFileCode, "#endif\n");
1023 push(@BootCode, "#endif");
1026 my(@fns) = keys %{$XSStack[-1]{functions}};
1027 if ($statement ne 'endif') {
1028 # Hide the functions defined in other #if branches, and reset.
1029 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
1030 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
1032 my($tmp) = pop(@XSStack);
1033 0 while (--$XSS_work_idx
1034 && $XSStack[$XSS_work_idx]{type} ne 'if');
1035 # Keep all new defined functions
1036 push(@fns, keys %{$tmp->{other_functions}});
1037 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
1042 next PARAGRAPH unless @line;
1044 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
1045 # We are inside an #if, but have not yet #defined its xsubpp variable.
1046 print "#define $cpp_next_tmp 1\n\n";
1047 push(@InitFileCode, "#if $cpp_next_tmp\n");
1048 push(@BootCode, "#if $cpp_next_tmp");
1049 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
1052 death ("Code is not inside a function"
1053 ." (maybe last function was ended by a blank line "
1054 ." followed by a statement on column one?)")
1055 if $line[0] =~ /^\s/;
1057 # initialize info arrays
1064 undef($wantRETVAL) ;
1065 undef($RETVAL_no_return) ;
1068 undef(@fake_INPUT_pre) ; # For length(s) generated variables
1069 undef(@fake_INPUT) ;
1070 undef($processing_arg_with_types) ;
1071 undef(%argtype_seen) ;
1075 # undef(%islengthof) ;
1076 undef($proto_in_this_xsub) ;
1077 undef($scope_in_this_xsub) ;
1079 undef($prepush_done);
1080 $interface_macro = 'XSINTERFACE_FUNC' ;
1081 $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
1082 $ProtoThisXSUB = $WantPrototypes ;
1087 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE")) {
1088 &{"${kwd}_handler"}() ;
1089 next PARAGRAPH unless @line ;
1093 if (check_keyword("BOOT")) {
1095 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
1096 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
1097 push (@BootCode, @line, "") ;
1102 # extract return type, function name and arguments
1103 ($ret_type) = TidyType($_);
1104 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
1106 # Allow one-line ANSI-like declaration
1108 if $process_argtypes
1109 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
1111 # a function definition needs at least 2 lines
1112 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
1115 $static = 1 if $ret_type =~ s/^static\s+//;
1117 $func_header = shift(@line);
1118 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
1119 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
1121 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
1122 $class = "$4 $class" if $4;
1123 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
1124 ($clean_func_name = $func_name) =~ s/^$Prefix//;
1125 $Full_func_name = "${Packid}_$clean_func_name";
1126 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
1128 # Check for duplicate function definition
1129 for $tmp (@XSStack) {
1130 next unless defined $tmp->{functions}{$Full_func_name};
1131 Warn("Warning: duplicate function definition '$clean_func_name' detected");
1134 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
1135 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
1138 $orig_args =~ s/\\\s*/ /g; # process line continuations
1140 my %only_C_inlist; # Not in the signature of Perl function
1141 if ($process_argtypes and $orig_args =~ /\S/) {
1142 my $args = "$orig_args ,";
1143 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
1144 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
1148 my ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
1149 my ($pre, $name) = ($arg =~ /(.*?) \s*
1150 \b ( \w+ | length\( \s*\w+\s* \) )
1152 next unless length $pre;
1155 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//) {
1157 $out_type = $type if $type ne 'IN';
1158 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1159 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1162 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
1163 $name = "XSauto_length_of_$1";
1165 die "Default value on length() argument: `$_'"
1168 if (length $pre or $islength) { # Has a type
1170 push @fake_INPUT_pre, $arg;
1172 push @fake_INPUT, $arg;
1174 # warn "pushing '$arg'\n";
1175 $argtype_seen{$name}++;
1176 $_ = "$name$default"; # Assigns to @args
1178 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
1179 push @outlist, $name if $out_type =~ /OUTLIST$/;
1180 $in_out{$name} = $out_type if $out_type;
1183 @args = split(/\s*,\s*/, $orig_args);
1184 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
1187 @args = split(/\s*,\s*/, $orig_args);
1189 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\s+//) {
1191 next if $out_type eq 'IN';
1192 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
1193 push @outlist, $name if $out_type =~ /OUTLIST$/;
1194 $in_out{$_} = $out_type;
1198 if (defined($class)) {
1199 my $arg0 = ((defined($static) or $func_name eq 'new')
1200 ? "CLASS" : "THIS");
1201 unshift(@args, $arg0);
1202 ($report_args = "$arg0, $report_args") =~ s/^\w+, $/$arg0/;
1207 my $report_args = '';
1208 foreach $i (0 .. $#args) {
1209 if ($args[$i] =~ s/\.\.\.//) {
1211 if ($args[$i] eq '' && $i == $#args) {
1212 $report_args .= ", ...";
1217 if ($only_C_inlist{$args[$i]}) {
1218 push @args_num, undef;
1220 push @args_num, ++$num_args;
1221 $report_args .= ", $args[$i]";
1223 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
1226 $defaults{$args[$i]} = $2;
1227 $defaults{$args[$i]} =~ s/"/\\"/g;
1229 $proto_arg[$i+1] = "\$" ;
1231 $min_args = $num_args - $extra_args;
1232 $report_args =~ s/"/\\"/g;
1233 $report_args =~ s/^,\s+//;
1234 my @func_args = @args;
1235 shift @func_args if defined($class);
1238 s/^/&/ if $in_out{$_};
1240 $func_args = join(", ", @func_args);
1241 @args_match{@args} = @args_num;
1243 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
1244 $CODE = grep(/^\s*CODE\s*:/, @line);
1245 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
1246 # to set explicit return values.
1247 $EXPLICIT_RETURN = ($CODE &&
1248 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
1249 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
1250 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
1252 $xsreturn = 1 if $EXPLICIT_RETURN;
1254 # print function header
1256 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
1257 #XS(XS_${Full_func_name})
1261 print Q<<"EOF" if $ALIAS ;
1264 print Q<<"EOF" if $INTERFACE ;
1265 # dXSFUNCTION($ret_type);
1268 $cond = ($min_args ? qq(items < $min_args) : 0);
1270 elsif ($min_args == $num_args) {
1271 $cond = qq(items != $min_args);
1274 $cond = qq(items < $min_args || items > $num_args);
1277 print Q<<"EOF" if $except;
1278 # char errbuf[1024];
1283 { print Q<<"EOF" if $cond }
1285 # Perl_croak(aTHX_ "Usage: %s($report_args)", GvNAME(CvGV(cv)));
1288 { print Q<<"EOF" if $cond }
1290 # Perl_croak(aTHX_ "Usage: $pname($report_args)");
1293 #gcc -Wall: if an xsub has no arguments and PPCODE is used
1294 #it is likely none of ST, XSRETURN or XSprePUSH macros are used
1295 #hence `ax' (setup by dXSARGS) is unused
1296 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
1297 #but such a move could break third-party extensions
1298 print Q<<"EOF" if $PPCODE and $num_args == 0;
1299 # PERL_UNUSED_VAR(ax); /* -Wall */
1302 print Q<<"EOF" if $PPCODE;
1306 # Now do a block of some sort.
1309 $cond = ''; # last CASE: condidional
1310 push(@line, "$END:");
1311 push(@line_no, $line_no[-1]);
1315 &CASE_handler if check_keyword("CASE");
1320 # do initialization of input variables
1328 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD") ;
1330 print Q<<"EOF" if $ScopeThisXSUB;
1335 if (!$thisdone && defined($class)) {
1336 if (defined($static) or $func_name eq 'new') {
1338 $var_types{"CLASS"} = "char *";
1339 &generate_init("char *", 1, "CLASS");
1343 $var_types{"THIS"} = "$class *";
1344 &generate_init("$class *", 1, "THIS");
1349 if (/^\s*NOT_IMPLEMENTED_YET/) {
1350 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1353 if ($ret_type ne "void") {
1354 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
1356 $args_match{"RETVAL"} = 0;
1357 $var_types{"RETVAL"} = $ret_type;
1358 print "\tdXSTARG;\n"
1359 if $WantOptimize and $targetable{$type_kind{$ret_type}};
1362 if (@fake_INPUT or @fake_INPUT_pre) {
1363 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
1365 $processing_arg_with_types = 1;
1370 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD") ;
1372 if (check_keyword("PPCODE")) {
1374 death ("PPCODE must be last thing") if @line;
1375 print "\tLEAVE;\n" if $ScopeThisXSUB;
1376 print "\tPUTBACK;\n\treturn;\n";
1377 } elsif (check_keyword("CODE")) {
1379 } elsif (defined($class) and $func_name eq "DESTROY") {
1381 print "delete THIS;\n";
1384 if ($ret_type ne "void") {
1388 if (defined($static)) {
1389 if ($func_name eq 'new') {
1390 $func_name = "$class";
1394 } elsif (defined($class)) {
1395 if ($func_name eq 'new') {
1396 $func_name .= " $class";
1401 $func_name =~ s/^($spat)//
1403 $func_name = 'XSFUNCTION' if $interface;
1404 print "$func_name($func_args);\n";
1408 # do output variables
1409 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
1410 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
1411 # $wantRETVAL set if 'RETVAL =' autogenerated
1412 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
1414 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
1416 &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
1417 for grep $in_out{$_} =~ /OUT$/, keys %in_out;
1419 # all OUTPUT done, so now push the return value on the stack
1420 if ($gotRETVAL && $RETVAL_code) {
1421 print "\t$RETVAL_code\n";
1422 } elsif ($gotRETVAL || $wantRETVAL) {
1423 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
1425 my $type = $ret_type;
1427 # 0: type, 1: with_size, 2: how, 3: how_size
1428 if ($t and not $t->[1] and $t->[0] eq 'p') {
1429 # PUSHp corresponds to setpvn. Treate setpv directly
1430 my $what = eval qq("$t->[2]");
1433 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
1437 my $what = eval qq("$t->[2]");
1441 $size = '' unless defined $size;
1442 $size = eval qq("$size");
1444 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
1448 # RETVAL almost never needs SvSETMAGIC()
1449 &generate_output($ret_type, 0, 'RETVAL', 0);
1453 $xsreturn = 1 if $ret_type ne "void";
1454 my $num = $xsreturn;
1456 print "\tXSprePUSH;" if $c and not $prepush_done;
1457 print "\tEXTEND(SP,$c);\n" if $c;
1459 generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
1462 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD") ;
1464 print Q<<"EOF" if $ScopeThisXSUB;
1467 print Q<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1471 # print function trailer
1475 print Q<<EOF if $except;
1478 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1481 if (check_keyword("CASE")) {
1482 blurt ("Error: No `CASE:' at top of function")
1484 $_ = "CASE: $_"; # Restore CASE: label
1487 last if $_ eq "$END:";
1488 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
1491 print Q<<EOF if $except;
1493 # Perl_croak(aTHX_ errbuf);
1497 print Q<<EOF unless $PPCODE;
1498 # XSRETURN($xsreturn);
1501 print Q<<EOF unless $PPCODE;
1511 my $newXS = "newXS" ;
1514 # Build the prototype string for the xsub
1515 if ($ProtoThisXSUB) {
1516 $newXS = "newXSproto";
1518 if ($ProtoThisXSUB eq 2) {
1519 # User has specified empty prototype
1522 elsif ($ProtoThisXSUB ne 1) {
1523 # User has specified a prototype
1524 $proto = ', "' . $ProtoThisXSUB . '"';
1528 if ($min_args < $num_args) {
1530 $proto_arg[$min_args] .= ";" ;
1532 push @proto_arg, "$s\@"
1535 $proto = ', "' . join ("", @proto_arg) . '"';
1540 $XsubAliases{$pname} = 0
1541 unless defined $XsubAliases{$pname} ;
1542 while ( ($name, $value) = each %XsubAliases) {
1543 push(@InitFileCode, Q<<"EOF");
1544 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1545 # XSANY.any_i32 = $value ;
1547 push(@InitFileCode, Q<<"EOF") if $proto;
1548 # sv_setpv((SV*)cv$proto) ;
1552 elsif (@Attributes) {
1553 push(@InitFileCode, Q<<"EOF");
1554 # cv = newXS(\"$pname\", XS_$Full_func_name, file);
1555 # apply_attrs_string("$Package", cv, "@Attributes", 0);
1558 elsif ($interface) {
1559 while ( ($name, $value) = each %Interfaces) {
1560 $name = "$Package\::$name" unless $name =~ /::/;
1561 push(@InitFileCode, Q<<"EOF");
1562 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1563 # $interface_macro_set(cv,$value) ;
1565 push(@InitFileCode, Q<<"EOF") if $proto;
1566 # sv_setpv((SV*)cv$proto) ;
1572 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1576 if ($Overload) # make it findable with fetchmethod
1580 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
1581 #XS(XS_${Packid}_nil)
1587 unshift(@InitFileCode, <<"MAKE_FETCHMETHOD_WORK");
1588 /* Making a sub named "${Package}::()" allows the package */
1589 /* to be findable via fetchmethod(), and causes */
1590 /* overload::Overloaded("${Package}") to return true. */
1591 newXS("${Package}::()", XS_${Packid}_nil, file$proto);
1592 MAKE_FETCHMETHOD_WORK
1595 # print initialization routine
1604 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1605 #XS(boot_$Module_cname)
1613 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1614 #so `file' is unused
1615 print Q<<"EOF" if $Full_func_name;
1616 # char* file = __FILE__;
1621 print Q<<"EOF" if $WantVersionChk ;
1622 # XS_VERSION_BOOTCHECK ;
1626 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1632 print Q<<"EOF" if ($Overload);
1633 # /* register the overloading (type 'A') magic */
1634 # PL_amagic_generation++;
1635 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1636 # /* mentioned above, and looks in the SV* slot of it for */
1637 # /* the "fallback" status. */
1639 # get_sv( "${Package}::()", TRUE ),
1644 print @InitFileCode;
1646 print Q<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1652 print "\n /* Initialisation Section */\n\n" ;
1655 print "\n /* End of Initialisation Section */\n\n" ;
1664 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1669 local($type, $num, $var, $init, $name_printed) = @_;
1670 local($arg) = "ST(" . ($num - 1) . ")";
1672 if( $init =~ /^=/ ) {
1673 if ($name_printed) {
1674 eval qq/print " $init\\n"/;
1676 eval qq/print "\\t$var $init\\n"/;
1680 if( $init =~ s/^\+// && $num ) {
1681 &generate_init($type, $num, $var, $name_printed);
1682 } elsif ($name_printed) {
1686 eval qq/print "\\t$var;\\n"/;
1690 $deferred .= eval qq/"\\n\\t$init\\n"/;
1697 # work out the line number
1698 my $line_no = $line_no[@line_no - @line -1] ;
1700 print STDERR "@_ in $filename, line $line_no\n" ;
1716 local($type, $num, $var) = @_;
1717 local($arg) = "ST(" . ($num - 1) . ")";
1718 local($argoff) = $num - 1;
1722 $type = TidyType($type) ;
1723 blurt("Error: '$type' not in typemap"), return
1724 unless defined($type_kind{$type});
1726 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1727 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1728 $tk = $type_kind{$type};
1729 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1730 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1731 print "\t$var" unless $name_printed;
1732 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1733 die "default value not supported with length(NAME) supplied"
1734 if defined $defaults{$var};
1737 $type =~ tr/:/_/ unless $hiertype;
1738 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1739 unless defined $input_expr{$tk} ;
1740 $expr = $input_expr{$tk};
1741 if ($expr =~ /DO_ARRAY_ELEM/) {
1742 blurt("Error: '$subtype' not in typemap"), return
1743 unless defined($type_kind{$subtype});
1744 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1745 unless defined $input_expr{$type_kind{$subtype}} ;
1746 $subexpr = $input_expr{$type_kind{$subtype}};
1747 $subexpr =~ s/\$type/\$subtype/g;
1748 $subexpr =~ s/ntype/subtype/g;
1749 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1750 $subexpr =~ s/\n\t/\n\t\t/g;
1751 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1752 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1753 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1755 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1758 if (defined($defaults{$var})) {
1759 $expr =~ s/(\t+)/$1 /g;
1761 if ($name_printed) {
1764 eval qq/print "\\t$var;\\n"/;
1767 if ($defaults{$var} eq 'NO_INIT') {
1768 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1770 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1773 } elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1774 if ($name_printed) {
1777 eval qq/print "\\t$var;\\n"/;
1780 $deferred .= eval qq/"\\n$expr;\\n"/;
1783 die "panic: do not know how to handle this branch for function pointers"
1785 eval qq/print "$expr;\\n"/;
1790 sub generate_output {
1791 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1792 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1793 local($argoff) = $num - 1;
1796 $type = TidyType($type) ;
1797 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1798 print "\t$arg = sv_newmortal();\n";
1799 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1800 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1802 blurt("Error: '$type' not in typemap"), return
1803 unless defined($type_kind{$type});
1804 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1805 unless defined $output_expr{$type_kind{$type}} ;
1806 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1807 $ntype =~ s/\(\)//g;
1808 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1809 $expr = $output_expr{$type_kind{$type}};
1810 if ($expr =~ /DO_ARRAY_ELEM/) {
1811 blurt("Error: '$subtype' not in typemap"), return
1812 unless defined($type_kind{$subtype});
1813 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1814 unless defined $output_expr{$type_kind{$subtype}} ;
1815 $subexpr = $output_expr{$type_kind{$subtype}};
1816 $subexpr =~ s/ntype/subtype/g;
1817 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1818 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1819 $subexpr =~ s/\n\t/\n\t\t/g;
1820 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1821 eval "print qq\a$expr\a";
1823 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1825 elsif ($var eq 'RETVAL') {
1826 if ($expr =~ /^\t\$arg = new/) {
1827 # We expect that $arg has refcnt 1, so we need to
1829 eval "print qq\a$expr\a";
1831 print "\tsv_2mortal(ST($num));\n";
1832 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1834 elsif ($expr =~ /^\s*\$arg\s*=/) {
1835 # We expect that $arg has refcnt >=1, so we need
1837 eval "print qq\a$expr\a";
1839 print "\tsv_2mortal(ST(0));\n";
1840 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1843 # Just hope that the entry would safely write it
1844 # over an already mortalized value. By
1845 # coincidence, something like $arg = &sv_undef
1847 print "\tST(0) = sv_newmortal();\n";
1848 eval "print qq\a$expr\a";
1850 # new mortals don't have set magic
1854 print "\tPUSHs(sv_newmortal());\n";
1856 eval "print qq\a$expr\a";
1858 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1860 elsif ($arg =~ /^ST\(\d+\)$/) {
1861 eval "print qq\a$expr\a";
1863 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1869 my($type, $varname) = @_;
1871 # C++ has :: in types too so skip this
1872 $type =~ tr/:/_/ unless $hiertype;
1873 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1875 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1876 (substr $type, pos $type, 0) = " $varname ";
1878 $type .= "\t$varname";
1886 # If this is VMS, the exit status has meaning to the shell, so we
1887 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1889 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1890 exit ($errors ? 1 : 0);