1 package ExtUtils::ParseXS;
4 use 5.006; # We use /??{}/ in regexes
11 use ExtUtils::ParseXS::Constants ();
12 use ExtUtils::ParseXS::CountLines;
13 use ExtUtils::ParseXS::Utilities qw(
14 standard_typemap_locations
24 our (@ISA, @EXPORT_OK, $VERSION);
26 @EXPORT_OK = qw(process_file);
28 $VERSION = eval $VERSION if $VERSION =~ /_/;
30 # use strict; # One of these days ...
33 $ProtoUsed, @InitFileCode, $FH, $proto_re, $Overload, $errors, $Fallback,
34 $hiertype, $WantPrototypes, $WantVersionChk, $WantLineNumbers, $filepathname,
35 $dir, $filename, %IncludedFiles, %input_expr, %output_expr,
36 %type_kind, %proto_letter, $BLOCK_re, $lastline, $lastline_no, $Package,
37 $Prefix, @line, %args_match, %defaults, %var_types, %arg_list, @proto_arg,
38 $processing_arg_with_types, %argtype_seen, %in_out, %lengthof,
39 $proto_in_this_xsub, $scope_in_this_xsub, $interface,
40 $interface_macro, $interface_macro_set, $ProtoThisXSUB, $ScopeThisXSUB,
41 @line_no, $ret_type, $func_name, $Full_func_name, $Packprefix, $Packid,
42 %XsubAliases, %XsubAliasValues, %Interfaces, @Attributes, %outargs, $pname,
43 $thisdone, $retvaldone, $deferred, $gotRETVAL, $condnum, $cond,
44 $RETVAL_code, $printed_name, $func_args, @XSStack, $ALIAS,
46 our ($DoSetMagic, $newXS, $proto, $Module_cname, $XsubAliases, $Interfaces, $var_num, );
50 # Allow for $package->process_file(%hash) in the future
51 my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
53 $ProtoUsed = exists $options{prototypes};
70 $args{except} = $args{except} ? ' TRY' : '';
74 my ($Is_VMS, $SymSet);
77 # Establish set of global symbols with max length 28, since xsubpp
78 # will later add the 'XS_' prefix.
79 require ExtUtils::XSSymSet;
80 $SymSet = new ExtUtils::XSSymSet 28;
82 @XSStack = ({type => 'none'});
84 my $cpp_next_tmp = 'XSubPPtmpAAAA';
85 @InitFileCode = @ExtUtils::ParseXS::Constants::InitFileCode;
86 $FH = $ExtUtils::ParseXS::Constants::FH;
87 $proto_re = $ExtUtils::ParseXS::Constants::proto_re;
88 $Overload = $ExtUtils::ParseXS::Constants::Overload;
89 $errors = $ExtUtils::ParseXS::Constants::errors;
90 $Fallback = $ExtUtils::ParseXS::Constants::Fallback;
92 # Most of the 1500 lines below uses these globals. We'll have to
93 # clean this up sometime, probably. For now, we just pull them out
96 $hiertype = $args{hiertype};
97 $WantPrototypes = $args{prototypes};
98 $WantVersionChk = $args{versioncheck};
99 $WantLineNumbers = $args{linenumbers};
101 for my $f ($args{filename}) {
102 die "Missing required parameter 'filename'" unless $f;
104 ($dir, $filename) = (dirname($f), basename($f));
105 $filepathname =~ s/\\/\\\\/g;
106 $IncludedFiles{$f}++;
109 # Open the output file if given as a string. If they provide some
110 # other kind of reference, trust them that we can print to it.
111 if (not ref $args{output}) {
112 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
113 $args{outfile} = $args{output};
117 # Really, we shouldn't have to chdir() or select() in the first
118 # place. For now, just save & restore.
119 my $orig_cwd = cwd();
120 my $orig_fh = select();
124 my $csuffix = $args{csuffix};
126 if ($WantLineNumbers) {
128 if ( $args{outfile} ) {
129 $cfile = $args{outfile};
132 $cfile = $args{filename};
133 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
135 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
136 select PSEUDO_STDOUT;
139 select $args{output};
142 my ($type_kind_ref, $proto_letter_ref, $input_expr_ref, $output_expr_ref) =
143 process_typemaps( $args{typemap}, $pwd );
145 %type_kind = %{ $type_kind_ref };
146 %proto_letter = %{ $proto_letter_ref };
147 %input_expr = %{ $input_expr_ref };
148 %output_expr = %{ $output_expr_ref };
150 foreach my $value (values %input_expr) {
151 $value =~ s/;*\s+\z//;
152 # Move C pre-processor instructions to column 1 to be strictly ANSI
153 # conformant. Some pre-processors are fussy about this.
154 $value =~ s/^\s+#/#/mg;
156 foreach my $value (values %output_expr) {
158 $value =~ s/^\s+#/#/mg;
161 my %targetable = make_targetable(\%output_expr);
163 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
165 # Match an XS keyword
166 $BLOCK_re = '\s*(' . join('|', qw(
167 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE
168 OUTPUT CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE
169 VERSIONCHECK INCLUDE INCLUDE_COMMAND SCOPE INTERFACE
170 INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
173 our ($C_group_rex, $C_arg);
174 # Group in C (no support for comments or literals)
175 $C_group_rex = qr/ [({\[]
176 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
178 # Chunk in C without comma at toplevel (no comments):
179 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
180 | (??{ $C_group_rex })
181 | " (?: (?> [^\\"]+ )
183 )* " # String literal
184 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
187 # Identify the version of xsubpp used
190 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
191 * contents of $filename. Do not edit this file, edit $filename instead.
193 * ANY CHANGES MADE HERE WILL BE LOST!
200 print("#line 1 \"$filepathname\"\n")
203 # Open the input file (using basename'd $args{filename} due to chdir above)
204 open($FH, $filename) or die "cannot open $filename: $!\n";
209 my $podstartline = $.;
212 # We can't just write out a /* */ comment, as our embedded
213 # POD might itself be in a comment. We can't put a /**/
214 # comment inside #if 0, as the C standard says that the source
215 # file is decomposed into preprocessing characters in the stage
216 # before preprocessing commands are executed.
217 # I don't want to leave the text as barewords, because the spec
218 # isn't clear whether macros are expanded before or after
219 # preprocessing commands are executed, and someone pathological
220 # may just have defined one of the 3 words as a macro that does
221 # something strange. Multiline strings are illegal in C, so
222 # the "" we write must be a string literal. And they aren't
223 # concatenated until 2 steps later, so we are safe.
225 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
226 printf("#line %d \"$filepathname\"\n", $. + 1)
232 # At this point $. is at end of file so die won't state the start
233 # of the problem, and as we haven't yet read any lines &death won't
234 # show the correct line in the message either.
235 die ("Error: Unterminated pod in $filename, line $podstartline\n")
238 last if ($Package, $Prefix) =
239 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
243 unless (defined $_) {
244 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
245 exit 0; # Not a fatal error for the caller process
248 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
251 #ifndef PERL_UNUSED_VAR
252 # define PERL_UNUSED_VAR(var) if (0) var = var
258 #ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
259 #define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)
261 /* prototype to pass -Wmissing-prototypes */
263 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params);
266 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params)
268 const GV *const gv = CvGV(cv);
270 PERL_ARGS_ASSERT_CROAK_XS_USAGE;
273 const char *const gvname = GvNAME(gv);
274 const HV *const stash = GvSTASH(gv);
275 const char *const hvname = stash ? HvNAME(stash) : NULL;
278 Perl_croak(aTHX_ "Usage: %s::%s(%s)", hvname, gvname, params);
280 Perl_croak(aTHX_ "Usage: %s(%s)", gvname, params);
282 /* Pants. I don't think that it should be possible to get here. */
283 Perl_croak(aTHX_ "Usage: CODE(0x%"UVxf")(%s)", PTR2UV(cv), params);
286 #undef PERL_ARGS_ASSERT_CROAK_XS_USAGE
288 #ifdef PERL_IMPLICIT_CONTEXT
289 #define croak_xs_usage(a,b) S_croak_xs_usage(aTHX_ a,b)
291 #define croak_xs_usage S_croak_xs_usage
296 /* NOTE: the prototype of newXSproto() is different in versions of perls,
297 * so we define a portable version of newXSproto()
300 #define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
302 #define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
303 #endif /* !defined(newXS_flags) */
307 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
312 my (@BootCode, @outlist, $prepush_done, $xsreturn, $func_header, $orig_args, );
314 while (fetch_para()) {
315 # Print initial preprocessor statements and blank lines
316 while (@line && $line[0] !~ /^[^\#]/) {
317 my $ln = shift(@line);
319 next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
321 if ($statement eq 'if') {
322 $XSS_work_idx = @XSStack;
323 push(@XSStack, {type => 'if'});
326 death ("Error: `$statement' with no matching `if'")
327 if $XSStack[-1]{type} ne 'if';
328 if ($XSStack[-1]{varname}) {
329 push(@InitFileCode, "#endif\n");
330 push(@BootCode, "#endif");
333 my(@fns) = keys %{$XSStack[-1]{functions}};
334 if ($statement ne 'endif') {
335 # Hide the functions defined in other #if branches, and reset.
336 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
337 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
340 my($tmp) = pop(@XSStack);
341 0 while (--$XSS_work_idx
342 && $XSStack[$XSS_work_idx]{type} ne 'if');
343 # Keep all new defined functions
344 push(@fns, keys %{$tmp->{other_functions}});
345 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
350 next PARAGRAPH unless @line;
352 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
353 # We are inside an #if, but have not yet #defined its xsubpp variable.
354 print "#define $cpp_next_tmp 1\n\n";
355 push(@InitFileCode, "#if $cpp_next_tmp\n");
356 push(@BootCode, "#if $cpp_next_tmp");
357 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
360 death ("Code is not inside a function"
361 ." (maybe last function was ended by a blank line "
362 ." followed by a statement on column one?)")
363 if $line[0] =~ /^\s/;
365 my ($class, $externC, $static, $ellipsis, $wantRETVAL, $RETVAL_no_return);
366 my (@fake_INPUT_pre); # For length(s) generated variables
369 # initialize info arrays
375 undef($processing_arg_with_types);
376 undef(%argtype_seen);
380 undef($proto_in_this_xsub);
381 undef($scope_in_this_xsub);
383 undef($prepush_done);
384 $interface_macro = 'XSINTERFACE_FUNC';
385 $interface_macro_set = 'XSINTERFACE_FUNC_SET';
386 $ProtoThisXSUB = $WantPrototypes;
391 while (my $kwd = check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
393 &{"${kwd}_handler"}();
395 next PARAGRAPH unless @line;
399 if (check_keyword("BOOT")) {
401 push (@BootCode, "#line $line_no[@line_no - @line] \"$filepathname\"")
402 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
403 push (@BootCode, @line, "");
407 # extract return type, function name and arguments
408 ($ret_type) = tidy_type($_);
409 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
411 # Allow one-line ANSI-like declaration
414 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
416 # a function definition needs at least 2 lines
417 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
420 $externC = 1 if $ret_type =~ s/^extern "C"\s+//;
421 $static = 1 if $ret_type =~ s/^static\s+//;
423 $func_header = shift(@line);
424 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
425 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
427 ($class, $func_name, $orig_args) = ($1, $2, $3);
428 $class = "$4 $class" if $4;
429 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
431 ($clean_func_name = $func_name) =~ s/^$Prefix//;
432 $Full_func_name = "${Packid}_$clean_func_name";
434 $Full_func_name = $SymSet->addsym($Full_func_name);
437 # Check for duplicate function definition
438 for my $tmp (@XSStack) {
439 next unless defined $tmp->{functions}{$Full_func_name};
440 Warn("Warning: duplicate function definition '$clean_func_name' detected");
443 $XSStack[$XSS_work_idx]{functions}{$Full_func_name}++;
444 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
447 $orig_args =~ s/\\\s*/ /g; # process line continuations
450 my %only_C_inlist; # Not in the signature of Perl function
451 if ($args{argtypes} and $orig_args =~ /\S/) {
452 my $args = "$orig_args ,";
453 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
454 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
458 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
459 my ($pre, $len_name) = ($arg =~ /(.*?) \s*
460 \b ( \w+ | length\( \s*\w+\s* \) )
462 next unless defined($pre) && length($pre);
465 if ($args{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
467 $out_type = $type if $type ne 'IN';
468 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
469 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
472 if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
473 $len_name = "XSauto_length_of_$1";
475 die "Default value on length() argument: `$_'"
478 if (length $pre or $islength) { # Has a type
480 push @fake_INPUT_pre, $arg;
483 push @fake_INPUT, $arg;
485 # warn "pushing '$arg'\n";
486 $argtype_seen{$len_name}++;
487 $_ = "$len_name$default"; # Assigns to @args
489 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
490 push @outlist, $len_name if $out_type =~ /OUTLIST$/;
491 $in_out{$len_name} = $out_type if $out_type;
495 @args = split(/\s*,\s*/, $orig_args);
496 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
500 @args = split(/\s*,\s*/, $orig_args);
502 if ($args{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
504 next if $out_type eq 'IN';
505 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
506 if ($out_type =~ /OUTLIST$/) {
507 push @outlist, undef;
509 $in_out{$_} = $out_type;
513 if (defined($class)) {
514 my $arg0 = ((defined($static) or $func_name eq 'new')
516 unshift(@args, $arg0);
521 my $report_args = '';
522 foreach my $i (0 .. $#args) {
523 if ($args[$i] =~ s/\.\.\.//) {
525 if ($args[$i] eq '' && $i == $#args) {
526 $report_args .= ", ...";
531 if ($only_C_inlist{$args[$i]}) {
532 push @args_num, undef;
535 push @args_num, ++$num_args;
536 $report_args .= ", $args[$i]";
538 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
541 $defaults{$args[$i]} = $2;
542 $defaults{$args[$i]} =~ s/"/\\"/g;
544 $proto_arg[$i+1] = '$';
546 my $min_args = $num_args - $extra_args;
547 $report_args =~ s/"/\\"/g;
548 $report_args =~ s/^,\s+//;
549 my @func_args = @args;
550 shift @func_args if defined($class);
553 s/^/&/ if $in_out{$_};
555 $func_args = join(", ", @func_args);
556 @args_match{@args} = @args_num;
558 my $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
559 my $CODE = grep(/^\s*CODE\s*:/, @line);
560 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
561 # to set explicit return values.
562 my $EXPLICIT_RETURN = ($CODE &&
563 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
565 # The $ALIAS which follows is only explicitly called within the scope of
566 # process_file(). In principle, it ought to be a lexical, i.e., 'my
567 # $ALIAS' like the other nearby variables. However, implementing that
568 # change produced a slight difference in the resulting .c output in at
569 # least two distributions: B/BD/BDFOY/Crypt-Rijndael and
570 # G/GF/GFUJI/Hash-FieldHash. The difference is, arguably, an improvement
571 # in the resulting C code. Example:
573 # < GvNAME(CvGV(cv)),
575 # > "Crypt::Rijndael::encrypt",
576 # But at this point we're committed to generating the *same* C code that
577 # the current version of ParseXS.pm does. So we're declaring it as 'our'.
578 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
580 my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
582 $xsreturn = 1 if $EXPLICIT_RETURN;
584 $externC = $externC ? qq[extern "C"] : "";
586 # print function header
589 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
590 #XS(XS_${Full_func_name})
598 print Q(<<"EOF") if $ALIAS;
601 print Q(<<"EOF") if $INTERFACE;
602 # dXSFUNCTION($ret_type);
605 $cond = ($min_args ? qq(items < $min_args) : 0);
607 elsif ($min_args == $num_args) {
608 $cond = qq(items != $min_args);
611 $cond = qq(items < $min_args || items > $num_args);
614 print Q(<<"EOF") if $args{except};
622 # croak_xs_usage(cv, "$report_args");
626 # cv likely to be unused
628 # PERL_UNUSED_VAR(cv); /* -W */
632 #gcc -Wall: if an xsub has PPCODE is used
633 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
634 #hence `ax' (setup by dXSARGS) is unused
635 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
636 #but such a move could break third-party extensions
637 print Q(<<"EOF") if $PPCODE;
638 # PERL_UNUSED_VAR(ax); /* -Wall */
641 print Q(<<"EOF") if $PPCODE;
645 # Now do a block of some sort.
648 $cond = ''; # last CASE: condidional
649 push(@line, "$END:");
650 push(@line_no, $line_no[-1]);
654 &CASE_handler if check_keyword("CASE");
659 # do initialization of input variables
667 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
669 print Q(<<"EOF") if $ScopeThisXSUB;
674 if (!$thisdone && defined($class)) {
675 if (defined($static) or $func_name eq 'new') {
677 $var_types{"CLASS"} = "char *";
682 printed_name => undef,
687 $var_types{"THIS"} = "$class *";
692 printed_name => undef,
698 if (/^\s*NOT_IMPLEMENTED_YET/) {
699 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
703 if ($ret_type ne "void") {
704 print "\t" . &map_type($ret_type, 'RETVAL', $hiertype) . ";\n"
706 $args_match{"RETVAL"} = 0;
707 $var_types{"RETVAL"} = $ret_type;
709 if $args{optimize} and $targetable{$type_kind{$ret_type}};
712 if (@fake_INPUT or @fake_INPUT_pre) {
713 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
715 $processing_arg_with_types = 1;
720 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
722 if (check_keyword("PPCODE")) {
724 death ("PPCODE must be last thing") if @line;
725 print "\tLEAVE;\n" if $ScopeThisXSUB;
726 print "\tPUTBACK;\n\treturn;\n";
728 elsif (check_keyword("CODE")) {
731 elsif (defined($class) and $func_name eq "DESTROY") {
733 print "delete THIS;\n";
737 if ($ret_type ne "void") {
741 if (defined($static)) {
742 if ($func_name eq 'new') {
743 $func_name = "$class";
749 elsif (defined($class)) {
750 if ($func_name eq 'new') {
751 $func_name .= " $class";
757 $func_name =~ s/^\Q$args{'s'}//
758 if exists $args{'s'};
759 $func_name = 'XSFUNCTION' if $interface;
760 print "$func_name($func_args);\n";
764 # do output variables
765 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
766 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
767 # $wantRETVAL set if 'RETVAL =' autogenerated
768 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
770 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
773 type => $var_types{$_},
774 num => $args_match{$_},
776 do_setmagic => $DoSetMagic,
778 } ) for grep $in_out{$_} =~ /OUT$/, keys %in_out;
780 # all OUTPUT done, so now push the return value on the stack
781 if ($gotRETVAL && $RETVAL_code) {
782 print "\t$RETVAL_code\n";
784 elsif ($gotRETVAL || $wantRETVAL) {
785 my $t = $args{optimize} && $targetable{$type_kind{$ret_type}};
786 # Although the '$var' declared in the next line is never explicitly
787 # used within this 'elsif' block, commenting it out leads to
788 # disaster, starting with the first 'eval qq' inside the 'elsif' block
790 # It appears that this is related to the fact that at this point the
791 # value of $t is a reference to an array whose [2] element includes
792 # '$var' as a substring:
795 my $type = $ret_type;
797 # 0: type, 1: with_size, 2: how, 3: how_size
798 if ($t and not $t->[1] and $t->[0] eq 'p') {
799 # PUSHp corresponds to setpvn. Treate setpv directly
800 my $what = eval qq("$t->[2]");
803 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
807 my $what = eval qq("$t->[2]");
811 $tsize = '' unless defined $tsize;
812 $tsize = eval qq("$tsize");
814 print "\tXSprePUSH; PUSH$t->[0]($what$tsize);\n";
818 # RETVAL almost never needs SvSETMAGIC()
829 $xsreturn = 1 if $ret_type ne "void";
832 print "\tXSprePUSH;" if $c and not $prepush_done;
833 print "\tEXTEND(SP,$c);\n" if $c;
836 type => $var_types{$_},
844 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
846 print Q(<<"EOF") if $ScopeThisXSUB;
849 print Q(<<"EOF") if $ScopeThisXSUB and not $PPCODE;
853 # print function trailer
857 print Q(<<"EOF") if $args{except};
860 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
863 if (check_keyword("CASE")) {
864 blurt ("Error: No `CASE:' at top of function")
866 $_ = "CASE: $_"; # Restore CASE: label
869 last if $_ eq "$END:";
870 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
873 print Q(<<"EOF") if $args{except};
875 # Perl_croak(aTHX_ errbuf);
879 print Q(<<"EOF") unless $PPCODE;
880 # XSRETURN($xsreturn);
884 print Q(<<"EOF") unless $PPCODE;
897 # Build the prototype string for the xsub
898 if ($ProtoThisXSUB) {
899 $newXS = "newXSproto_portable";
901 if ($ProtoThisXSUB eq 2) {
902 # User has specified empty prototype
904 elsif ($ProtoThisXSUB eq 1) {
906 if ($min_args < $num_args) {
908 $proto_arg[$min_args] .= ";";
910 push @proto_arg, "$s\@"
913 $proto = join ("", grep defined, @proto_arg);
916 # User has specified a prototype
917 $proto = $ProtoThisXSUB;
919 $proto = qq{, "$proto"};
923 $XsubAliases{$pname} = 0
924 unless defined $XsubAliases{$pname};
925 while ( my ($xname, $value) = each %XsubAliases) {
926 push(@InitFileCode, Q(<<"EOF"));
927 # cv = ${newXS}(\"$xname\", XS_$Full_func_name, file$proto);
928 # XSANY.any_i32 = $value;
932 elsif (@Attributes) {
933 push(@InitFileCode, Q(<<"EOF"));
934 # cv = ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);
935 # apply_attrs_string("$Package", cv, "@Attributes", 0);
939 while ( my ($yname, $value) = each %Interfaces) {
940 $yname = "$Package\::$yname" unless $yname =~ /::/;
941 push(@InitFileCode, Q(<<"EOF"));
942 # cv = ${newXS}(\"$yname\", XS_$Full_func_name, file$proto);
943 # $interface_macro_set(cv,$value);
947 elsif($newXS eq 'newXS'){ # work around P5NCI's empty newXS macro
949 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
953 " (void)${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
955 } # END 'PARAGRAPH' 'while' loop
957 if ($Overload) { # make it findable with fetchmethod
959 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
960 #XS(XS_${Packid}_nil)
967 unshift(@InitFileCode, <<"MAKE_FETCHMETHOD_WORK");
968 /* Making a sub named "${Package}::()" allows the package */
969 /* to be findable via fetchmethod(), and causes */
970 /* overload::Overloaded("${Package}") to return true. */
971 (void)${newXS}("${Package}::()", XS_${Packid}_nil, file$proto);
972 MAKE_FETCHMETHOD_WORK
975 # print initialization routine
984 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
985 #XS(boot_$Module_cname)
997 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
998 #file name argument. If the wrong qualifier is used, it causes breakage with
999 #C++ compilers and warnings with recent gcc.
1000 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1001 #so `file' is unused
1002 print Q(<<"EOF") if $Full_func_name;
1003 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
1004 # char* file = __FILE__;
1006 # const char* file = __FILE__;
1013 # PERL_UNUSED_VAR(cv); /* -W */
1014 # PERL_UNUSED_VAR(items); /* -W */
1017 print Q(<<"EOF") if $WantVersionChk;
1018 # XS_VERSION_BOOTCHECK;
1022 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1028 print Q(<<"EOF") if ($Overload);
1029 # /* register the overloading (type 'A') magic */
1030 # PL_amagic_generation++;
1031 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1032 # /* mentioned above, and looks in the SV* slot of it for */
1033 # /* the "fallback" status. */
1035 # get_sv( "${Package}::()", TRUE ),
1040 print @InitFileCode;
1042 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1047 print "\n /* Initialisation Section */\n\n";
1050 print "\n /* End of Initialisation Section */\n\n";
1054 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
1055 # if (PL_unitcheckav)
1056 # call_list(PL_scopestack_ix, PL_unitcheckav);
1066 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1071 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
1077 sub errors { $errors }
1079 # Input: ($_, @line) == unparsed input.
1080 # Output: ($_, @line) == (rest of line, following lines).
1081 # Return: the matched keyword if found, otherwise 0
1083 $_ = shift(@line) while !/\S/ && @line;
1084 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1088 # the "do" is required for right semantics
1089 do { $_ = shift(@line) } while !/\S/ && @line;
1091 print("#line ", $line_no[@line_no - @line -1], " \"$filepathname\"\n")
1092 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1093 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1096 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
1102 while (!/\S/ && @line) {
1106 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1113 sub process_keyword($) {
1118 &{"${kwd}_handler"}()
1119 while $kwd = check_keyword($pattern);
1124 blurt ("Error: `CASE:' after unconditional `CASE:'")
1125 if $condnum && $cond eq '';
1127 trim_whitespace($cond);
1128 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
1133 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1134 last if /^\s*NOT_IMPLEMENTED_YET/;
1135 next unless /\S/; # skip blank lines
1137 trim_whitespace($_);
1140 # remove trailing semicolon if no initialisation
1141 s/\s*;$//g unless /[=;+].*\S/;
1143 # Process the length(foo) declarations
1144 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1145 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1146 $lengthof{$2} = undef;
1147 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1150 # check for optional initialisation code
1152 $var_init = $1 if s/\s*([=;+].*)$//s;
1153 $var_init =~ s/"/\\"/g;
1156 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1157 or blurt("Error: invalid argument declaration '$ln'"), next;
1159 # Check for duplicate definitions
1160 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
1161 if $arg_list{$var_name}++
1162 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
1164 $thisdone |= $var_name eq "THIS";
1165 $retvaldone |= $var_name eq "RETVAL";
1166 $var_types{$var_name} = $var_type;
1167 # XXXX This check is a safeguard against the unfinished conversion of
1168 # generate_init(). When generate_init() is fixed,
1169 # one can use 2-args map_type() unconditionally.
1170 if ($var_type =~ / \( \s* \* \s* \) /x) {
1171 # Function pointers are not yet supported with &output_init!
1172 print "\t" . &map_type($var_type, $var_name, $hiertype);
1176 print "\t" . &map_type($var_type, undef, $hiertype);
1179 $var_num = $args_match{$var_name};
1181 $proto_arg[$var_num] = ProtoString($var_type)
1183 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
1184 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1185 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
1186 and $var_init !~ /\S/) {
1187 if ($printed_name) {
1191 print "\t$var_name;\n";
1194 elsif ($var_init =~ /\S/) {
1200 printed_name => $printed_name,
1208 printed_name => $printed_name,
1217 sub OUTPUT_handler {
1218 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1220 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1221 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
1224 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1225 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1226 if $outargs{$outarg}++;
1227 if (!$gotRETVAL and $outarg eq 'RETVAL') {
1228 # deal with RETVAL last
1229 $RETVAL_code = $outcode;
1233 blurt ("Error: OUTPUT $outarg not an argument"), next
1234 unless defined($args_match{$outarg});
1235 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1236 unless defined $var_types{$outarg};
1237 $var_num = $args_match{$outarg};
1239 print "\t$outcode\n";
1240 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
1244 type => $var_types{$outarg},
1247 do_setmagic => $DoSetMagic,
1251 delete $in_out{$outarg} # No need to auto-OUTPUT
1252 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
1256 sub C_ARGS_handler() {
1257 my $in = merge_section();
1259 trim_whitespace($in);
1263 sub INTERFACE_MACRO_handler() {
1264 my $in = merge_section();
1266 trim_whitespace($in);
1267 if ($in =~ /\s/) { # two
1268 ($interface_macro, $interface_macro_set) = split ' ', $in;
1271 $interface_macro = $in;
1272 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
1274 $interface = 1; # local
1275 $Interfaces = 1; # global
1278 sub INTERFACE_handler() {
1279 my $in = merge_section();
1281 trim_whitespace($in);
1283 foreach (split /[\s,]+/, $in) {
1284 my $iface_name = $_;
1285 $iface_name =~ s/^$Prefix//;
1286 $Interfaces{$iface_name} = $_;
1289 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
1291 $interface = 1; # local
1292 $Interfaces = 1; # global
1295 sub CLEANUP_handler() { print_section() }
1296 sub PREINIT_handler() { print_section() }
1297 sub POSTCALL_handler() { print_section() }
1298 sub INIT_handler() { print_section() }
1304 # Parse alias definitions
1306 # alias = value alias = value ...
1308 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1309 my ($alias, $value) = ($1, $2);
1310 my $orig_alias = $alias;
1312 # check for optional package definition in the alias
1313 $alias = $Packprefix . $alias if $alias !~ /::/;
1315 # check for duplicate alias name & duplicate value
1316 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
1317 if defined $XsubAliases{$alias};
1319 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
1320 if $XsubAliasValues{$value};
1323 $XsubAliases{$alias} = $value;
1324 $XsubAliasValues{$value} = $orig_alias;
1327 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
1331 sub ATTRS_handler () {
1332 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1334 trim_whitespace($_);
1335 push @Attributes, $_;
1339 sub ALIAS_handler () {
1340 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1342 trim_whitespace($_);
1343 GetAliases($_) if $_;
1347 sub OVERLOAD_handler() {
1348 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1350 trim_whitespace($_);
1351 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1352 $Overload = 1 unless $Overload;
1353 my $overload = "$Package\::(".$1;
1355 " (void)${newXS}(\"$overload\", XS_$Full_func_name, file$proto);\n");
1360 sub FALLBACK_handler() {
1361 # the rest of the current line should contain either TRUE,
1364 trim_whitespace($_);
1366 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1367 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1368 UNDEF => "&PL_sv_undef",
1371 # check for valid FALLBACK value
1372 death ("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1374 $Fallback = $map{uc $_};
1378 sub REQUIRE_handler () {
1379 # the rest of the current line should contain a version number
1382 trim_whitespace($Ver);
1384 death ("Error: REQUIRE expects a version number")
1387 # check that the version number is of the form n.n
1388 death ("Error: REQUIRE: expected a number, got '$Ver'")
1389 unless $Ver =~ /^\d+(\.\d*)?/;
1391 death ("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1392 unless $VERSION >= $Ver;
1395 sub VERSIONCHECK_handler () {
1396 # the rest of the current line should contain either ENABLE or
1399 trim_whitespace($_);
1401 # check for ENABLE/DISABLE
1402 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
1403 unless /^(ENABLE|DISABLE)/i;
1405 $WantVersionChk = 1 if $1 eq 'ENABLE';
1406 $WantVersionChk = 0 if $1 eq 'DISABLE';
1410 sub PROTOTYPE_handler () {
1413 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1414 if $proto_in_this_xsub++;
1416 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1419 trim_whitespace($_);
1420 if ($_ eq 'DISABLE') {
1423 elsif ($_ eq 'ENABLE') {
1427 # remove any whitespace
1429 death("Error: Invalid prototype '$_'")
1430 unless valid_proto_string($_);
1431 $ProtoThisXSUB = C_string($_);
1435 # If no prototype specified, then assume empty prototype ""
1436 $ProtoThisXSUB = 2 unless $specified;
1441 sub SCOPE_handler () {
1442 death("Error: Only 1 SCOPE declaration allowed per xsub")
1443 if $scope_in_this_xsub++;
1445 trim_whitespace($_);
1446 death ("Error: SCOPE: ENABLE/DISABLE")
1447 unless /^(ENABLE|DISABLE)\b/i;
1448 $ScopeThisXSUB = ( uc($1) eq 'ENABLE' );
1451 sub PROTOTYPES_handler () {
1452 # the rest of the current line should contain either ENABLE or
1455 trim_whitespace($_);
1457 # check for ENABLE/DISABLE
1458 death ("Error: PROTOTYPES: ENABLE/DISABLE")
1459 unless /^(ENABLE|DISABLE)/i;
1461 $WantPrototypes = 1 if $1 eq 'ENABLE';
1462 $WantPrototypes = 0 if $1 eq 'DISABLE';
1468 # Save the current file context.
1471 LastLine => $lastline,
1472 LastLineNo => $lastline_no,
1474 LineNo => \@line_no,
1475 Filename => $filename,
1476 Filepathname => $filepathname,
1478 IsPipe => scalar($filename =~ /\|\s*$/),
1484 sub INCLUDE_handler () {
1485 # the rest of the current line should contain a valid filename
1487 trim_whitespace($_);
1489 death("INCLUDE: filename missing")
1492 death("INCLUDE: output pipe is illegal")
1495 # simple minded recursion detector
1496 death("INCLUDE loop detected")
1497 if $IncludedFiles{$_};
1499 ++$IncludedFiles{$_} unless /\|\s*$/;
1501 if (/\|\s*$/ && /^\s*perl\s/) {
1502 Warn("The INCLUDE directive with a command is discouraged." .
1503 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1504 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1505 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1506 " the use of \$^X as the currently running perl, see" .
1507 " 'perldoc perlxs' for details.");
1512 $FH = Symbol::gensym();
1515 open ($FH, "$_") or death("Cannot open '$_': $!");
1519 #/* INCLUDE: Including '$_' from '$filename' */
1524 $filepathname = File::Spec->catfile($dir, $filename);
1526 # Prime the pump by reading the first
1529 # skip leading blank lines
1531 last unless /^\s*$/;
1540 my @args = split /\s+/, $cmd;
1543 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1545 return join (' ', ($cmd, @args));
1548 sub INCLUDE_COMMAND_handler () {
1549 # the rest of the current line should contain a valid command
1551 trim_whitespace($_);
1553 $_ = QuoteArgs($_) if $^O eq 'VMS';
1555 death("INCLUDE_COMMAND: command missing")
1558 death("INCLUDE_COMMAND: pipes are illegal")
1559 if /^\s*\|/ or /\|\s*$/;
1561 PushXSStack( IsPipe => 1 );
1563 $FH = Symbol::gensym();
1565 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1566 # the same perl interpreter as we're currently running
1570 open ($FH, "-|", "$_")
1571 or death("Cannot run command '$_' to include its output: $!");
1575 #/* INCLUDE_COMMAND: Including output of '$_' from '$filename' */
1580 $filepathname = $filename;
1581 $filepathname =~ s/\"/\\"/g;
1583 # Prime the pump by reading the first
1586 # skip leading blank lines
1588 last unless /^\s*$/;
1596 return 0 unless $XSStack[-1]{type} eq 'file';
1598 my $data = pop @XSStack;
1599 my $ThisFile = $filename;
1600 my $isPipe = $data->{IsPipe};
1602 --$IncludedFiles{$filename}
1607 $FH = $data->{Handle};
1608 # $filename is the leafname, which for some reason isused for diagnostic
1609 # messages, whereas $filepathname is the full pathname, and is used for
1611 $filename = $data->{Filename};
1612 $filepathname = $data->{Filepathname};
1613 $lastline = $data->{LastLine};
1614 $lastline_no = $data->{LastLineNo};
1615 @line = @{ $data->{Line} };
1616 @line_no = @{ $data->{LineNo} };
1618 if ($isPipe and $? ) {
1620 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
1626 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
1633 sub ProtoString ($) {
1636 $proto_letter{$type} or "\$";
1640 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
1642 my ($cpp, $cpplevel);
1644 if ($cpp =~ /^\#\s*if/) {
1647 elsif (!$cpplevel) {
1648 Warn("Warning: #else/elif/endif without #if in this function");
1649 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
1650 if $XSStack[-1]{type} eq 'if';
1653 elsif ($cpp =~ /^\#\s*endif/) {
1657 Warn("Warning: #if without #endif in this function") if $cpplevel;
1665 $text =~ s/\[\[/{/g;
1666 $text =~ s/\]\]/}/g;
1670 # Read next xsub into @line from ($lastline, <$FH>).
1673 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
1674 if !defined $lastline && $XSStack[-1]{type} eq 'if';
1677 return PopFile() if !defined $lastline;
1680 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1682 $Package = defined($2) ? $2 : ''; # keep -w happy
1683 $Prefix = defined($3) ? $3 : ''; # keep -w happy
1684 $Prefix = quotemeta $Prefix;
1685 ($Module_cname = $Module) =~ s/\W/_/g;
1686 ($Packid = $Package) =~ tr/:/_/;
1687 $Packprefix = $Package;
1688 $Packprefix .= "::" if $Packprefix ne "";
1693 # Skip embedded PODs
1694 while ($lastline =~ /^=/) {
1695 while ($lastline = <$FH>) {
1696 last if ($lastline =~ /^=cut\s*$/);
1698 death ("Error: Unterminated pod") unless $lastline;
1701 $lastline =~ s/^\s+$//;
1703 if ($lastline !~ /^\s*#/ ||
1705 # ANSI: if ifdef ifndef elif else endif define undef
1707 # gcc: warning include_next
1709 # others: ident (gcc notes that some cpps have this one)
1710 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1711 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
1712 push(@line, $lastline);
1713 push(@line_no, $lastline_no);
1716 # Read next line and continuation lines
1717 last unless defined($lastline = <$FH>);
1720 $lastline .= $tmp_line
1721 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
1724 $lastline =~ s/^\s+$//;
1726 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
1731 my $argsref = shift;
1732 my ($type, $num, $var, $init, $printed_name) = (
1737 $argsref->{printed_name}
1739 my $arg = "ST(" . ($num - 1) . ")";
1741 if ( $init =~ /^=/ ) {
1742 if ($printed_name) {
1743 eval qq/print " $init\\n"/;
1746 eval qq/print "\\t$var $init\\n"/;
1751 if ( $init =~ s/^\+// && $num ) {
1756 printed_name => $printed_name,
1759 elsif ($printed_name) {
1764 eval qq/print "\\t$var;\\n"/;
1768 $deferred .= eval qq/"\\n\\t$init\\n"/;
1774 my $argsref = shift;
1775 my ($type, $num, $var, $printed_name) = (
1779 $argsref->{printed_name},
1781 my $arg = "ST(" . ($num - 1) . ")";
1782 my ($argoff, $ntype, $tk);
1785 $type = tidy_type($type);
1786 blurt("Error: '$type' not in typemap"), return
1787 unless defined($type_kind{$type});
1789 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1791 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1792 $tk = $type_kind{$type};
1793 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1794 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1795 print "\t$var" unless $printed_name;
1796 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1797 die "default value not supported with length(NAME) supplied"
1798 if defined $defaults{$var};
1801 $type =~ tr/:/_/ unless $hiertype;
1802 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1803 unless defined $input_expr{$tk};
1804 my $expr = $input_expr{$tk};
1805 if ($expr =~ /DO_ARRAY_ELEM/) {
1806 blurt("Error: '$subtype' not in typemap"), return
1807 unless defined($type_kind{$subtype});
1808 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1809 unless defined $input_expr{$type_kind{$subtype}};
1810 my $subexpr = $input_expr{$type_kind{$subtype}};
1811 $subexpr =~ s/\$type/\$subtype/g;
1812 $subexpr =~ s/ntype/subtype/g;
1813 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1814 $subexpr =~ s/\n\t/\n\t\t/g;
1815 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1816 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1817 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1819 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1822 if (defined($defaults{$var})) {
1823 $expr =~ s/(\t+)/$1 /g;
1825 if ($printed_name) {
1829 eval qq/print "\\t$var;\\n"/;
1832 if ($defaults{$var} eq 'NO_INIT') {
1833 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1836 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1840 elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1841 if ($printed_name) {
1845 eval qq/print "\\t$var;\\n"/;
1848 $deferred .= eval qq/"\\n$expr;\\n"/;
1852 die "panic: do not know how to handle this branch for function pointers"
1854 eval qq/print "$expr;\\n"/;
1859 sub generate_output {
1860 my $argsref = shift;
1861 my ($type, $num, $var, $do_setmagic, $do_push) = (
1865 $argsref->{do_setmagic},
1868 my $arg = "ST(" . ($num - ($num != 0)) . ")";
1871 $type = tidy_type($type);
1872 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1873 print "\t$arg = sv_newmortal();\n";
1874 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1875 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1878 blurt("Error: '$type' not in typemap"), return
1879 unless defined($type_kind{$type});
1880 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1881 unless defined $output_expr{$type_kind{$type}};
1882 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1883 $ntype =~ s/\(\)//g;
1885 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1886 my $expr = $output_expr{$type_kind{$type}};
1887 if ($expr =~ /DO_ARRAY_ELEM/) {
1888 blurt("Error: '$subtype' not in typemap"), return
1889 unless defined($type_kind{$subtype});
1890 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1891 unless defined $output_expr{$type_kind{$subtype}};
1892 my $subexpr = $output_expr{$type_kind{$subtype}};
1893 $subexpr =~ s/ntype/subtype/g;
1894 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1895 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1896 $subexpr =~ s/\n\t/\n\t\t/g;
1897 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1898 eval "print qq\a$expr\a";
1900 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1902 elsif ($var eq 'RETVAL') {
1903 if ($expr =~ /^\t\$arg = new/) {
1904 # We expect that $arg has refcnt 1, so we need to
1906 eval "print qq\a$expr\a";
1908 print "\tsv_2mortal(ST($num));\n";
1909 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1911 elsif ($expr =~ /^\s*\$arg\s*=/) {
1912 # We expect that $arg has refcnt >=1, so we need
1914 eval "print qq\a$expr\a";
1916 print "\tsv_2mortal(ST(0));\n";
1917 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1920 # Just hope that the entry would safely write it
1921 # over an already mortalized value. By
1922 # coincidence, something like $arg = &sv_undef
1924 print "\tST(0) = sv_newmortal();\n";
1925 eval "print qq\a$expr\a";
1927 # new mortals don't have set magic
1931 print "\tPUSHs(sv_newmortal());\n";
1933 eval "print qq\a$expr\a";
1935 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1937 elsif ($arg =~ /^ST\(\d+\)$/) {
1938 eval "print qq\a$expr\a";
1940 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1946 # work out the line number
1947 my $warn_line_number = $line_no[@line_no - @line -1];
1949 print STDERR "@_ in $filename, line $warn_line_number\n";