2 eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
3 if $running_under_some_shell;
8 xsubpp - compiler to convert Perl XS code into C code
12 B<xsubpp> [B<-v>] [B<-C++>] [B<-csuffix csuffix>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-nolinenumbers>] [B<-nooptimize>] [B<-typemap typemap>] ... file.xs
16 This compiler is typically run by the makefiles created by L<ExtUtils::MakeMaker>.
18 I<xsubpp> will compile XS code into C code by embedding the constructs
19 necessary to let C functions manipulate Perl values and creates the glue
20 necessary to let Perl access those functions. The compiler uses typemaps to
21 determine how to map C function parameters and variables to Perl values.
23 The compiler will search for typemap files called I<typemap>. It will use
24 the following search path to find default typemaps, with the rightmost
25 typemap taking precedence.
27 ../../../typemap:../../typemap:../typemap:typemap
31 Note that the C<XSOPT> MakeMaker option may be used to add these options to
32 any makefiles generated by MakeMaker.
38 Adds ``extern "C"'' to the C code.
40 =item B<-csuffix csuffix>
42 Set the suffix used for the generated C or C++ code. Defaults to '.c'
43 (even with B<-C++>), but some platforms might want to have e.g. '.cpp'.
44 Don't forget the '.' from the front.
48 Retains '::' in type names so that C++ hierachical types can be mapped.
52 Adds exception handling stubs to the C code.
54 =item B<-typemap typemap>
56 Indicates that a user-supplied typemap should take precedence over the
57 default typemaps. This option may be used multiple times, with the last
58 typemap having the highest precedence.
62 Prints the I<xsubpp> version number to standard output, then exits.
66 By default I<xsubpp> will not automatically generate prototype code for
67 all xsubs. This flag will enable prototypes.
69 =item B<-noversioncheck>
71 Disables the run time test that determines if the object file (derived
72 from the C<.xs> file) and the C<.pm> files have the same version
75 =item B<-nolinenumbers>
77 Prevents the inclusion of `#line' directives in the output.
81 Disables certain optimizations. The only optimization that is currently
82 affected is the use of I<target>s by the output C code (see L<perlguts>).
83 This may significantly slow down the generated code, but this is the way
84 B<xsubpp> of 5.005 and earlier operated.
88 Disable recognition of C<IN>, C<OUT_LIST> and C<INOUT_LIST> declarations.
92 Disable recognition of ANSI-like descriptions of function signature.
98 No environment variables are used.
104 =head1 MODIFICATION HISTORY
106 See the file F<changes.pod>.
110 perl(1), perlxs(1), perlxstut(1)
116 use vars
qw($cplusplus $hiertype);
125 $XSUBPP_version = "1.9508";
127 my ($Is_VMS, $SymSet);
130 # Establish set of global symbols with max length 28, since xsubpp
131 # will later add the 'XS_' prefix.
132 require ExtUtils::XSSymSet;
133 $SymSet = new ExtUtils::XSSymSet 28;
138 $usage = "Usage: xsubpp [-v] [-C++] [-csuffix csuffix] [-except] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-noinout] [-noargtypes] [-s pattern] [-typemap typemap]... file.xs\n";
140 $proto_re = "[" . quotemeta('\$%&*@;[]') . "]" ;
143 $WantPrototypes = -1 ;
144 $WantVersionChk = 1 ;
146 $WantLineNumbers = 1 ;
149 $Fallback = 'PL_sv_undef';
151 my $process_inout = 1;
152 my $process_argtypes = 1;
155 SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
158 $spat = quotemeta shift, next SWITCH if $flag eq 's';
159 $cplusplus = 1, next SWITCH if $flag eq 'C++';
160 $csuffix = shift, next SWITCH if $flag eq 'csuffix';
161 $hiertype = 1, next SWITCH if $flag eq 'hiertype';
162 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
163 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
164 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
165 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
166 # XXX left this in for compat
167 next SWITCH if $flag eq 'object_capi';
168 $except = " TRY", next SWITCH if $flag eq 'except';
169 push(@tm,shift), next SWITCH if $flag eq 'typemap';
170 $WantLineNumbers = 0, next SWITCH if $flag eq 'nolinenumbers';
171 $WantLineNumbers = 1, next SWITCH if $flag eq 'linenumbers';
172 $WantOptimize = 0, next SWITCH if $flag eq 'nooptimize';
173 $WantOptimize = 1, next SWITCH if $flag eq 'optimize';
174 $process_inout = 0, next SWITCH if $flag eq 'noinout';
175 $process_inout = 1, next SWITCH if $flag eq 'inout';
176 $process_argtypes = 0, next SWITCH if $flag eq 'noargtypes';
177 $process_argtypes = 1, next SWITCH if $flag eq 'argtypes';
178 (print "xsubpp version $XSUBPP_version\n"), exit
182 if ($WantPrototypes == -1)
183 { $WantPrototypes = 0}
188 @ARGV == 1 or die $usage;
189 ($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
190 or ($dir, $filename) = $ARGV[0] =~ m#(.*)\\(.*)#
191 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
192 or ($dir, $filename) = ('.', $ARGV[0]);
196 ++ $IncludedFiles{$ARGV[0]} ;
198 my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
199 my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
204 $_[0] =~ s/^\s+|\s+$//go ;
211 # rationalise any '*' by joining them into bunches and removing whitespace
215 # change multiple whitespace into a single space
218 # trim leading & trailing whitespace
224 $typemap = shift @ARGV;
225 foreach $typemap (@tm) {
226 die "Can't find $typemap in $pwd\n" unless -r $typemap;
228 unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
229 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
231 foreach $typemap (@tm) {
232 next unless -f
$typemap ;
233 # skip directories, binary files etc.
234 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
236 open(TYPEMAP
, $typemap)
237 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
243 my $line_no = $. + 1;
244 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \
$junk; next; }
245 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \
$junk; next; }
246 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \
$junk; next; }
247 if ($mode eq 'Typemap') {
251 # skip blank lines and comment lines
252 next if /^$/ or /^#/ ;
253 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
254 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
255 $type = TidyType
($type) ;
256 $type_kind{$type} = $kind ;
257 # prototype defaults to '$'
258 $proto = "\$" unless $proto ;
259 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
260 unless ValidProtoString
($proto) ;
261 $proto_letter{$type} = C_string
($proto) ;
266 elsif ($mode eq 'Input') {
268 $input_expr{$_} = '';
269 $current = \
$input_expr{$_};
273 $output_expr{$_} = '';
274 $current = \
$output_expr{$_};
280 foreach $key (keys %input_expr) {
281 $input_expr{$key} =~ s/;*\s+\z//;
284 $bal = qr
[(?
:(?
>[^()]+)|\
((??
{ $bal })\
))*]; # ()-balanced
285 $cast = qr
[(?
:\
(\s
*SV\s
*\
*\s
*\
)\s
*)?
]; # Optional (SV*) cast
286 $size = qr
[,\s
* (??
{ $bal }) ]x
; # Third arg (to setpvn)
288 foreach $key (keys %output_expr) {
291 my ($t, $with_size, $arg, $sarg) =
292 ($output_expr{$key} =~
293 m
[^ \s
+ sv_set
( [iunp
] ) v
(n
)?
# Type, is_setpvn
294 \s
* \
( \s
* $cast \
$arg \s
* ,
295 \s
* ( (??
{ $bal }) ) # Set from
296 ( (??
{ $size }) )?
# Possible sizeof set-from
299 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
302 $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
304 # Match an XS keyword
305 $BLOCK_re= '\s*(' . join('|', qw(
306 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
307 CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
308 SCOPE INTERFACE INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
311 # Input: ($_, @line) == unparsed input.
312 # Output: ($_, @line) == (rest of line, following lines).
313 # Return: the matched keyword if found, otherwise 0
315 $_ = shift(@line) while !/\S/ && @line;
316 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
319 my ($C_group_rex, $C_arg);
320 # Group in C (no support for comments or literals)
321 $C_group_rex = qr
/ [({\
[]
322 (?
: (?
> [^()\
[\
]{}]+ ) | (??
{ $C_group_rex }) )*
324 # Chunk in C without comma at toplevel (no comments):
325 $C_arg = qr
/ (?
: (?
> [^()\
[\
]{},"']+ )
326 | (??{ $C_group_rex })
327 | " (?
: (?
> [^\\"]+ )
329 )* " # String literal
330 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
333 if ($WantLineNumbers) {
335 package xsubpp::counter;
337 my ($class, $cfile) = @_;
339 $SECTION_END_MARKER = "#line --- \"$cfile\"";
348 while ($$self =~ s/^([^\n]*\n)//) {
351 $line =~ s|^\#line\s+---(?=\s)|#line $line_no|;
360 $self->PRINT(sprintf($fmt, @_));
364 # Not necessary if we're careful to end with a
"\n"
370 my $cfile = $filename;
371 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
372 tie
(*PSEUDO_STDOUT
, 'xsubpp::counter', $cfile);
373 select PSEUDO_STDOUT
;
377 # the "do" is required for right semantics
378 do { $_ = shift(@line) } while !/\S/ && @line;
380 print("#line ", $line_no[@line_no - @line -1], " \"$filename\"\n")
381 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
382 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
385 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
391 while (!/\S/ && @line) {
395 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
402 sub process_keyword
($)
407 &{"${kwd}_handler"}()
408 while $kwd = check_keyword
($pattern) ;
412 blurt
("Error: `CASE:' after unconditional `CASE:'")
413 if $condnum && $cond eq '';
415 TrimWhitespace
($cond);
416 print " ", ($condnum++ ?
" else" : ""), ($cond ?
" if ($cond)\n" : "\n");
421 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
422 last if /^\s*NOT_IMPLEMENTED_YET/;
423 next unless /\S/; # skip blank lines
428 # remove trailing semicolon if no initialisation
429 s/\s*;$//g unless /[=;+].*\S/ ;
431 # Process the length(foo) declarations
432 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
433 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
434 $lengthof{$2} = $name;
435 # $islengthof{$name} = $1;
436 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;";
439 # check for optional initialisation code
441 $var_init = $1 if s/\s*([=;+].*)$//s ;
442 $var_init =~ s/"/\\"/g;
445 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
446 or blurt
("Error: invalid argument declaration '$line'"), next;
448 # Check for duplicate definitions
449 blurt
("Error: duplicate definition of argument '$var_name' ignored"), next
450 if $arg_list{$var_name}++
451 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
453 $thisdone |= $var_name eq "THIS";
454 $retvaldone |= $var_name eq "RETVAL";
455 $var_types{$var_name} = $var_type;
456 # XXXX This check is a safeguard against the unfinished conversion of
457 # generate_init(). When generate_init() is fixed,
458 # one can use 2-args map_type() unconditionally.
459 if ($var_type =~ / \( \s* \* \s* \) /x) {
460 # Function pointers are not yet supported with &output_init!
461 print "\t" . &map_type
($var_type, $var_name);
464 print "\t" . &map_type
($var_type);
467 $var_num = $args_match{$var_name};
469 $proto_arg[$var_num] = ProtoString
($var_type)
471 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
472 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
473 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
474 and $var_init !~ /\S/) {
478 print "\t$var_name;\n";
480 } elsif ($var_init =~ /\S/) {
481 &output_init
($var_type, $var_num, $var_name, $var_init, $name_printed);
483 # generate initialization code
484 &generate_init
($var_type, $var_num, $var_name, $name_printed);
492 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
494 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
495 $DoSetMagic = ($1 eq "ENABLE" ?
1 : 0);
498 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
499 blurt
("Error: duplicate OUTPUT argument '$outarg' ignored"), next
500 if $outargs{$outarg} ++ ;
501 if (!$gotRETVAL and $outarg eq 'RETVAL') {
502 # deal with RETVAL last
503 $RETVAL_code = $outcode ;
507 blurt
("Error: OUTPUT $outarg not an argument"), next
508 unless defined($args_match{$outarg});
509 blurt
("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
510 unless defined $var_types{$outarg} ;
511 $var_num = $args_match{$outarg};
513 print "\t$outcode\n";
514 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
516 &generate_output
($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
518 delete $in_out{$outarg} # No need to auto-OUTPUT
519 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
523 sub C_ARGS_handler
() {
524 my $in = merge_section
();
530 sub INTERFACE_MACRO_handler
() {
531 my $in = merge_section
();
534 if ($in =~ /\s/) { # two
535 ($interface_macro, $interface_macro_set) = split ' ', $in;
537 $interface_macro = $in;
538 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
540 $interface = 1; # local
541 $Interfaces = 1; # global
544 sub INTERFACE_handler
() {
545 my $in = merge_section
();
549 foreach (split /[\s,]+/, $in) {
550 $Interfaces{$_} = $_;
553 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
555 $interface = 1; # local
556 $Interfaces = 1; # global
559 sub CLEANUP_handler
() { print_section
() }
560 sub PREINIT_handler
() { print_section
() }
561 sub POSTCALL_handler
() { print_section
() }
562 sub INIT_handler
() { print_section
() }
571 # Parse alias definitions
573 # alias = value alias = value ...
575 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
577 $orig_alias = $alias ;
580 # check for optional package definition in the alias
581 $alias = $Packprefix . $alias if $alias !~ /::/ ;
583 # check for duplicate alias name & duplicate value
584 Warn
("Warning: Ignoring duplicate alias '$orig_alias'")
585 if defined $XsubAliases{$alias} ;
587 Warn
("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
588 if $XsubAliasValues{$value} ;
591 $XsubAliases{$alias} = $value ;
592 $XsubAliasValues{$value} = $orig_alias ;
595 blurt
("Error: Cannot parse ALIAS definitions from '$orig'")
601 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
604 push @Attributes, $_;
610 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
613 GetAliases
($_) if $_ ;
617 sub OVERLOAD_handler
()
619 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
622 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
623 $Overload = 1 unless $Overload;
624 my $overload = "$Package\::(".$1 ;
626 " newXS(\"$overload\", XS_$Full_func_name, file$proto);\n");
632 sub FALLBACK_handler
()
634 # the rest of the current line should contain either TRUE,
639 TRUE
=> "PL_sv_yes", 1 => "PL_sv_yes",
640 FALSE
=> "PL_sv_no", 0 => "PL_sv_no",
641 UNDEF
=> "PL_sv_undef",
644 # check for valid FALLBACK value
645 death
("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_} ;
647 $Fallback = $map{uc $_} ;
650 sub REQUIRE_handler
()
652 # the rest of the current line should contain a version number
655 TrimWhitespace
($Ver) ;
657 death
("Error: REQUIRE expects a version number")
660 # check that the version number is of the form n.n
661 death
("Error: REQUIRE: expected a number, got '$Ver'")
662 unless $Ver =~ /^\d+(\.\d*)?/ ;
664 death
("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
665 unless $XSUBPP_version >= $Ver ;
668 sub VERSIONCHECK_handler
()
670 # the rest of the current line should contain either ENABLE or
675 # check for ENABLE/DISABLE
676 death
("Error: VERSIONCHECK: ENABLE/DISABLE")
677 unless /^(ENABLE|DISABLE)/i ;
679 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
680 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
684 sub PROTOTYPE_handler
()
688 death
("Error: Only 1 PROTOTYPE definition allowed per xsub")
689 if $proto_in_this_xsub ++ ;
691 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
695 if ($_ eq 'DISABLE') {
698 elsif ($_ eq 'ENABLE') {
702 # remove any whitespace
704 death
("Error: Invalid prototype '$_'")
705 unless ValidProtoString
($_) ;
706 $ProtoThisXSUB = C_string
($_) ;
710 # If no prototype specified, then assume empty prototype ""
711 $ProtoThisXSUB = 2 unless $specified ;
719 death
("Error: Only 1 SCOPE declaration allowed per xsub")
720 if $scope_in_this_xsub ++ ;
722 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
725 if ($_ =~ /^DISABLE/i) {
728 elsif ($_ =~ /^ENABLE/i) {
735 sub PROTOTYPES_handler
()
737 # the rest of the current line should contain either ENABLE or
742 # check for ENABLE/DISABLE
743 death
("Error: PROTOTYPES: ENABLE/DISABLE")
744 unless /^(ENABLE|DISABLE)/i ;
746 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
747 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
752 sub INCLUDE_handler
()
754 # the rest of the current line should contain a valid filename
758 death
("INCLUDE: filename missing")
761 death
("INCLUDE: output pipe is illegal")
764 # simple minded recursion detector
765 death
("INCLUDE loop detected")
766 if $IncludedFiles{$_} ;
768 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
770 # Save the current file context.
773 LastLine
=> $lastline,
774 LastLineNo
=> $lastline_no,
777 Filename
=> $filename,
784 open ($FH, "$_") or death
("Cannot open '$_': $!") ;
788 #/* INCLUDE: Including '$_' from '$filename' */
794 # Prime the pump by reading the first
797 # skip leading blank lines
799 last unless /^\s*$/ ;
809 return 0 unless $XSStack[-1]{type
} eq 'file' ;
811 my $data = pop @XSStack ;
812 my $ThisFile = $filename ;
813 my $isPipe = ($filename =~ /\|\s*$/) ;
815 -- $IncludedFiles{$filename}
820 $FH = $data->{Handle
} ;
821 $filename = $data->{Filename
} ;
822 $lastline = $data->{LastLine
} ;
823 $lastline_no = $data->{LastLineNo
} ;
824 @line = @
{ $data->{Line
} } ;
825 @line_no = @
{ $data->{LineNo
} } ;
827 if ($isPipe and $?
) {
829 print STDERR
"Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
835 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
842 sub ValidProtoString
($)
846 if ( $string =~ /^$proto_re+$/ ) {
857 $string =~ s
[\\][\\\\]g
;
865 $proto_letter{$type} or "\$" ;
869 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
871 my ($cpp, $cpplevel);
873 if ($cpp =~ /^\#\s*if/) {
875 } elsif (!$cpplevel) {
876 Warn
("Warning: #else/elif/endif without #if in this function");
877 print STDERR
" (precede it with a blank line if the matching #if is outside the function)\n"
878 if $XSStack[-1]{type
} eq 'if';
880 } elsif ($cpp =~ /^\#\s*endif/) {
884 Warn
("Warning: #if without #endif in this function") if $cpplevel;
897 open($FH, $filename) or die "cannot open $filename: $!\n";
899 # Identify the version of xsubpp used
902 * This file was generated automatically by xsubpp version $XSUBPP_version from the
903 * contents of $filename. Do not edit this file, edit $filename instead.
905 * ANY CHANGES MADE HERE WILL BE LOST!
912 print("#line 1 \"$filename\"\n")
918 my $podstartline = $.;
921 # We can't just write out a /* */ comment, as our embedded
922 # POD might itself be in a comment. We can't put a /**/
923 # comment inside #if 0, as the C standard says that the source
924 # file is decomposed into preprocessing characters in the stage
925 # before preprocessing commands are executed.
926 # I don't want to leave the text as barewords, because the spec
927 # isn't clear whether macros are expanded before or after
928 # preprocessing commands are executed, and someone pathological
929 # may just have defined one of the 3 words as a macro that does
930 # something strange. Multiline strings are illegal in C, so
931 # the "" we write must be a string literal. And they aren't
932 # concatenated until 2 steps later, so we are safe.
933 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
934 printf("#line %d \"$filename\"\n", $. + 1)
940 # At this point $. is at end of file so die won't state the start
941 # of the problem, and as we haven't yet read any lines &death won't
942 # show the correct line in the message either.
943 die ("Error: Unterminated pod in $filename, line $podstartline\n")
946 last if ($Module, $Package, $Prefix) =
947 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
951 &Exit
unless defined $_;
953 print "$xsubpp::counter::SECTION_END_MARKER\n" if $WantLineNumbers;
958 # Read next xsub into @line from ($lastline, <$FH>).
961 death
("Error: Unterminated `#if/#ifdef/#ifndef'")
962 if !defined $lastline && $XSStack[-1]{type
} eq 'if';
965 return PopFile
() if !defined $lastline;
968 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
970 $Package = defined($2) ?
$2 : ''; # keep -w happy
971 $Prefix = defined($3) ?
$3 : ''; # keep -w happy
972 $Prefix = quotemeta $Prefix ;
973 ($Module_cname = $Module) =~ s/\W/_/g;
974 ($Packid = $Package) =~ tr/:/_/;
975 $Packprefix = $Package;
976 $Packprefix .= "::" if $Packprefix ne "";
982 while ($lastline =~ /^=/) {
983 while ($lastline = <$FH>) {
984 last if ($lastline =~ /^=cut\s*$/);
986 death
("Error: Unterminated pod") unless $lastline;
989 $lastline =~ s/^\s+$//;
991 if ($lastline !~ /^\s*#/ ||
993 # ANSI: if ifdef ifndef elif else endif define undef
995 # gcc: warning include_next
997 # others: ident (gcc notes that some cpps have this one)
998 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
999 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
1000 push(@line, $lastline);
1001 push(@line_no, $lastline_no) ;
1004 # Read next line and continuation lines
1005 last unless defined($lastline = <$FH>);
1008 $lastline .= $tmp_line
1009 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
1012 $lastline =~ s/^\s+$//;
1014 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
1019 while (fetch_para
()) {
1020 # Print initial preprocessor statements and blank lines
1021 while (@line && $line[0] !~ /^[^\#]/) {
1022 my $line = shift(@line);
1024 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
1026 if ($statement eq 'if') {
1027 $XSS_work_idx = @XSStack;
1028 push(@XSStack, {type
=> 'if'});
1030 death
("Error: `$statement' with no matching `if'")
1031 if $XSStack[-1]{type
} ne 'if';
1032 if ($XSStack[-1]{varname
}) {
1033 push(@InitFileCode, "#endif\n");
1034 push(@BootCode, "#endif");
1037 my(@fns) = keys %{$XSStack[-1]{functions
}};
1038 if ($statement ne 'endif') {
1039 # Hide the functions defined in other #if branches, and reset.
1040 @
{$XSStack[-1]{other_functions
}}{@fns} = (1) x
@fns;
1041 @
{$XSStack[-1]}{qw(varname functions)} = ('', {});
1043 my($tmp) = pop(@XSStack);
1044 0 while (--$XSS_work_idx
1045 && $XSStack[$XSS_work_idx]{type
} ne 'if');
1046 # Keep all new defined functions
1047 push(@fns, keys %{$tmp->{other_functions
}});
1048 @
{$XSStack[$XSS_work_idx]{functions
}}{@fns} = (1) x
@fns;
1053 next PARAGRAPH
unless @line;
1055 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname
}) {
1056 # We are inside an #if, but have not yet #defined its xsubpp variable.
1057 print "#define $cpp_next_tmp 1\n\n";
1058 push(@InitFileCode, "#if $cpp_next_tmp\n");
1059 push(@BootCode, "#if $cpp_next_tmp");
1060 $XSStack[$XSS_work_idx]{varname
} = $cpp_next_tmp++;
1063 death
("Code is not inside a function"
1064 ." (maybe last function was ended by a blank line "
1065 ." followed by a statement on column one?)")
1066 if $line[0] =~ /^\s/;
1068 # initialize info arrays
1076 undef($wantRETVAL) ;
1077 undef($RETVAL_no_return) ;
1080 undef(@fake_INPUT_pre) ; # For length(s) generated variables
1081 undef(@fake_INPUT) ;
1082 undef($processing_arg_with_types) ;
1083 undef(%argtype_seen) ;
1087 # undef(%islengthof) ;
1088 undef($proto_in_this_xsub) ;
1089 undef($scope_in_this_xsub) ;
1091 undef($prepush_done);
1092 $interface_macro = 'XSINTERFACE_FUNC' ;
1093 $interface_macro_set = 'XSINTERFACE_FUNC_SET' ;
1094 $ProtoThisXSUB = $WantPrototypes ;
1099 while ($kwd = check_keyword
("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE")) {
1100 &{"${kwd}_handler"}() ;
1101 next PARAGRAPH
unless @line ;
1105 if (check_keyword
("BOOT")) {
1107 push (@BootCode, "#line $line_no[@line_no - @line] \"$filename\"")
1108 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
1109 push (@BootCode, @line, "") ;
1114 # extract return type, function name and arguments
1115 ($ret_type) = TidyType
($_);
1116 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
1118 # Allow one-line ANSI-like declaration
1120 if $process_argtypes
1121 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
1123 # a function definition needs at least 2 lines
1124 blurt
("Error: Function definition too short '$ret_type'"), next PARAGRAPH
1127 $externC = 1 if $ret_type =~ s/^extern "C"\s+//;
1128 $static = 1 if $ret_type =~ s/^static\s+//;
1130 $func_header = shift(@line);
1131 blurt
("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
1132 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
1134 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
1135 $class = "$4 $class" if $4;
1136 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
1137 ($clean_func_name = $func_name) =~ s/^$Prefix//;
1138 $Full_func_name = "${Packid}_$clean_func_name";
1139 if ($Is_VMS) { $Full_func_name = $SymSet->addsym($Full_func_name); }
1141 # Check for duplicate function definition
1142 for $tmp (@XSStack) {
1143 next unless defined $tmp->{functions
}{$Full_func_name};
1144 Warn
("Warning: duplicate function definition '$clean_func_name' detected");
1147 $XSStack[$XSS_work_idx]{functions
}{$Full_func_name} ++ ;
1148 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
1151 $orig_args =~ s/\\\s*/ /g; # process line continuations
1153 my %only_C_inlist; # Not in the signature of Perl function
1154 if ($process_argtypes and $orig_args =~ /\S/) {
1155 my $args = "$orig_args ,";
1156 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
1157 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
1161 my ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
1162 my ($pre, $name) = ($arg =~ /(.*?
) \s
*
1163 \b ( \w
+ | length\
( \s
*\w
+\s
* \
) )
1165 next unless length $pre;
1168 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//) {
1170 $out_type = $type if $type ne 'IN';
1171 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1172 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\s+//;
1175 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
1176 $name = "XSauto_length_of_$1";
1178 die "Default value on length() argument: `$_'"
1181 if (length $pre or $islength) { # Has a type
1183 push @fake_INPUT_pre, $arg;
1185 push @fake_INPUT, $arg;
1187 # warn "pushing '$arg'\n";
1188 $argtype_seen{$name}++;
1189 $_ = "$name$default"; # Assigns to @args
1191 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
1192 push @outlist, $name if $out_type =~ /OUTLIST$/;
1193 $in_out{$name} = $out_type if $out_type;
1196 @args = split(/\s*,\s*/, $orig_args);
1197 Warn
("Warning: cannot parse argument list '$orig_args', fallback to split");
1200 @args = split(/\s*,\s*/, $orig_args);
1202 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\s+//) {
1204 next if $out_type eq 'IN';
1205 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
1206 push @outlist, $name if $out_type =~ /OUTLIST$/;
1207 $in_out{$_} = $out_type;
1211 if (defined($class)) {
1212 my $arg0 = ((defined($static) or $func_name eq 'new')
1213 ?
"CLASS" : "THIS");
1214 unshift(@args, $arg0);
1215 ($report_args = "$arg0, $report_args") =~ s/^\w+, $/$arg0/;
1220 my $report_args = '';
1221 foreach $i (0 .. $#args) {
1222 if ($args[$i] =~ s/\.\.\.//) {
1224 if ($args[$i] eq '' && $i == $#args) {
1225 $report_args .= ", ...";
1230 if ($only_C_inlist{$args[$i]}) {
1231 push @args_num, undef;
1233 push @args_num, ++$num_args;
1234 $report_args .= ", $args[$i]";
1236 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
1239 $defaults{$args[$i]} = $2;
1240 $defaults{$args[$i]} =~ s/"/\\"/g;
1242 $proto_arg[$i+1] = "\$" ;
1244 $min_args = $num_args - $extra_args;
1245 $report_args =~ s/"/\\"/g;
1246 $report_args =~ s/^,\s+//;
1247 my @func_args = @args;
1248 shift @func_args if defined($class);
1251 s/^/&/ if $in_out{$_};
1253 $func_args = join(", ", @func_args);
1254 @args_match{@args} = @args_num;
1256 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
1257 $CODE = grep(/^\s*CODE\s*:/, @line);
1258 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
1259 # to set explicit return values.
1260 $EXPLICIT_RETURN = ($CODE &&
1261 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
1262 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
1263 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
1265 $xsreturn = 1 if $EXPLICIT_RETURN;
1267 $externC = $externC ?
qq[extern
"C"] : "";
1269 # print function header
1272 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
1273 #XS(XS_${Full_func_name})
1277 print Q
<<"EOF" if $ALIAS ;
1280 print Q
<<"EOF" if $INTERFACE ;
1281 # dXSFUNCTION($ret_type);
1284 $cond = ($min_args ?
qq(items
< $min_args) : 0);
1286 elsif ($min_args == $num_args) {
1287 $cond = qq(items
!= $min_args);
1290 $cond = qq(items
< $min_args || items
> $num_args);
1293 print Q
<<"EOF" if $except;
1294 # char errbuf[1024];
1299 { print Q
<<"EOF" if $cond }
1301 # Perl_croak(aTHX_ "Usage: %s($report_args)", GvNAME(CvGV(cv)));
1304 { print Q
<<"EOF" if $cond }
1306 # Perl_croak(aTHX_ "Usage: $pname($report_args)");
1309 #gcc -Wall: if an xsub has no arguments and PPCODE is used
1310 #it is likely none of ST, XSRETURN or XSprePUSH macros are used
1311 #hence `ax' (setup by dXSARGS) is unused
1312 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
1313 #but such a move could break third-party extensions
1314 print Q
<<"EOF" if $PPCODE and $num_args == 0;
1315 # PERL_UNUSED_VAR(ax); /* -Wall */
1318 print Q
<<"EOF" if $PPCODE;
1322 # Now do a block of some sort.
1325 $cond = ''; # last CASE: condidional
1326 push(@line, "$END:");
1327 push(@line_no, $line_no[-1]);
1331 &CASE_handler
if check_keyword
("CASE");
1336 # do initialization of input variables
1344 process_keyword
("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD") ;
1346 print Q
<<"EOF" if $ScopeThisXSUB;
1351 if (!$thisdone && defined($class)) {
1352 if (defined($static) or $func_name eq 'new') {
1354 $var_types{"CLASS"} = "char *";
1355 &generate_init
("char *", 1, "CLASS");
1359 $var_types{"THIS"} = "$class *";
1360 &generate_init
("$class *", 1, "THIS");
1365 if (/^\s*NOT_IMPLEMENTED_YET/) {
1366 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
1369 if ($ret_type ne "void") {
1370 print "\t" . &map_type
($ret_type, 'RETVAL') . ";\n"
1372 $args_match{"RETVAL"} = 0;
1373 $var_types{"RETVAL"} = $ret_type;
1374 print "\tdXSTARG;\n"
1375 if $WantOptimize and $targetable{$type_kind{$ret_type}};
1378 if (@fake_INPUT or @fake_INPUT_pre) {
1379 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
1381 $processing_arg_with_types = 1;
1386 process_keyword
("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD") ;
1388 if (check_keyword
("PPCODE")) {
1390 death
("PPCODE must be last thing") if @line;
1391 print "\tLEAVE;\n" if $ScopeThisXSUB;
1392 print "\tPUTBACK;\n\treturn;\n";
1393 } elsif (check_keyword
("CODE")) {
1395 } elsif (defined($class) and $func_name eq "DESTROY") {
1397 print "delete THIS;\n";
1400 if ($ret_type ne "void") {
1404 if (defined($static)) {
1405 if ($func_name eq 'new') {
1406 $func_name = "$class";
1410 } elsif (defined($class)) {
1411 if ($func_name eq 'new') {
1412 $func_name .= " $class";
1417 $func_name =~ s/^($spat)//
1419 $func_name = 'XSFUNCTION' if $interface;
1420 print "$func_name($func_args);\n";
1424 # do output variables
1425 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
1426 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
1427 # $wantRETVAL set if 'RETVAL =' autogenerated
1428 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
1430 process_keyword
("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
1432 &generate_output
($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
1433 for grep $in_out{$_} =~ /OUT$/, keys %in_out;
1435 # all OUTPUT done, so now push the return value on the stack
1436 if ($gotRETVAL && $RETVAL_code) {
1437 print "\t$RETVAL_code\n";
1438 } elsif ($gotRETVAL || $wantRETVAL) {
1439 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
1441 my $type = $ret_type;
1443 # 0: type, 1: with_size, 2: how, 3: how_size
1444 if ($t and not $t->[1] and $t->[0] eq 'p') {
1445 # PUSHp corresponds to setpvn. Treate setpv directly
1446 my $what = eval qq("$t->[2]");
1449 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
1453 my $what = eval qq("$t->[2]");
1457 $size = '' unless defined $size;
1458 $size = eval qq("$size");
1460 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
1464 # RETVAL almost never needs SvSETMAGIC()
1465 &generate_output
($ret_type, 0, 'RETVAL', 0);
1469 $xsreturn = 1 if $ret_type ne "void";
1470 my $num = $xsreturn;
1472 # (PP)CODE set different values of SP; reset to PPCODE's with 0 output
1473 print "\tXSprePUSH;" if $c and not $prepush_done;
1474 # Take into account stuff already put on stack
1475 print "\t++SP;" if $c and not $prepush_done and $xsreturn;
1476 # Now SP corresponds to ST($xsreturn), so one can combine PUSH and ST()
1477 print "\tEXTEND(SP,$c);\n" if $c;
1479 generate_output
($var_types{$_}, $num++, $_, 0, 1) for @outlist;
1482 process_keyword
("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD") ;
1484 print Q
<<"EOF" if $ScopeThisXSUB;
1487 print Q
<<"EOF" if $ScopeThisXSUB and not $PPCODE;
1491 # print function trailer
1495 print Q
<<EOF if $except;
1498 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
1501 if (check_keyword
("CASE")) {
1502 blurt
("Error: No `CASE:' at top of function")
1504 $_ = "CASE: $_"; # Restore CASE: label
1507 last if $_ eq "$END:";
1508 death
(/^$BLOCK_re/o ?
"Misplaced `$1:'" : "Junk at end of function");
1511 print Q
<<EOF if $except;
1513 # Perl_croak(aTHX_ errbuf);
1517 print Q
<<EOF unless $PPCODE;
1518 # XSRETURN($xsreturn);
1521 print Q
<<EOF unless $PPCODE;
1531 my $newXS = "newXS" ;
1534 # Build the prototype string for the xsub
1535 if ($ProtoThisXSUB) {
1536 $newXS = "newXSproto";
1538 if ($ProtoThisXSUB eq 2) {
1539 # User has specified empty prototype
1542 elsif ($ProtoThisXSUB ne 1) {
1543 # User has specified a prototype
1544 $proto = ', "' . $ProtoThisXSUB . '"';
1548 if ($min_args < $num_args) {
1550 $proto_arg[$min_args] .= ";" ;
1552 push @proto_arg, "$s\@"
1555 $proto = ', "' . join ("", @proto_arg) . '"';
1560 $XsubAliases{$pname} = 0
1561 unless defined $XsubAliases{$pname} ;
1562 while ( ($name, $value) = each %XsubAliases) {
1563 push(@InitFileCode, Q
<<"EOF");
1564 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1565 # XSANY.any_i32 = $value ;
1567 push(@InitFileCode, Q
<<"EOF") if $proto;
1568 # sv_setpv((SV*)cv$proto) ;
1572 elsif (@Attributes) {
1573 push(@InitFileCode, Q
<<"EOF");
1574 # cv = newXS(\"$pname\", XS_$Full_func_name, file);
1575 # apply_attrs_string("$Package", cv, "@Attributes", 0);
1578 elsif ($interface) {
1579 while ( ($name, $value) = each %Interfaces) {
1580 $name = "$Package\::$name" unless $name =~ /::/;
1581 push(@InitFileCode, Q
<<"EOF");
1582 # cv = newXS(\"$name\", XS_$Full_func_name, file);
1583 # $interface_macro_set(cv,$value) ;
1585 push(@InitFileCode, Q
<<"EOF") if $proto;
1586 # sv_setpv((SV*)cv$proto) ;
1592 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1596 if ($Overload) # make it findable with fetchmethod
1600 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
1601 #XS(XS_${Packid}_nil)
1607 unshift(@InitFileCode, <<"MAKE_FETCHMETHOD_WORK");
1608 /* Making a sub named "${Package}::()" allows the package */
1609 /* to be findable via fetchmethod(), and causes */
1610 /* overload::Overloaded("${Package}") to return true. */
1611 newXS("${Package}::()", XS_${Packid}_nil, file$proto);
1612 MAKE_FETCHMETHOD_WORK
1615 # print initialization routine
1624 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1625 #XS(boot_$Module_cname)
1633 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1634 #so `file' is unused
1635 print Q
<<"EOF" if $Full_func_name;
1636 # char* file = __FILE__;
1641 print Q
<<"EOF" if $WantVersionChk ;
1642 # XS_VERSION_BOOTCHECK ;
1646 print Q
<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1652 print Q
<<"EOF" if ($Overload);
1653 # /* register the overloading (type 'A') magic */
1654 # PL_amagic_generation++;
1655 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1656 # /* mentioned above, and looks in the SV* slot of it for */
1657 # /* the "fallback" status. */
1659 # get_sv( "${Package}::()", TRUE ),
1664 print @InitFileCode;
1666 print Q
<<"EOF" if defined $XsubAliases or defined $Interfaces ;
1672 print "\n /* Initialisation Section */\n\n" ;
1675 print "\n /* End of Initialisation Section */\n\n" ;
1684 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1689 local($type, $num, $var, $init, $name_printed) = @_;
1690 local($arg) = "ST(" . ($num - 1) . ")";
1692 if( $init =~ /^=/ ) {
1693 if ($name_printed) {
1694 eval qq/print " $init\\n"/;
1696 eval qq/print "\\t$var $init\\n"/;
1700 if( $init =~ s/^\+// && $num ) {
1701 &generate_init
($type, $num, $var, $name_printed);
1702 } elsif ($name_printed) {
1706 eval qq/print "\\t$var;\\n"/;
1710 $deferred .= eval qq/"\\n\\t$init\\n"/;
1717 # work out the line number
1718 my $line_no = $line_no[@line_no - @line -1] ;
1720 print STDERR
"@_ in $filename, line $line_no\n" ;
1736 local($type, $num, $var) = @_;
1737 local($arg) = "ST(" . ($num - 1) . ")";
1738 local($argoff) = $num - 1;
1742 $type = TidyType
($type) ;
1743 blurt
("Error: '$type' not in typemap"), return
1744 unless defined($type_kind{$type});
1746 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1747 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1748 $tk = $type_kind{$type};
1749 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1750 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1751 print "\t$var" unless $name_printed;
1752 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1753 die "default value not supported with length(NAME) supplied"
1754 if defined $defaults{$var};
1757 $type =~ tr/:/_/ unless $hiertype;
1758 blurt
("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1759 unless defined $input_expr{$tk} ;
1760 $expr = $input_expr{$tk};
1761 if ($expr =~ /DO_ARRAY_ELEM/) {
1762 blurt
("Error: '$subtype' not in typemap"), return
1763 unless defined($type_kind{$subtype});
1764 blurt
("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1765 unless defined $input_expr{$type_kind{$subtype}} ;
1766 $subexpr = $input_expr{$type_kind{$subtype}};
1767 $subexpr =~ s/\$type/\$subtype/g;
1768 $subexpr =~ s/ntype/subtype/g;
1769 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1770 $subexpr =~ s/\n\t/\n\t\t/g;
1771 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1772 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1773 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1775 if ($expr =~ m
#/\*.*scope.*\*/#i) { # "scope" in C comments
1778 if (defined($defaults{$var})) {
1779 $expr =~ s/(\t+)/$1 /g;
1781 if ($name_printed) {
1784 eval qq/print "\\t$var;\\n"/;
1787 if ($defaults{$var} eq 'NO_INIT') {
1788 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1790 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1793 } elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1794 if ($name_printed) {
1797 eval qq/print "\\t$var;\\n"/;
1800 $deferred .= eval qq/"\\n$expr;\\n"/;
1803 die "panic: do not know how to handle this branch for function pointers"
1805 eval qq/print "$expr;\\n"/;
1810 sub generate_output
{
1811 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1812 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1813 local($argoff) = $num - 1;
1816 $type = TidyType
($type) ;
1817 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1818 print "\t$arg = sv_newmortal();\n";
1819 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1820 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1822 blurt
("Error: '$type' not in typemap"), return
1823 unless defined($type_kind{$type});
1824 blurt
("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1825 unless defined $output_expr{$type_kind{$type}} ;
1826 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1827 $ntype =~ s/\(\)//g;
1828 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1829 $expr = $output_expr{$type_kind{$type}};
1830 if ($expr =~ /DO_ARRAY_ELEM/) {
1831 blurt
("Error: '$subtype' not in typemap"), return
1832 unless defined($type_kind{$subtype});
1833 blurt
("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1834 unless defined $output_expr{$type_kind{$subtype}} ;
1835 $subexpr = $output_expr{$type_kind{$subtype}};
1836 $subexpr =~ s/ntype/subtype/g;
1837 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1838 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1839 $subexpr =~ s/\n\t/\n\t\t/g;
1840 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1841 eval "print qq\a$expr\a";
1843 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1845 elsif ($var eq 'RETVAL') {
1846 if ($expr =~ /^\t\$arg = new/) {
1847 # We expect that $arg has refcnt 1, so we need to
1849 eval "print qq\a$expr\a";
1851 print "\tsv_2mortal(ST($num));\n";
1852 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1854 elsif ($expr =~ /^\s*\$arg\s*=/) {
1855 # We expect that $arg has refcnt >=1, so we need
1857 eval "print qq\a$expr\a";
1859 print "\tsv_2mortal(ST(0));\n";
1860 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1863 # Just hope that the entry would safely write it
1864 # over an already mortalized value. By
1865 # coincidence, something like $arg = &sv_undef
1867 print "\tST(0) = sv_newmortal();\n";
1868 eval "print qq\a$expr\a";
1870 # new mortals don't have set magic
1874 print "\tPUSHs(sv_newmortal());\n";
1876 eval "print qq\a$expr\a";
1878 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1880 elsif ($arg =~ /^ST\(\d+\)$/) {
1881 eval "print qq\a$expr\a";
1883 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1889 my($type, $varname) = @_;
1891 # C++ has :: in types too so skip this
1892 $type =~ tr/:/_/ unless $hiertype;
1893 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1895 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1896 (substr $type, pos $type, 0) = " $varname ";
1898 $type .= "\t$varname";
1906 # If this is VMS, the exit status has meaning to the shell, so we
1907 # use a predictable value (SS$_Normal or SS$_Abort) rather than an
1909 # exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
1910 exit ($errors ?
1 : 0);