1 package ExtUtils::ParseXS;
3 use 5.006; # We use /??{}/ in regexes
10 use ExtUtils::ParseXS::Utilities qw(
11 standard_typemap_locations
14 our (@ISA, @EXPORT_OK, $VERSION);
16 @EXPORT_OK = qw(process_file);
17 $VERSION = '2.2210_01';
18 $VERSION = eval $VERSION if $VERSION =~ /_/;
20 # use strict; # One of these days...
22 my(@XSStack); # Stack of conditionals and INCLUDEs
23 my($XSS_work_idx, $cpp_next_tmp);
25 our (%input_expr, %output_expr, $ProtoUsed, @InitFileCode, $FH,
26 $proto_re, $Overload, $errors, $Fallback, $cplusplus, $hiertype,
27 $WantPrototypes, $WantVersionChk, $except, $WantLineNumbers,
28 $WantOptimize, $process_inout, $process_argtypes, @tm, $dir,
29 $filename, $filepathname, %IncludedFiles, %type_kind, %proto_letter,
30 %targetable, $BLOCK_re, $lastline, $lastline_no, $Package, $Prefix,
31 @line, @BootCode, %args_match, %defaults, %var_types, %arg_list, @proto_arg,
32 $processing_arg_with_types, %argtype_seen, @outlist, %in_out, %lengthof,
33 $proto_in_this_xsub, $scope_in_this_xsub, $interface, $prepush_done,
34 $interface_macro, $interface_macro_set, $ProtoThisXSUB, $ScopeThisXSUB,
35 $xsreturn, @line_no, $ret_type, $func_header, $orig_args,
40 # Allow for $package->process_file(%hash) in the future
41 my ($pkg, %args) = @_ % 2 ? @_ : (__PACKAGE__, @_);
43 $ProtoUsed = exists $args{prototypes};
47 # 'C++' => 0, # Doesn't seem to *do* anything...
65 my ($Is_VMS, $SymSet);
68 # Establish set of global symbols with max length 28, since xsubpp
69 # will later add the 'XS_' prefix.
70 require ExtUtils::XSSymSet;
71 $SymSet = new ExtUtils::XSSymSet 28;
73 @XSStack = ({type => 'none'});
74 ($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
76 $FH = Symbol::gensym();
77 $proto_re = "[" . quotemeta('\$%&*@;[]_') . "]";
80 $Fallback = '&PL_sv_undef';
82 # Most of the 1500 lines below uses these globals. We'll have to
83 # clean this up sometime, probably. For now, we just pull them out
86 $cplusplus = $args{'C++'};
87 $hiertype = $args{hiertype};
88 $WantPrototypes = $args{prototypes};
89 $WantVersionChk = $args{versioncheck};
90 $except = $args{except} ? ' TRY' : '';
91 $WantLineNumbers = $args{linenumbers};
92 $WantOptimize = $args{optimize};
93 $process_inout = $args{inout};
94 $process_argtypes = $args{argtypes};
95 @tm = ref $args{typemap} ? @{$args{typemap}} : ($args{typemap});
97 for ($args{filename}) {
98 die "Missing required parameter 'filename'" unless $_;
100 ($dir, $filename) = (dirname($_), basename($_));
101 $filepathname =~ s/\\/\\\\/g;
102 $IncludedFiles{$_}++;
105 # Open the input file
106 open($FH, $args{filename}) or die "cannot open $args{filename}: $!\n";
108 # Open the output file if given as a string. If they provide some
109 # other kind of reference, trust them that we can print to it.
110 if (not ref $args{output}) {
111 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
112 $args{outfile} = $args{output};
116 # Really, we shouldn't have to chdir() or select() in the first
117 # place. For now, just save & restore.
118 my $orig_cwd = cwd();
119 my $orig_fh = select();
123 my $csuffix = $args{csuffix};
125 if ($WantLineNumbers) {
127 if ( $args{outfile} ) {
128 $cfile = $args{outfile};
131 $cfile = $args{filename};
132 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
134 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
135 select PSEUDO_STDOUT;
138 select $args{output};
141 foreach my $typemap (@tm) {
142 die "Can't find $typemap in $pwd\n" unless -r $typemap;
145 push @tm, standard_typemap_locations( \@INC );
147 foreach my $typemap (@tm) {
148 next unless -f $typemap;
149 # skip directories, binary files etc.
150 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
152 open(TYPEMAP, $typemap)
153 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
154 my $mode = 'Typemap';
156 my $current = \$junk;
159 my $line_no = $. + 1;
161 $mode = 'Input'; $current = \$junk; next;
164 $mode = 'Output'; $current = \$junk; next;
166 if (/^TYPEMAP\s*$/) {
167 $mode = 'Typemap'; $current = \$junk; next;
169 if ($mode eq 'Typemap') {
173 # skip blank lines and comment lines
174 next if /^$/ or /^#/;
175 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
176 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
177 $type = TidyType($type);
178 $type_kind{$type} = $kind;
179 # prototype defaults to '$'
180 $proto = "\$" unless $proto;
181 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
182 unless ValidProtoString($proto);
183 $proto_letter{$type} = C_string($proto);
188 elsif ($mode eq 'Input') {
190 $input_expr{$_} = '';
191 $current = \$input_expr{$_};
195 $output_expr{$_} = '';
196 $current = \$output_expr{$_};
202 foreach my $value (values %input_expr) {
203 $value =~ s/;*\s+\z//;
204 # Move C pre-processor instructions to column 1 to be strictly ANSI
205 # conformant. Some pre-processors are fussy about this.
206 $value =~ s/^\s+#/#/mg;
208 foreach my $value (values %output_expr) {
210 $value =~ s/^\s+#/#/mg;
214 our $bal = qr[(?:(?>[^()]+)|\((??{ $bal })\))*]; # ()-balanced
215 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
216 $size = qr[,\s* (??{ $bal }) ]x; # Third arg (to setpvn)
218 foreach my $key (keys %output_expr) {
219 # We can still bootstrap compile 're', because in code re.pm is
220 # available to miniperl, and does not attempt to load the XS code.
223 my ($t, $with_size, $arg, $sarg) =
224 ($output_expr{$key} =~
225 m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
226 \s* \( \s* $cast \$arg \s* ,
227 \s* ( (??{ $bal }) ) # Set from
228 ( (??{ $size }) )? # Possible sizeof set-from
232 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
235 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
237 # Match an XS keyword
238 $BLOCK_re = '\s*(' . join('|', qw(
239 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE
240 OUTPUT CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE
241 VERSIONCHECK INCLUDE INCLUDE_COMMAND SCOPE INTERFACE
242 INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
245 our ($C_group_rex, $C_arg);
246 # Group in C (no support for comments or literals)
247 $C_group_rex = qr/ [({\[]
248 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
250 # Chunk in C without comma at toplevel (no comments):
251 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
252 | (??{ $C_group_rex })
253 | " (?: (?> [^\\"]+ )
255 )* " # String literal
256 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
259 # Identify the version of xsubpp used
262 * This file was venerated automatically by ExtUtils::ParseXS version $VERSION from the
263 * contents of $filename. Do not edit this file, edit $filename instead.
265 * ANY CHANGES MADE HERE WILL BE LOST!
272 print("#line 1 \"$filepathname\"\n")
278 my $podstartline = $.;
281 # We can't just write out a /* */ comment, as our embedded
282 # POD might itself be in a comment. We can't put a /**/
283 # comment inside #if 0, as the C standard says that the source
284 # file is decomposed into preprocessing characters in the stage
285 # before preprocessing commands are executed.
286 # I don't want to leave the text as barewords, because the spec
287 # isn't clear whether macros are expanded before or after
288 # preprocessing commands are executed, and someone pathological
289 # may just have defined one of the 3 words as a macro that does
290 # something strange. Multiline strings are illegal in C, so
291 # the "" we write must be a string literal. And they aren't
292 # concatenated until 2 steps later, so we are safe.
294 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
295 printf("#line %d \"$filepathname\"\n", $. + 1)
301 # At this point $. is at end of file so die won't state the start
302 # of the problem, and as we haven't yet read any lines &death won't
303 # show the correct line in the message either.
304 die ("Error: Unterminated pod in $filename, line $podstartline\n")
307 last if ($Package, $Prefix) =
308 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
312 unless (defined $_) {
313 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
314 exit 0; # Not a fatal error for the caller process
317 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
320 #ifndef PERL_UNUSED_VAR
321 # define PERL_UNUSED_VAR(var) if (0) var = var
327 #ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
328 #define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)
330 /* prototype to pass -Wmissing-prototypes */
332 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params);
335 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params)
337 const GV *const gv = CvGV(cv);
339 PERL_ARGS_ASSERT_CROAK_XS_USAGE;
342 const char *const gvname = GvNAME(gv);
343 const HV *const stash = GvSTASH(gv);
344 const char *const hvname = stash ? HvNAME(stash) : NULL;
347 Perl_croak(aTHX_ "Usage: %s::%s(%s)", hvname, gvname, params);
349 Perl_croak(aTHX_ "Usage: %s(%s)", gvname, params);
351 /* Pants. I don't think that it should be possible to get here. */
352 Perl_croak(aTHX_ "Usage: CODE(0x%"UVxf")(%s)", PTR2UV(cv), params);
355 #undef PERL_ARGS_ASSERT_CROAK_XS_USAGE
357 #ifdef PERL_IMPLICIT_CONTEXT
358 #define croak_xs_usage(a,b) S_croak_xs_usage(aTHX_ a,b)
360 #define croak_xs_usage S_croak_xs_usage
365 /* NOTE: the prototype of newXSproto() is different in versions of perls,
366 * so we define a portable version of newXSproto()
369 #define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
371 #define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
372 #endif /* !defined(newXS_flags) */
376 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
382 while (fetch_para()) {
383 # Print initial preprocessor statements and blank lines
384 while (@line && $line[0] !~ /^[^\#]/) {
385 my $line = shift(@line);
387 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
389 if ($statement eq 'if') {
390 $XSS_work_idx = @XSStack;
391 push(@XSStack, {type => 'if'});
394 death ("Error: `$statement' with no matching `if'")
395 if $XSStack[-1]{type} ne 'if';
396 if ($XSStack[-1]{varname}) {
397 push(@InitFileCode, "#endif\n");
398 push(@BootCode, "#endif");
401 my(@fns) = keys %{$XSStack[-1]{functions}};
402 if ($statement ne 'endif') {
403 # Hide the functions defined in other #if branches, and reset.
404 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
405 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
408 my($tmp) = pop(@XSStack);
409 0 while (--$XSS_work_idx
410 && $XSStack[$XSS_work_idx]{type} ne 'if');
411 # Keep all new defined functions
412 push(@fns, keys %{$tmp->{other_functions}});
413 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
418 next PARAGRAPH unless @line;
420 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
421 # We are inside an #if, but have not yet #defined its xsubpp variable.
422 print "#define $cpp_next_tmp 1\n\n";
423 push(@InitFileCode, "#if $cpp_next_tmp\n");
424 push(@BootCode, "#if $cpp_next_tmp");
425 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
428 death ("Code is not inside a function"
429 ." (maybe last function was ended by a blank line "
430 ." followed by a statement on column one?)")
431 if $line[0] =~ /^\s/;
433 my ($class, $externC, $static, $ellipsis, $wantRETVAL, $RETVAL_no_return);
434 my (@fake_INPUT_pre); # For length(s) generated variables
437 # initialize info arrays
443 undef($processing_arg_with_types);
444 undef(%argtype_seen);
448 undef($proto_in_this_xsub);
449 undef($scope_in_this_xsub);
451 undef($prepush_done);
452 $interface_macro = 'XSINTERFACE_FUNC';
453 $interface_macro_set = 'XSINTERFACE_FUNC_SET';
454 $ProtoThisXSUB = $WantPrototypes;
459 while (my $kwd = check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
460 &{"${kwd}_handler"}();
461 next PARAGRAPH unless @line;
465 if (check_keyword("BOOT")) {
467 push (@BootCode, "#line $line_no[@line_no - @line] \"$filepathname\"")
468 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
469 push (@BootCode, @line, "");
473 # extract return type, function name and arguments
474 ($ret_type) = TidyType($_);
475 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
477 # Allow one-line ANSI-like declaration
480 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
482 # a function definition needs at least 2 lines
483 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
486 $externC = 1 if $ret_type =~ s/^extern "C"\s+//;
487 $static = 1 if $ret_type =~ s/^static\s+//;
489 $func_header = shift(@line);
490 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
491 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
493 ($class, $func_name, $orig_args) = ($1, $2, $3);
494 $class = "$4 $class" if $4;
495 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
496 ($clean_func_name = $func_name) =~ s/^$Prefix//;
497 $Full_func_name = "${Packid}_$clean_func_name";
499 $Full_func_name = $SymSet->addsym($Full_func_name);
502 # Check for duplicate function definition
503 for my $tmp (@XSStack) {
504 next unless defined $tmp->{functions}{$Full_func_name};
505 Warn("Warning: duplicate function definition '$clean_func_name' detected");
508 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++;
509 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
512 $orig_args =~ s/\\\s*/ /g; # process line continuations
515 my %only_C_inlist; # Not in the signature of Perl function
516 if ($process_argtypes and $orig_args =~ /\S/) {
517 my $args = "$orig_args ,";
518 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
519 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
523 my ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
524 my ($pre, $name) = ($arg =~ /(.*?) \s*
525 \b ( \w+ | length\( \s*\w+\s* \) )
527 next unless defined($pre) && length($pre);
530 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
532 $out_type = $type if $type ne 'IN';
533 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
534 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
537 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
538 $name = "XSauto_length_of_$1";
540 die "Default value on length() argument: `$_'"
543 if (length $pre or $islength) { # Has a type
545 push @fake_INPUT_pre, $arg;
548 push @fake_INPUT, $arg;
550 # warn "pushing '$arg'\n";
551 $argtype_seen{$name}++;
552 $_ = "$name$default"; # Assigns to @args
554 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
555 push @outlist, $name if $out_type =~ /OUTLIST$/;
556 $in_out{$name} = $out_type if $out_type;
560 @args = split(/\s*,\s*/, $orig_args);
561 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
565 @args = split(/\s*,\s*/, $orig_args);
567 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
569 next if $out_type eq 'IN';
570 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
571 push @outlist, $name if $out_type =~ /OUTLIST$/;
572 $in_out{$_} = $out_type;
576 if (defined($class)) {
577 my $arg0 = ((defined($static) or $func_name eq 'new')
579 unshift(@args, $arg0);
584 my $report_args = '';
585 foreach my $i (0 .. $#args) {
586 if ($args[$i] =~ s/\.\.\.//) {
588 if ($args[$i] eq '' && $i == $#args) {
589 $report_args .= ", ...";
594 if ($only_C_inlist{$args[$i]}) {
595 push @args_num, undef;
598 push @args_num, ++$num_args;
599 $report_args .= ", $args[$i]";
601 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
604 $defaults{$args[$i]} = $2;
605 $defaults{$args[$i]} =~ s/"/\\"/g;
607 $proto_arg[$i+1] = '$';
609 $min_args = $num_args - $extra_args;
610 $report_args =~ s/"/\\"/g;
611 $report_args =~ s/^,\s+//;
612 my @func_args = @args;
613 shift @func_args if defined($class);
616 s/^/&/ if $in_out{$_};
618 $func_args = join(", ", @func_args);
619 @args_match{@args} = @args_num;
621 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
622 $CODE = grep(/^\s*CODE\s*:/, @line);
623 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
624 # to set explicit return values.
625 $EXPLICIT_RETURN = ($CODE &&
626 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
627 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
628 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
630 $xsreturn = 1 if $EXPLICIT_RETURN;
632 $externC = $externC ? qq[extern "C"] : "";
634 # print function header
637 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
638 #XS(XS_${Full_func_name})
646 print Q(<<"EOF") if $ALIAS;
649 print Q(<<"EOF") if $INTERFACE;
650 # dXSFUNCTION($ret_type);
653 $cond = ($min_args ? qq(items < $min_args) : 0);
655 elsif ($min_args == $num_args) {
656 $cond = qq(items != $min_args);
659 $cond = qq(items < $min_args || items > $num_args);
662 print Q(<<"EOF") if $except;
670 # croak_xs_usage(cv, "$report_args");
674 # cv likely to be unused
676 # PERL_UNUSED_VAR(cv); /* -W */
680 #gcc -Wall: if an xsub has PPCODE is used
681 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
682 #hence `ax' (setup by dXSARGS) is unused
683 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
684 #but such a move could break third-party extensions
685 print Q(<<"EOF") if $PPCODE;
686 # PERL_UNUSED_VAR(ax); /* -Wall */
689 print Q(<<"EOF") if $PPCODE;
693 # Now do a block of some sort.
696 $cond = ''; # last CASE: condidional
697 push(@line, "$END:");
698 push(@line_no, $line_no[-1]);
702 &CASE_handler if check_keyword("CASE");
707 # do initialization of input variables
715 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
717 print Q(<<"EOF") if $ScopeThisXSUB;
722 if (!$thisdone && defined($class)) {
723 if (defined($static) or $func_name eq 'new') {
725 $var_types{"CLASS"} = "char *";
726 &generate_init("char *", 1, "CLASS");
730 $var_types{"THIS"} = "$class *";
731 &generate_init("$class *", 1, "THIS");
736 if (/^\s*NOT_IMPLEMENTED_YET/) {
737 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
741 if ($ret_type ne "void") {
742 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
744 $args_match{"RETVAL"} = 0;
745 $var_types{"RETVAL"} = $ret_type;
747 if $WantOptimize and $targetable{$type_kind{$ret_type}};
750 if (@fake_INPUT or @fake_INPUT_pre) {
751 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
753 $processing_arg_with_types = 1;
758 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
760 if (check_keyword("PPCODE")) {
762 death ("PPCODE must be last thing") if @line;
763 print "\tLEAVE;\n" if $ScopeThisXSUB;
764 print "\tPUTBACK;\n\treturn;\n";
766 elsif (check_keyword("CODE")) {
769 elsif (defined($class) and $func_name eq "DESTROY") {
771 print "delete THIS;\n";
775 if ($ret_type ne "void") {
779 if (defined($static)) {
780 if ($func_name eq 'new') {
781 $func_name = "$class";
787 elsif (defined($class)) {
788 if ($func_name eq 'new') {
789 $func_name .= " $class";
795 $func_name =~ s/^\Q$args{'s'}//
796 if exists $args{'s'};
797 $func_name = 'XSFUNCTION' if $interface;
798 print "$func_name($func_args);\n";
802 # do output variables
803 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
804 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
805 # $wantRETVAL set if 'RETVAL =' autogenerated
806 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
808 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
810 &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
811 for grep $in_out{$_} =~ /OUT$/, keys %in_out;
813 # all OUTPUT done, so now push the return value on the stack
814 if ($gotRETVAL && $RETVAL_code) {
815 print "\t$RETVAL_code\n";
817 elsif ($gotRETVAL || $wantRETVAL) {
818 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
820 my $type = $ret_type;
822 # 0: type, 1: with_size, 2: how, 3: how_size
823 if ($t and not $t->[1] and $t->[0] eq 'p') {
824 # PUSHp corresponds to setpvn. Treate setpv directly
825 my $what = eval qq("$t->[2]");
828 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
832 my $what = eval qq("$t->[2]");
836 $size = '' unless defined $size;
837 $size = eval qq("$size");
839 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
843 # RETVAL almost never needs SvSETMAGIC()
844 &generate_output($ret_type, 0, 'RETVAL', 0);
848 $xsreturn = 1 if $ret_type ne "void";
851 print "\tXSprePUSH;" if $c and not $prepush_done;
852 print "\tEXTEND(SP,$c);\n" if $c;
854 generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
857 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
859 print Q(<<"EOF") if $ScopeThisXSUB;
862 print Q(<<"EOF") if $ScopeThisXSUB and not $PPCODE;
866 # print function trailer
870 print Q(<<"EOF") if $except;
873 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
876 if (check_keyword("CASE")) {
877 blurt ("Error: No `CASE:' at top of function")
879 $_ = "CASE: $_"; # Restore CASE: label
882 last if $_ eq "$END:";
883 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
886 print Q(<<"EOF") if $except;
888 # Perl_croak(aTHX_ errbuf);
892 print Q(<<"EOF") unless $PPCODE;
893 # XSRETURN($xsreturn);
897 print Q(<<"EOF") unless $PPCODE;
907 our $newXS = "newXS";
910 # Build the prototype string for the xsub
911 if ($ProtoThisXSUB) {
912 $newXS = "newXSproto_portable";
914 if ($ProtoThisXSUB eq 2) {
915 # User has specified empty prototype
917 elsif ($ProtoThisXSUB eq 1) {
919 if ($min_args < $num_args) {
921 $proto_arg[$min_args] .= ";";
923 push @proto_arg, "$s\@"
926 $proto = join ("", grep defined, @proto_arg);
929 # User has specified a prototype
930 $proto = $ProtoThisXSUB;
932 $proto = qq{, "$proto"};
936 $XsubAliases{$pname} = 0
937 unless defined $XsubAliases{$pname};
938 while ( ($name, $value) = each %XsubAliases) {
939 push(@InitFileCode, Q(<<"EOF"));
940 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
941 # XSANY.any_i32 = $value;
945 elsif (@Attributes) {
946 push(@InitFileCode, Q(<<"EOF"));
947 # cv = ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);
948 # apply_attrs_string("$Package", cv, "@Attributes", 0);
952 while ( ($name, $value) = each %Interfaces) {
953 $name = "$Package\::$name" unless $name =~ /::/;
954 push(@InitFileCode, Q(<<"EOF"));
955 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
956 # $interface_macro_set(cv,$value);
960 elsif($newXS eq 'newXS'){ # work around P5NCI's empty newXS macro
962 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
966 " (void)${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
970 if ($Overload) # make it findable with fetchmethod
973 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
974 #XS(XS_${Packid}_nil)
981 unshift(@InitFileCode, <<"MAKE_FETCHMETHOD_WORK");
982 /* Making a sub named "${Package}::()" allows the package */
983 /* to be findable via fetchmethod(), and causes */
984 /* overload::Overloaded("${Package}") to return true. */
985 (void)${newXS}("${Package}::()", XS_${Packid}_nil, file$proto);
986 MAKE_FETCHMETHOD_WORK
989 # print initialization routine
998 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
999 #XS(boot_$Module_cname)
1011 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
1012 #file name argument. If the wrong qualifier is used, it causes breakage with
1013 #C++ compilers and warnings with recent gcc.
1014 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1015 #so `file' is unused
1016 print Q(<<"EOF") if $Full_func_name;
1017 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
1018 # char* file = __FILE__;
1020 # const char* file = __FILE__;
1027 # PERL_UNUSED_VAR(cv); /* -W */
1028 # PERL_UNUSED_VAR(items); /* -W */
1031 print Q(<<"EOF") if $WantVersionChk;
1032 # XS_VERSION_BOOTCHECK;
1036 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1042 print Q(<<"EOF") if ($Overload);
1043 # /* register the overloading (type 'A') magic */
1044 # PL_amagic_generation++;
1045 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1046 # /* mentioned above, and looks in the SV* slot of it for */
1047 # /* the "fallback" status. */
1049 # get_sv( "${Package}::()", TRUE ),
1054 print @InitFileCode;
1056 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1061 print "\n /* Initialisation Section */\n\n";
1064 print "\n /* End of Initialisation Section */\n\n";
1068 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
1069 # if (PL_unitcheckav)
1070 # call_list(PL_scopestack_ix, PL_unitcheckav);
1080 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1085 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
1091 sub errors { $errors }
1093 sub TrimWhitespace {
1094 $_[0] =~ s/^\s+|\s+$//go;
1100 # rationalise any '*' by joining them into bunches and removing whitespace
1104 # change multiple whitespace into a single space
1107 # trim leading & trailing whitespace
1113 # Input: ($_, @line) == unparsed input.
1114 # Output: ($_, @line) == (rest of line, following lines).
1115 # Return: the matched keyword if found, otherwise 0
1117 $_ = shift(@line) while !/\S/ && @line;
1118 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1122 # the "do" is required for right semantics
1123 do { $_ = shift(@line) } while !/\S/ && @line;
1125 print("#line ", $line_no[@line_no - @line -1], " \"$filepathname\"\n")
1126 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1127 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1130 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
1136 while (!/\S/ && @line) {
1140 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1147 sub process_keyword($) {
1151 &{"${kwd}_handler"}()
1152 while $kwd = check_keyword($pattern);
1156 blurt ("Error: `CASE:' after unconditional `CASE:'")
1157 if $condnum && $cond eq '';
1159 TrimWhitespace($cond);
1160 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
1165 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1166 last if /^\s*NOT_IMPLEMENTED_YET/;
1167 next unless /\S/; # skip blank lines
1172 # remove trailing semicolon if no initialisation
1173 s/\s*;$//g unless /[=;+].*\S/;
1175 # Process the length(foo) declarations
1176 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1177 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1178 $lengthof{$2} = $name;
1179 # $islengthof{$name} = $1;
1180 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1183 # check for optional initialisation code
1185 $var_init = $1 if s/\s*([=;+].*)$//s;
1186 $var_init =~ s/"/\\"/g;
1189 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1190 or blurt("Error: invalid argument declaration '$line'"), next;
1192 # Check for duplicate definitions
1193 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
1194 if $arg_list{$var_name}++
1195 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
1197 $thisdone |= $var_name eq "THIS";
1198 $retvaldone |= $var_name eq "RETVAL";
1199 $var_types{$var_name} = $var_type;
1200 # XXXX This check is a safeguard against the unfinished conversion of
1201 # generate_init(). When generate_init() is fixed,
1202 # one can use 2-args map_type() unconditionally.
1203 if ($var_type =~ / \( \s* \* \s* \) /x) {
1204 # Function pointers are not yet supported with &output_init!
1205 print "\t" . &map_type($var_type, $var_name);
1209 print "\t" . &map_type($var_type);
1212 $var_num = $args_match{$var_name};
1214 $proto_arg[$var_num] = ProtoString($var_type)
1216 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
1217 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1218 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
1219 and $var_init !~ /\S/) {
1220 if ($name_printed) {
1224 print "\t$var_name;\n";
1227 elsif ($var_init =~ /\S/) {
1228 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
1231 # generate initialization code
1232 &generate_init($var_type, $var_num, $var_name, $name_printed);
1240 sub OUTPUT_handler {
1241 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1243 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1244 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
1247 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1248 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1249 if $outargs{$outarg} ++;
1250 if (!$gotRETVAL and $outarg eq 'RETVAL') {
1251 # deal with RETVAL last
1252 $RETVAL_code = $outcode;
1256 blurt ("Error: OUTPUT $outarg not an argument"), next
1257 unless defined($args_match{$outarg});
1258 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1259 unless defined $var_types{$outarg};
1260 $var_num = $args_match{$outarg};
1262 print "\t$outcode\n";
1263 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
1266 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
1268 delete $in_out{$outarg} # No need to auto-OUTPUT
1269 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
1273 sub C_ARGS_handler() {
1274 my $in = merge_section();
1276 TrimWhitespace($in);
1280 sub INTERFACE_MACRO_handler() {
1281 my $in = merge_section();
1283 TrimWhitespace($in);
1284 if ($in =~ /\s/) { # two
1285 ($interface_macro, $interface_macro_set) = split ' ', $in;
1288 $interface_macro = $in;
1289 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
1291 $interface = 1; # local
1292 $Interfaces = 1; # global
1295 sub INTERFACE_handler() {
1296 my $in = merge_section();
1298 TrimWhitespace($in);
1300 foreach (split /[\s,]+/, $in) {
1302 $name =~ s/^$Prefix//;
1303 $Interfaces{$name} = $_;
1306 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
1308 $interface = 1; # local
1309 $Interfaces = 1; # global
1312 sub CLEANUP_handler() { print_section() }
1313 sub PREINIT_handler() { print_section() }
1314 sub POSTCALL_handler() { print_section() }
1315 sub INIT_handler() { print_section() }
1323 # Parse alias definitions
1325 # alias = value alias = value ...
1327 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1329 $orig_alias = $alias;
1332 # check for optional package definition in the alias
1333 $alias = $Packprefix . $alias if $alias !~ /::/;
1335 # check for duplicate alias name & duplicate value
1336 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
1337 if defined $XsubAliases{$alias};
1339 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
1340 if $XsubAliasValues{$value};
1343 $XsubAliases{$alias} = $value;
1344 $XsubAliasValues{$value} = $orig_alias;
1347 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
1351 sub ATTRS_handler () {
1352 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1355 push @Attributes, $_;
1359 sub ALIAS_handler () {
1360 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1363 GetAliases($_) if $_;
1367 sub OVERLOAD_handler() {
1368 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1371 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1372 $Overload = 1 unless $Overload;
1373 my $overload = "$Package\::(".$1;
1375 " (void)${newXS}(\"$overload\", XS_$Full_func_name, file$proto);\n");
1380 sub FALLBACK_handler() {
1381 # the rest of the current line should contain either TRUE,
1386 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1387 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1388 UNDEF => "&PL_sv_undef",
1391 # check for valid FALLBACK value
1392 death ("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1394 $Fallback = $map{uc $_};
1398 sub REQUIRE_handler () {
1399 # the rest of the current line should contain a version number
1402 TrimWhitespace($Ver);
1404 death ("Error: REQUIRE expects a version number")
1407 # check that the version number is of the form n.n
1408 death ("Error: REQUIRE: expected a number, got '$Ver'")
1409 unless $Ver =~ /^\d+(\.\d*)?/;
1411 death ("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1412 unless $VERSION >= $Ver;
1415 sub VERSIONCHECK_handler () {
1416 # the rest of the current line should contain either ENABLE or
1421 # check for ENABLE/DISABLE
1422 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
1423 unless /^(ENABLE|DISABLE)/i;
1425 $WantVersionChk = 1 if $1 eq 'ENABLE';
1426 $WantVersionChk = 0 if $1 eq 'DISABLE';
1430 sub PROTOTYPE_handler () {
1433 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1434 if $proto_in_this_xsub ++;
1436 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1440 if ($_ eq 'DISABLE') {
1443 elsif ($_ eq 'ENABLE') {
1447 # remove any whitespace
1449 death("Error: Invalid prototype '$_'")
1450 unless ValidProtoString($_);
1451 $ProtoThisXSUB = C_string($_);
1455 # If no prototype specified, then assume empty prototype ""
1456 $ProtoThisXSUB = 2 unless $specified;
1461 sub SCOPE_handler () {
1462 death("Error: Only 1 SCOPE declaration allowed per xsub")
1463 if $scope_in_this_xsub ++;
1466 death ("Error: SCOPE: ENABLE/DISABLE")
1467 unless /^(ENABLE|DISABLE)\b/i;
1468 $ScopeThisXSUB = ( uc($1) eq 'ENABLE' );
1471 sub PROTOTYPES_handler () {
1472 # the rest of the current line should contain either ENABLE or
1477 # check for ENABLE/DISABLE
1478 death ("Error: PROTOTYPES: ENABLE/DISABLE")
1479 unless /^(ENABLE|DISABLE)/i;
1481 $WantPrototypes = 1 if $1 eq 'ENABLE';
1482 $WantPrototypes = 0 if $1 eq 'DISABLE';
1487 # Save the current file context.
1490 LastLine => $lastline,
1491 LastLineNo => $lastline_no,
1493 LineNo => \@line_no,
1494 Filename => $filename,
1495 Filepathname => $filepathname,
1497 IsPipe => scalar($filename =~ /\|\s*$/),
1503 sub INCLUDE_handler () {
1504 # the rest of the current line should contain a valid filename
1508 death("INCLUDE: filename missing")
1511 death("INCLUDE: output pipe is illegal")
1514 # simple minded recursion detector
1515 death("INCLUDE loop detected")
1516 if $IncludedFiles{$_};
1518 ++ $IncludedFiles{$_} unless /\|\s*$/;
1520 if (/\|\s*$/ && /^\s*perl\s/) {
1521 Warn("The INCLUDE directive with a command is discouraged." .
1522 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1523 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1524 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1525 " the use of \$^X as the currently running perl, see" .
1526 " 'perldoc perlxs' for details.");
1531 $FH = Symbol::gensym();
1534 open ($FH, "$_") or death("Cannot open '$_': $!");
1538 #/* INCLUDE: Including '$_' from '$filename' */
1543 $filepathname = File::Spec->catfile($dir, $filename);
1545 # Prime the pump by reading the first
1548 # skip leading blank lines
1550 last unless /^\s*$/;
1559 my @args = split /\s+/, $cmd;
1562 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1564 return join (' ', ($cmd, @args));
1567 sub INCLUDE_COMMAND_handler () {
1568 # the rest of the current line should contain a valid command
1572 $_ = QuoteArgs($_) if $^O eq 'VMS';
1574 death("INCLUDE_COMMAND: command missing")
1577 death("INCLUDE_COMMAND: pipes are illegal")
1578 if /^\s*\|/ or /\|\s*$/;
1580 PushXSStack( IsPipe => 1 );
1582 $FH = Symbol::gensym();
1584 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1585 # the same perl interpreter as we're currently running
1589 open ($FH, "-|", "$_")
1590 or death("Cannot run command '$_' to include its output: $!");
1594 #/* INCLUDE_COMMAND: Including output of '$_' from '$filename' */
1599 $filepathname = $filename;
1600 $filepathname =~ s/\"/\\"/g;
1602 # Prime the pump by reading the first
1605 # skip leading blank lines
1607 last unless /^\s*$/;
1615 return 0 unless $XSStack[-1]{type} eq 'file';
1617 my $data = pop @XSStack;
1618 my $ThisFile = $filename;
1619 my $isPipe = $data->{IsPipe};
1621 -- $IncludedFiles{$filename}
1626 $FH = $data->{Handle};
1627 # $filename is the leafname, which for some reason isused for diagnostic
1628 # messages, whereas $filepathname is the full pathname, and is used for
1630 $filename = $data->{Filename};
1631 $filepathname = $data->{Filepathname};
1632 $lastline = $data->{LastLine};
1633 $lastline_no = $data->{LastLineNo};
1634 @line = @{ $data->{Line} };
1635 @line_no = @{ $data->{LineNo} };
1637 if ($isPipe and $? ) {
1639 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
1645 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
1652 sub ValidProtoString ($) {
1655 if ( $string =~ /^$proto_re+$/ ) {
1665 $string =~ s[\\][\\\\]g;
1669 sub ProtoString ($) {
1672 $proto_letter{$type} or "\$";
1676 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
1678 my ($cpp, $cpplevel);
1680 if ($cpp =~ /^\#\s*if/) {
1683 elsif (!$cpplevel) {
1684 Warn("Warning: #else/elif/endif without #if in this function");
1685 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
1686 if $XSStack[-1]{type} eq 'if';
1689 elsif ($cpp =~ /^\#\s*endif/) {
1693 Warn("Warning: #if without #endif in this function") if $cpplevel;
1701 $text =~ s/\[\[/{/g;
1702 $text =~ s/\]\]/}/g;
1706 # Read next xsub into @line from ($lastline, <$FH>).
1709 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
1710 if !defined $lastline && $XSStack[-1]{type} eq 'if';
1713 return PopFile() if !defined $lastline;
1716 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1718 $Package = defined($2) ? $2 : ''; # keep -w happy
1719 $Prefix = defined($3) ? $3 : ''; # keep -w happy
1720 $Prefix = quotemeta $Prefix;
1721 ($Module_cname = $Module) =~ s/\W/_/g;
1722 ($Packid = $Package) =~ tr/:/_/;
1723 $Packprefix = $Package;
1724 $Packprefix .= "::" if $Packprefix ne "";
1729 # Skip embedded PODs
1730 while ($lastline =~ /^=/) {
1731 while ($lastline = <$FH>) {
1732 last if ($lastline =~ /^=cut\s*$/);
1734 death ("Error: Unterminated pod") unless $lastline;
1737 $lastline =~ s/^\s+$//;
1739 if ($lastline !~ /^\s*#/ ||
1741 # ANSI: if ifdef ifndef elif else endif define undef
1743 # gcc: warning include_next
1745 # others: ident (gcc notes that some cpps have this one)
1746 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1747 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
1748 push(@line, $lastline);
1749 push(@line_no, $lastline_no);
1752 # Read next line and continuation lines
1753 last unless defined($lastline = <$FH>);
1756 $lastline .= $tmp_line
1757 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
1760 $lastline =~ s/^\s+$//;
1762 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
1767 local($type, $num, $var, $init, $name_printed) = @_;
1768 local($arg) = "ST(" . ($num - 1) . ")";
1770 if ( $init =~ /^=/ ) {
1771 if ($name_printed) {
1772 eval qq/print " $init\\n"/;
1775 eval qq/print "\\t$var $init\\n"/;
1780 if ( $init =~ s/^\+// && $num ) {
1781 &generate_init($type, $num, $var, $name_printed);
1783 elsif ($name_printed) {
1788 eval qq/print "\\t$var;\\n"/;
1792 $deferred .= eval qq/"\\n\\t$init\\n"/;
1798 # work out the line number
1799 my $line_no = $line_no[@line_no - @line -1];
1801 print STDERR "@_ in $filename, line $line_no\n";
1815 local($type, $num, $var) = @_;
1816 local($arg) = "ST(" . ($num - 1) . ")";
1817 local($argoff) = $num - 1;
1821 $type = TidyType($type);
1822 blurt("Error: '$type' not in typemap"), return
1823 unless defined($type_kind{$type});
1825 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1826 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1827 $tk = $type_kind{$type};
1828 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1829 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1830 print "\t$var" unless $name_printed;
1831 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1832 die "default value not supported with length(NAME) supplied"
1833 if defined $defaults{$var};
1836 $type =~ tr/:/_/ unless $hiertype;
1837 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1838 unless defined $input_expr{$tk};
1839 $expr = $input_expr{$tk};
1840 if ($expr =~ /DO_ARRAY_ELEM/) {
1841 blurt("Error: '$subtype' not in typemap"), return
1842 unless defined($type_kind{$subtype});
1843 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1844 unless defined $input_expr{$type_kind{$subtype}};
1845 $subexpr = $input_expr{$type_kind{$subtype}};
1846 $subexpr =~ s/\$type/\$subtype/g;
1847 $subexpr =~ s/ntype/subtype/g;
1848 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1849 $subexpr =~ s/\n\t/\n\t\t/g;
1850 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1851 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1852 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1854 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1857 if (defined($defaults{$var})) {
1858 $expr =~ s/(\t+)/$1 /g;
1860 if ($name_printed) {
1864 eval qq/print "\\t$var;\\n"/;
1867 if ($defaults{$var} eq 'NO_INIT') {
1868 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1871 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1875 elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1876 if ($name_printed) {
1880 eval qq/print "\\t$var;\\n"/;
1883 $deferred .= eval qq/"\\n$expr;\\n"/;
1887 die "panic: do not know how to handle this branch for function pointers"
1889 eval qq/print "$expr;\\n"/;
1894 sub generate_output {
1895 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1896 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1897 local($argoff) = $num - 1;
1900 $type = TidyType($type);
1901 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1902 print "\t$arg = sv_newmortal();\n";
1903 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1904 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1907 blurt("Error: '$type' not in typemap"), return
1908 unless defined($type_kind{$type});
1909 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1910 unless defined $output_expr{$type_kind{$type}};
1911 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1912 $ntype =~ s/\(\)//g;
1913 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1914 $expr = $output_expr{$type_kind{$type}};
1915 if ($expr =~ /DO_ARRAY_ELEM/) {
1916 blurt("Error: '$subtype' not in typemap"), return
1917 unless defined($type_kind{$subtype});
1918 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1919 unless defined $output_expr{$type_kind{$subtype}};
1920 $subexpr = $output_expr{$type_kind{$subtype}};
1921 $subexpr =~ s/ntype/subtype/g;
1922 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1923 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1924 $subexpr =~ s/\n\t/\n\t\t/g;
1925 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1926 eval "print qq\a$expr\a";
1928 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1930 elsif ($var eq 'RETVAL') {
1931 if ($expr =~ /^\t\$arg = new/) {
1932 # We expect that $arg has refcnt 1, so we need to
1934 eval "print qq\a$expr\a";
1936 print "\tsv_2mortal(ST($num));\n";
1937 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1939 elsif ($expr =~ /^\s*\$arg\s*=/) {
1940 # We expect that $arg has refcnt >=1, so we need
1942 eval "print qq\a$expr\a";
1944 print "\tsv_2mortal(ST(0));\n";
1945 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1948 # Just hope that the entry would safely write it
1949 # over an already mortalized value. By
1950 # coincidence, something like $arg = &sv_undef
1952 print "\tST(0) = sv_newmortal();\n";
1953 eval "print qq\a$expr\a";
1955 # new mortals don't have set magic
1959 print "\tPUSHs(sv_newmortal());\n";
1961 eval "print qq\a$expr\a";
1963 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1965 elsif ($arg =~ /^ST\(\d+\)$/) {
1966 eval "print qq\a$expr\a";
1968 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1974 my($type, $varname) = @_;
1976 # C++ has :: in types too so skip this
1977 $type =~ tr/:/_/ unless $hiertype;
1978 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1980 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1981 (substr $type, pos $type, 0) = " $varname ";
1984 $type .= "\t$varname";
1991 #########################################################
1993 ExtUtils::ParseXS::CountLines;
1995 our $SECTION_END_MARKER;
1998 my ($class, $cfile, $fh) = @_;
1999 $cfile =~ s/\\/\\\\/g;
2000 $SECTION_END_MARKER = qq{#line --- "$cfile"};
2012 $self->{buffer} .= $_;
2013 while ($self->{buffer} =~ s/^([^\n]*\n)//) {
2015 ++ $self->{line_no};
2016 $line =~ s|^\#line\s+---(?=\s)|#line $self->{line_no}|;
2017 print {$self->{fh}} $line;
2025 $self->PRINT(sprintf($fmt, @_));
2029 # Not necessary if we're careful to end with a "\n"
2031 print {$self->{fh}} $self->{buffer};
2035 # This sub does nothing, but is neccessary for references to be released.
2039 return $SECTION_END_MARKER;