1 package ExtUtils::ParseXS;
3 use 5.006; # We use /??{}/ in regexes
10 use ExtUtils::ParseXS::Utilities qw(
11 standard_typemap_locations
16 our (@ISA, @EXPORT_OK, $VERSION);
18 @EXPORT_OK = qw(process_file);
20 $VERSION = eval $VERSION if $VERSION =~ /_/;
22 # use strict; # One of these days ...
24 my(@XSStack); # Stack of conditionals and INCLUDEs
25 my($XSS_work_idx, $cpp_next_tmp);
28 $ProtoUsed, @InitFileCode, $FH, $proto_re, $Overload, $errors, $Fallback,
29 $hiertype, $WantPrototypes, $WantVersionChk, $WantLineNumbers, $filepathname,
30 $dir, $filename, %IncludedFiles, %input_expr, %output_expr,
31 %type_kind, %proto_letter, $BLOCK_re, $lastline, $lastline_no, $Package,
32 $Prefix, @line, %args_match, %defaults, %var_types, %arg_list, @proto_arg,
33 $processing_arg_with_types, %argtype_seen, %in_out, %lengthof,
34 $proto_in_this_xsub, $scope_in_this_xsub, $interface,
35 $interface_macro, $interface_macro_set, $ProtoThisXSUB, $ScopeThisXSUB,
36 @line_no, $ret_type, $func_name, $Full_func_name, $Packprefix, $Packid,
37 %XsubAliases, %XsubAliasValues, %Interfaces, @Attributes, %outargs, $pname,
43 # Allow for $package->process_file(%hash) in the future
44 my ($pkg, %args) = @_ % 2 ? @_ : (__PACKAGE__, @_);
46 $ProtoUsed = exists $args{prototypes};
66 my ($Is_VMS, $SymSet);
69 # Establish set of global symbols with max length 28, since xsubpp
70 # will later add the 'XS_' prefix.
71 require ExtUtils::XSSymSet;
72 $SymSet = new ExtUtils::XSSymSet 28;
74 @XSStack = ({type => 'none'});
75 ($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
77 $FH = Symbol::gensym();
78 $proto_re = "[" . quotemeta('\$%&*@;[]_') . "]";
81 $Fallback = '&PL_sv_undef';
83 # Most of the 1500 lines below uses these globals. We'll have to
84 # clean this up sometime, probably. For now, we just pull them out
87 $hiertype = $args{hiertype};
88 $WantPrototypes = $args{prototypes};
89 $WantVersionChk = $args{versioncheck};
90 my $except = $args{except} ? ' TRY' : '';
91 $WantLineNumbers = $args{linenumbers};
92 my $WantOptimize = $args{optimize};
93 my $process_inout = $args{inout};
94 my $process_argtypes = $args{argtypes};
95 my @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 my $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 = tidy_type($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;
215 $bal = qr[(?:(?>[^()]+)|\((??{ $bal })\))*]; # ()-balanced
216 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
217 $size = qr[,\s* (??{ $bal }) ]x; # Third arg (to setpvn)
220 foreach my $key (keys %output_expr) {
221 # We can still bootstrap compile 're', because in code re.pm is
222 # available to miniperl, and does not attempt to load the XS code.
225 my ($t, $with_size, $arg, $sarg) =
226 ($output_expr{$key} =~
227 m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
228 \s* \( \s* $cast \$arg \s* ,
229 \s* ( (??{ $bal }) ) # Set from
230 ( (??{ $size }) )? # Possible sizeof set-from
234 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
237 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
239 # Match an XS keyword
240 $BLOCK_re = '\s*(' . join('|', qw(
241 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE
242 OUTPUT CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE
243 VERSIONCHECK INCLUDE INCLUDE_COMMAND SCOPE INTERFACE
244 INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
247 our ($C_group_rex, $C_arg);
248 # Group in C (no support for comments or literals)
249 $C_group_rex = qr/ [({\[]
250 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
252 # Chunk in C without comma at toplevel (no comments):
253 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
254 | (??{ $C_group_rex })
255 | " (?: (?> [^\\"]+ )
257 )* " # String literal
258 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
261 # Identify the version of xsubpp used
264 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
265 * contents of $filename. Do not edit this file, edit $filename instead.
267 * ANY CHANGES MADE HERE WILL BE LOST!
274 print("#line 1 \"$filepathname\"\n")
280 my $podstartline = $.;
283 # We can't just write out a /* */ comment, as our embedded
284 # POD might itself be in a comment. We can't put a /**/
285 # comment inside #if 0, as the C standard says that the source
286 # file is decomposed into preprocessing characters in the stage
287 # before preprocessing commands are executed.
288 # I don't want to leave the text as barewords, because the spec
289 # isn't clear whether macros are expanded before or after
290 # preprocessing commands are executed, and someone pathological
291 # may just have defined one of the 3 words as a macro that does
292 # something strange. Multiline strings are illegal in C, so
293 # the "" we write must be a string literal. And they aren't
294 # concatenated until 2 steps later, so we are safe.
296 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
297 printf("#line %d \"$filepathname\"\n", $. + 1)
303 # At this point $. is at end of file so die won't state the start
304 # of the problem, and as we haven't yet read any lines &death won't
305 # show the correct line in the message either.
306 die ("Error: Unterminated pod in $filename, line $podstartline\n")
309 last if ($Package, $Prefix) =
310 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
314 unless (defined $_) {
315 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
316 exit 0; # Not a fatal error for the caller process
319 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
322 #ifndef PERL_UNUSED_VAR
323 # define PERL_UNUSED_VAR(var) if (0) var = var
329 #ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
330 #define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)
332 /* prototype to pass -Wmissing-prototypes */
334 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params);
337 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params)
339 const GV *const gv = CvGV(cv);
341 PERL_ARGS_ASSERT_CROAK_XS_USAGE;
344 const char *const gvname = GvNAME(gv);
345 const HV *const stash = GvSTASH(gv);
346 const char *const hvname = stash ? HvNAME(stash) : NULL;
349 Perl_croak(aTHX_ "Usage: %s::%s(%s)", hvname, gvname, params);
351 Perl_croak(aTHX_ "Usage: %s(%s)", gvname, params);
353 /* Pants. I don't think that it should be possible to get here. */
354 Perl_croak(aTHX_ "Usage: CODE(0x%"UVxf")(%s)", PTR2UV(cv), params);
357 #undef PERL_ARGS_ASSERT_CROAK_XS_USAGE
359 #ifdef PERL_IMPLICIT_CONTEXT
360 #define croak_xs_usage(a,b) S_croak_xs_usage(aTHX_ a,b)
362 #define croak_xs_usage S_croak_xs_usage
367 /* NOTE: the prototype of newXSproto() is different in versions of perls,
368 * so we define a portable version of newXSproto()
371 #define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
373 #define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
374 #endif /* !defined(newXS_flags) */
378 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
383 my (@BootCode, @outlist, $prepush_done, $xsreturn, $func_header, $orig_args, );
385 while (fetch_para()) {
386 # Print initial preprocessor statements and blank lines
387 while (@line && $line[0] !~ /^[^\#]/) {
388 my $line = shift(@line);
390 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
392 if ($statement eq 'if') {
393 $XSS_work_idx = @XSStack;
394 push(@XSStack, {type => 'if'});
397 death ("Error: `$statement' with no matching `if'")
398 if $XSStack[-1]{type} ne 'if';
399 if ($XSStack[-1]{varname}) {
400 push(@InitFileCode, "#endif\n");
401 push(@BootCode, "#endif");
404 my(@fns) = keys %{$XSStack[-1]{functions}};
405 if ($statement ne 'endif') {
406 # Hide the functions defined in other #if branches, and reset.
407 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
408 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
411 my($tmp) = pop(@XSStack);
412 0 while (--$XSS_work_idx
413 && $XSStack[$XSS_work_idx]{type} ne 'if');
414 # Keep all new defined functions
415 push(@fns, keys %{$tmp->{other_functions}});
416 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
421 next PARAGRAPH unless @line;
423 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
424 # We are inside an #if, but have not yet #defined its xsubpp variable.
425 print "#define $cpp_next_tmp 1\n\n";
426 push(@InitFileCode, "#if $cpp_next_tmp\n");
427 push(@BootCode, "#if $cpp_next_tmp");
428 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
431 death ("Code is not inside a function"
432 ." (maybe last function was ended by a blank line "
433 ." followed by a statement on column one?)")
434 if $line[0] =~ /^\s/;
436 my ($class, $externC, $static, $ellipsis, $wantRETVAL, $RETVAL_no_return);
437 my (@fake_INPUT_pre); # For length(s) generated variables
440 # initialize info arrays
446 undef($processing_arg_with_types);
447 undef(%argtype_seen);
451 undef($proto_in_this_xsub);
452 undef($scope_in_this_xsub);
454 undef($prepush_done);
455 $interface_macro = 'XSINTERFACE_FUNC';
456 $interface_macro_set = 'XSINTERFACE_FUNC_SET';
457 $ProtoThisXSUB = $WantPrototypes;
462 while (my $kwd = check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
463 &{"${kwd}_handler"}();
464 next PARAGRAPH unless @line;
468 if (check_keyword("BOOT")) {
470 push (@BootCode, "#line $line_no[@line_no - @line] \"$filepathname\"")
471 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
472 push (@BootCode, @line, "");
476 # extract return type, function name and arguments
477 ($ret_type) = tidy_type($_);
478 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
480 # Allow one-line ANSI-like declaration
483 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
485 # a function definition needs at least 2 lines
486 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
489 $externC = 1 if $ret_type =~ s/^extern "C"\s+//;
490 $static = 1 if $ret_type =~ s/^static\s+//;
492 $func_header = shift(@line);
493 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
494 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
496 ($class, $func_name, $orig_args) = ($1, $2, $3);
497 $class = "$4 $class" if $4;
498 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
500 ($clean_func_name = $func_name) =~ s/^$Prefix//;
501 $Full_func_name = "${Packid}_$clean_func_name";
503 $Full_func_name = $SymSet->addsym($Full_func_name);
506 # Check for duplicate function definition
507 for my $tmp (@XSStack) {
508 next unless defined $tmp->{functions}{$Full_func_name};
509 Warn("Warning: duplicate function definition '$clean_func_name' detected");
512 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++;
513 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
516 $orig_args =~ s/\\\s*/ /g; # process line continuations
519 my %only_C_inlist; # Not in the signature of Perl function
520 if ($process_argtypes and $orig_args =~ /\S/) {
521 my $args = "$orig_args ,";
522 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
523 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
527 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
528 my ($pre, $name) = ($arg =~ /(.*?) \s*
529 \b ( \w+ | length\( \s*\w+\s* \) )
531 next unless defined($pre) && length($pre);
534 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
536 $out_type = $type if $type ne 'IN';
537 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
538 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
541 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
542 $name = "XSauto_length_of_$1";
544 die "Default value on length() argument: `$_'"
547 if (length $pre or $islength) { # Has a type
549 push @fake_INPUT_pre, $arg;
552 push @fake_INPUT, $arg;
554 # warn "pushing '$arg'\n";
555 $argtype_seen{$name}++;
556 $_ = "$name$default"; # Assigns to @args
558 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
559 push @outlist, $name if $out_type =~ /OUTLIST$/;
560 $in_out{$name} = $out_type if $out_type;
564 @args = split(/\s*,\s*/, $orig_args);
565 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
569 @args = split(/\s*,\s*/, $orig_args);
571 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
573 next if $out_type eq 'IN';
574 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
575 push @outlist, $name if $out_type =~ /OUTLIST$/;
576 $in_out{$_} = $out_type;
580 if (defined($class)) {
581 my $arg0 = ((defined($static) or $func_name eq 'new')
583 unshift(@args, $arg0);
588 my $report_args = '';
589 foreach my $i (0 .. $#args) {
590 if ($args[$i] =~ s/\.\.\.//) {
592 if ($args[$i] eq '' && $i == $#args) {
593 $report_args .= ", ...";
598 if ($only_C_inlist{$args[$i]}) {
599 push @args_num, undef;
602 push @args_num, ++$num_args;
603 $report_args .= ", $args[$i]";
605 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
608 $defaults{$args[$i]} = $2;
609 $defaults{$args[$i]} =~ s/"/\\"/g;
611 $proto_arg[$i+1] = '$';
613 $min_args = $num_args - $extra_args;
614 $report_args =~ s/"/\\"/g;
615 $report_args =~ s/^,\s+//;
616 my @func_args = @args;
617 shift @func_args if defined($class);
620 s/^/&/ if $in_out{$_};
622 $func_args = join(", ", @func_args);
623 @args_match{@args} = @args_num;
625 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
626 $CODE = grep(/^\s*CODE\s*:/, @line);
627 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
628 # to set explicit return values.
629 $EXPLICIT_RETURN = ($CODE &&
630 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
631 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
632 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
634 $xsreturn = 1 if $EXPLICIT_RETURN;
636 $externC = $externC ? qq[extern "C"] : "";
638 # print function header
641 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
642 #XS(XS_${Full_func_name})
650 print Q(<<"EOF") if $ALIAS;
653 print Q(<<"EOF") if $INTERFACE;
654 # dXSFUNCTION($ret_type);
657 $cond = ($min_args ? qq(items < $min_args) : 0);
659 elsif ($min_args == $num_args) {
660 $cond = qq(items != $min_args);
663 $cond = qq(items < $min_args || items > $num_args);
666 print Q(<<"EOF") if $except;
674 # croak_xs_usage(cv, "$report_args");
678 # cv likely to be unused
680 # PERL_UNUSED_VAR(cv); /* -W */
684 #gcc -Wall: if an xsub has PPCODE is used
685 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
686 #hence `ax' (setup by dXSARGS) is unused
687 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
688 #but such a move could break third-party extensions
689 print Q(<<"EOF") if $PPCODE;
690 # PERL_UNUSED_VAR(ax); /* -Wall */
693 print Q(<<"EOF") if $PPCODE;
697 # Now do a block of some sort.
700 $cond = ''; # last CASE: condidional
701 push(@line, "$END:");
702 push(@line_no, $line_no[-1]);
706 &CASE_handler if check_keyword("CASE");
711 # do initialization of input variables
719 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
721 print Q(<<"EOF") if $ScopeThisXSUB;
726 if (!$thisdone && defined($class)) {
727 if (defined($static) or $func_name eq 'new') {
729 $var_types{"CLASS"} = "char *";
730 &generate_init("char *", 1, "CLASS");
734 $var_types{"THIS"} = "$class *";
735 &generate_init("$class *", 1, "THIS");
740 if (/^\s*NOT_IMPLEMENTED_YET/) {
741 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
745 if ($ret_type ne "void") {
746 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
748 $args_match{"RETVAL"} = 0;
749 $var_types{"RETVAL"} = $ret_type;
751 if $WantOptimize and $targetable{$type_kind{$ret_type}};
754 if (@fake_INPUT or @fake_INPUT_pre) {
755 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
757 $processing_arg_with_types = 1;
762 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
764 if (check_keyword("PPCODE")) {
766 death ("PPCODE must be last thing") if @line;
767 print "\tLEAVE;\n" if $ScopeThisXSUB;
768 print "\tPUTBACK;\n\treturn;\n";
770 elsif (check_keyword("CODE")) {
773 elsif (defined($class) and $func_name eq "DESTROY") {
775 print "delete THIS;\n";
779 if ($ret_type ne "void") {
783 if (defined($static)) {
784 if ($func_name eq 'new') {
785 $func_name = "$class";
791 elsif (defined($class)) {
792 if ($func_name eq 'new') {
793 $func_name .= " $class";
799 $func_name =~ s/^\Q$args{'s'}//
800 if exists $args{'s'};
801 $func_name = 'XSFUNCTION' if $interface;
802 print "$func_name($func_args);\n";
806 # do output variables
807 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
808 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
809 # $wantRETVAL set if 'RETVAL =' autogenerated
810 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
812 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
814 &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
815 for grep $in_out{$_} =~ /OUT$/, keys %in_out;
817 # all OUTPUT done, so now push the return value on the stack
818 if ($gotRETVAL && $RETVAL_code) {
819 print "\t$RETVAL_code\n";
821 elsif ($gotRETVAL || $wantRETVAL) {
822 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
824 my $type = $ret_type;
826 # 0: type, 1: with_size, 2: how, 3: how_size
827 if ($t and not $t->[1] and $t->[0] eq 'p') {
828 # PUSHp corresponds to setpvn. Treate setpv directly
829 my $what = eval qq("$t->[2]");
832 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
836 my $what = eval qq("$t->[2]");
840 $size = '' unless defined $size;
841 $size = eval qq("$size");
843 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
847 # RETVAL almost never needs SvSETMAGIC()
848 &generate_output($ret_type, 0, 'RETVAL', 0);
852 $xsreturn = 1 if $ret_type ne "void";
855 print "\tXSprePUSH;" if $c and not $prepush_done;
856 print "\tEXTEND(SP,$c);\n" if $c;
858 generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
861 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
863 print Q(<<"EOF") if $ScopeThisXSUB;
866 print Q(<<"EOF") if $ScopeThisXSUB and not $PPCODE;
870 # print function trailer
874 print Q(<<"EOF") if $except;
877 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
880 if (check_keyword("CASE")) {
881 blurt ("Error: No `CASE:' at top of function")
883 $_ = "CASE: $_"; # Restore CASE: label
886 last if $_ eq "$END:";
887 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
890 print Q(<<"EOF") if $except;
892 # Perl_croak(aTHX_ errbuf);
896 print Q(<<"EOF") unless $PPCODE;
897 # XSRETURN($xsreturn);
901 print Q(<<"EOF") unless $PPCODE;
911 our $newXS = "newXS";
914 # Build the prototype string for the xsub
915 if ($ProtoThisXSUB) {
916 $newXS = "newXSproto_portable";
918 if ($ProtoThisXSUB eq 2) {
919 # User has specified empty prototype
921 elsif ($ProtoThisXSUB eq 1) {
923 if ($min_args < $num_args) {
925 $proto_arg[$min_args] .= ";";
927 push @proto_arg, "$s\@"
930 $proto = join ("", grep defined, @proto_arg);
933 # User has specified a prototype
934 $proto = $ProtoThisXSUB;
936 $proto = qq{, "$proto"};
940 $XsubAliases{$pname} = 0
941 unless defined $XsubAliases{$pname};
942 while ( ($name, $value) = each %XsubAliases) {
943 push(@InitFileCode, Q(<<"EOF"));
944 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
945 # XSANY.any_i32 = $value;
949 elsif (@Attributes) {
950 push(@InitFileCode, Q(<<"EOF"));
951 # cv = ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);
952 # apply_attrs_string("$Package", cv, "@Attributes", 0);
956 while ( ($name, $value) = each %Interfaces) {
957 $name = "$Package\::$name" unless $name =~ /::/;
958 push(@InitFileCode, Q(<<"EOF"));
959 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
960 # $interface_macro_set(cv,$value);
964 elsif($newXS eq 'newXS'){ # work around P5NCI's empty newXS macro
966 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
970 " (void)${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
974 if ($Overload) # make it findable with fetchmethod
977 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
978 #XS(XS_${Packid}_nil)
985 unshift(@InitFileCode, <<"MAKE_FETCHMETHOD_WORK");
986 /* Making a sub named "${Package}::()" allows the package */
987 /* to be findable via fetchmethod(), and causes */
988 /* overload::Overloaded("${Package}") to return true. */
989 (void)${newXS}("${Package}::()", XS_${Packid}_nil, file$proto);
990 MAKE_FETCHMETHOD_WORK
993 # print initialization routine
1002 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1003 #XS(boot_$Module_cname)
1015 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
1016 #file name argument. If the wrong qualifier is used, it causes breakage with
1017 #C++ compilers and warnings with recent gcc.
1018 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1019 #so `file' is unused
1020 print Q(<<"EOF") if $Full_func_name;
1021 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
1022 # char* file = __FILE__;
1024 # const char* file = __FILE__;
1031 # PERL_UNUSED_VAR(cv); /* -W */
1032 # PERL_UNUSED_VAR(items); /* -W */
1035 print Q(<<"EOF") if $WantVersionChk;
1036 # XS_VERSION_BOOTCHECK;
1040 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1046 print Q(<<"EOF") if ($Overload);
1047 # /* register the overloading (type 'A') magic */
1048 # PL_amagic_generation++;
1049 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1050 # /* mentioned above, and looks in the SV* slot of it for */
1051 # /* the "fallback" status. */
1053 # get_sv( "${Package}::()", TRUE ),
1058 print @InitFileCode;
1060 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1065 print "\n /* Initialisation Section */\n\n";
1068 print "\n /* End of Initialisation Section */\n\n";
1072 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
1073 # if (PL_unitcheckav)
1074 # call_list(PL_scopestack_ix, PL_unitcheckav);
1084 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1089 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
1095 sub errors { $errors }
1097 # Input: ($_, @line) == unparsed input.
1098 # Output: ($_, @line) == (rest of line, following lines).
1099 # Return: the matched keyword if found, otherwise 0
1101 $_ = shift(@line) while !/\S/ && @line;
1102 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1106 # the "do" is required for right semantics
1107 do { $_ = shift(@line) } while !/\S/ && @line;
1109 print("#line ", $line_no[@line_no - @line -1], " \"$filepathname\"\n")
1110 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1111 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1114 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
1120 while (!/\S/ && @line) {
1124 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1131 sub process_keyword($) {
1135 &{"${kwd}_handler"}()
1136 while $kwd = check_keyword($pattern);
1140 blurt ("Error: `CASE:' after unconditional `CASE:'")
1141 if $condnum && $cond eq '';
1143 trim_whitespace($cond);
1144 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
1149 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1150 last if /^\s*NOT_IMPLEMENTED_YET/;
1151 next unless /\S/; # skip blank lines
1153 trim_whitespace($_);
1156 # remove trailing semicolon if no initialisation
1157 s/\s*;$//g unless /[=;+].*\S/;
1159 # Process the length(foo) declarations
1160 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1161 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1162 $lengthof{$2} = $name;
1163 # $islengthof{$name} = $1;
1164 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1167 # check for optional initialisation code
1169 $var_init = $1 if s/\s*([=;+].*)$//s;
1170 $var_init =~ s/"/\\"/g;
1173 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1174 or blurt("Error: invalid argument declaration '$line'"), next;
1176 # Check for duplicate definitions
1177 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
1178 if $arg_list{$var_name}++
1179 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
1181 $thisdone |= $var_name eq "THIS";
1182 $retvaldone |= $var_name eq "RETVAL";
1183 $var_types{$var_name} = $var_type;
1184 # XXXX This check is a safeguard against the unfinished conversion of
1185 # generate_init(). When generate_init() is fixed,
1186 # one can use 2-args map_type() unconditionally.
1187 if ($var_type =~ / \( \s* \* \s* \) /x) {
1188 # Function pointers are not yet supported with &output_init!
1189 print "\t" . &map_type($var_type, $var_name);
1193 print "\t" . &map_type($var_type);
1196 $var_num = $args_match{$var_name};
1198 $proto_arg[$var_num] = ProtoString($var_type)
1200 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
1201 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1202 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
1203 and $var_init !~ /\S/) {
1204 if ($name_printed) {
1208 print "\t$var_name;\n";
1211 elsif ($var_init =~ /\S/) {
1212 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
1215 # generate initialization code
1216 &generate_init($var_type, $var_num, $var_name, $name_printed);
1224 sub OUTPUT_handler {
1225 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1227 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1228 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
1231 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1232 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1233 if $outargs{$outarg} ++;
1234 if (!$gotRETVAL and $outarg eq 'RETVAL') {
1235 # deal with RETVAL last
1236 $RETVAL_code = $outcode;
1240 blurt ("Error: OUTPUT $outarg not an argument"), next
1241 unless defined($args_match{$outarg});
1242 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1243 unless defined $var_types{$outarg};
1244 $var_num = $args_match{$outarg};
1246 print "\t$outcode\n";
1247 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
1250 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
1252 delete $in_out{$outarg} # No need to auto-OUTPUT
1253 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
1257 sub C_ARGS_handler() {
1258 my $in = merge_section();
1260 trim_whitespace($in);
1264 sub INTERFACE_MACRO_handler() {
1265 my $in = merge_section();
1267 trim_whitespace($in);
1268 if ($in =~ /\s/) { # two
1269 ($interface_macro, $interface_macro_set) = split ' ', $in;
1272 $interface_macro = $in;
1273 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
1275 $interface = 1; # local
1276 $Interfaces = 1; # global
1279 sub INTERFACE_handler() {
1280 my $in = merge_section();
1282 trim_whitespace($in);
1284 foreach (split /[\s,]+/, $in) {
1286 $name =~ s/^$Prefix//;
1287 $Interfaces{$name} = $_;
1290 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
1292 $interface = 1; # local
1293 $Interfaces = 1; # global
1296 sub CLEANUP_handler() { print_section() }
1297 sub PREINIT_handler() { print_section() }
1298 sub POSTCALL_handler() { print_section() }
1299 sub INIT_handler() { print_section() }
1307 # Parse alias definitions
1309 # alias = value alias = value ...
1311 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1313 $orig_alias = $alias;
1316 # check for optional package definition in the alias
1317 $alias = $Packprefix . $alias if $alias !~ /::/;
1319 # check for duplicate alias name & duplicate value
1320 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
1321 if defined $XsubAliases{$alias};
1323 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
1324 if $XsubAliasValues{$value};
1327 $XsubAliases{$alias} = $value;
1328 $XsubAliasValues{$value} = $orig_alias;
1331 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
1335 sub ATTRS_handler () {
1336 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1338 trim_whitespace($_);
1339 push @Attributes, $_;
1343 sub ALIAS_handler () {
1344 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1346 trim_whitespace($_);
1347 GetAliases($_) if $_;
1351 sub OVERLOAD_handler() {
1352 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1354 trim_whitespace($_);
1355 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1356 $Overload = 1 unless $Overload;
1357 my $overload = "$Package\::(".$1;
1359 " (void)${newXS}(\"$overload\", XS_$Full_func_name, file$proto);\n");
1364 sub FALLBACK_handler() {
1365 # the rest of the current line should contain either TRUE,
1368 trim_whitespace($_);
1370 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1371 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1372 UNDEF => "&PL_sv_undef",
1375 # check for valid FALLBACK value
1376 death ("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1378 $Fallback = $map{uc $_};
1382 sub REQUIRE_handler () {
1383 # the rest of the current line should contain a version number
1386 trim_whitespace($Ver);
1388 death ("Error: REQUIRE expects a version number")
1391 # check that the version number is of the form n.n
1392 death ("Error: REQUIRE: expected a number, got '$Ver'")
1393 unless $Ver =~ /^\d+(\.\d*)?/;
1395 death ("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1396 unless $VERSION >= $Ver;
1399 sub VERSIONCHECK_handler () {
1400 # the rest of the current line should contain either ENABLE or
1403 trim_whitespace($_);
1405 # check for ENABLE/DISABLE
1406 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
1407 unless /^(ENABLE|DISABLE)/i;
1409 $WantVersionChk = 1 if $1 eq 'ENABLE';
1410 $WantVersionChk = 0 if $1 eq 'DISABLE';
1414 sub PROTOTYPE_handler () {
1417 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1418 if $proto_in_this_xsub ++;
1420 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1423 trim_whitespace($_);
1424 if ($_ eq 'DISABLE') {
1427 elsif ($_ eq 'ENABLE') {
1431 # remove any whitespace
1433 death("Error: Invalid prototype '$_'")
1434 unless ValidProtoString($_);
1435 $ProtoThisXSUB = C_string($_);
1439 # If no prototype specified, then assume empty prototype ""
1440 $ProtoThisXSUB = 2 unless $specified;
1445 sub SCOPE_handler () {
1446 death("Error: Only 1 SCOPE declaration allowed per xsub")
1447 if $scope_in_this_xsub ++;
1449 trim_whitespace($_);
1450 death ("Error: SCOPE: ENABLE/DISABLE")
1451 unless /^(ENABLE|DISABLE)\b/i;
1452 $ScopeThisXSUB = ( uc($1) eq 'ENABLE' );
1455 sub PROTOTYPES_handler () {
1456 # the rest of the current line should contain either ENABLE or
1459 trim_whitespace($_);
1461 # check for ENABLE/DISABLE
1462 death ("Error: PROTOTYPES: ENABLE/DISABLE")
1463 unless /^(ENABLE|DISABLE)/i;
1465 $WantPrototypes = 1 if $1 eq 'ENABLE';
1466 $WantPrototypes = 0 if $1 eq 'DISABLE';
1471 # Save the current file context.
1474 LastLine => $lastline,
1475 LastLineNo => $lastline_no,
1477 LineNo => \@line_no,
1478 Filename => $filename,
1479 Filepathname => $filepathname,
1481 IsPipe => scalar($filename =~ /\|\s*$/),
1487 sub INCLUDE_handler () {
1488 # the rest of the current line should contain a valid filename
1490 trim_whitespace($_);
1492 death("INCLUDE: filename missing")
1495 death("INCLUDE: output pipe is illegal")
1498 # simple minded recursion detector
1499 death("INCLUDE loop detected")
1500 if $IncludedFiles{$_};
1502 ++ $IncludedFiles{$_} unless /\|\s*$/;
1504 if (/\|\s*$/ && /^\s*perl\s/) {
1505 Warn("The INCLUDE directive with a command is discouraged." .
1506 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1507 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1508 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1509 " the use of \$^X as the currently running perl, see" .
1510 " 'perldoc perlxs' for details.");
1515 $FH = Symbol::gensym();
1518 open ($FH, "$_") or death("Cannot open '$_': $!");
1522 #/* INCLUDE: Including '$_' from '$filename' */
1527 $filepathname = File::Spec->catfile($dir, $filename);
1529 # Prime the pump by reading the first
1532 # skip leading blank lines
1534 last unless /^\s*$/;
1543 my @args = split /\s+/, $cmd;
1546 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1548 return join (' ', ($cmd, @args));
1551 sub INCLUDE_COMMAND_handler () {
1552 # the rest of the current line should contain a valid command
1554 trim_whitespace($_);
1556 $_ = QuoteArgs($_) if $^O eq 'VMS';
1558 death("INCLUDE_COMMAND: command missing")
1561 death("INCLUDE_COMMAND: pipes are illegal")
1562 if /^\s*\|/ or /\|\s*$/;
1564 PushXSStack( IsPipe => 1 );
1566 $FH = Symbol::gensym();
1568 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1569 # the same perl interpreter as we're currently running
1573 open ($FH, "-|", "$_")
1574 or death("Cannot run command '$_' to include its output: $!");
1578 #/* INCLUDE_COMMAND: Including output of '$_' from '$filename' */
1583 $filepathname = $filename;
1584 $filepathname =~ s/\"/\\"/g;
1586 # Prime the pump by reading the first
1589 # skip leading blank lines
1591 last unless /^\s*$/;
1599 return 0 unless $XSStack[-1]{type} eq 'file';
1601 my $data = pop @XSStack;
1602 my $ThisFile = $filename;
1603 my $isPipe = $data->{IsPipe};
1605 -- $IncludedFiles{$filename}
1610 $FH = $data->{Handle};
1611 # $filename is the leafname, which for some reason isused for diagnostic
1612 # messages, whereas $filepathname is the full pathname, and is used for
1614 $filename = $data->{Filename};
1615 $filepathname = $data->{Filepathname};
1616 $lastline = $data->{LastLine};
1617 $lastline_no = $data->{LastLineNo};
1618 @line = @{ $data->{Line} };
1619 @line_no = @{ $data->{LineNo} };
1621 if ($isPipe and $? ) {
1623 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
1629 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
1636 sub ValidProtoString ($) {
1639 if ( $string =~ /^$proto_re+$/ ) {
1649 $string =~ s[\\][\\\\]g;
1653 sub ProtoString ($) {
1656 $proto_letter{$type} or "\$";
1660 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
1662 my ($cpp, $cpplevel);
1664 if ($cpp =~ /^\#\s*if/) {
1667 elsif (!$cpplevel) {
1668 Warn("Warning: #else/elif/endif without #if in this function");
1669 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
1670 if $XSStack[-1]{type} eq 'if';
1673 elsif ($cpp =~ /^\#\s*endif/) {
1677 Warn("Warning: #if without #endif in this function") if $cpplevel;
1685 $text =~ s/\[\[/{/g;
1686 $text =~ s/\]\]/}/g;
1690 # Read next xsub into @line from ($lastline, <$FH>).
1693 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
1694 if !defined $lastline && $XSStack[-1]{type} eq 'if';
1697 return PopFile() if !defined $lastline;
1700 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1702 $Package = defined($2) ? $2 : ''; # keep -w happy
1703 $Prefix = defined($3) ? $3 : ''; # keep -w happy
1704 $Prefix = quotemeta $Prefix;
1705 ($Module_cname = $Module) =~ s/\W/_/g;
1706 ($Packid = $Package) =~ tr/:/_/;
1707 $Packprefix = $Package;
1708 $Packprefix .= "::" if $Packprefix ne "";
1713 # Skip embedded PODs
1714 while ($lastline =~ /^=/) {
1715 while ($lastline = <$FH>) {
1716 last if ($lastline =~ /^=cut\s*$/);
1718 death ("Error: Unterminated pod") unless $lastline;
1721 $lastline =~ s/^\s+$//;
1723 if ($lastline !~ /^\s*#/ ||
1725 # ANSI: if ifdef ifndef elif else endif define undef
1727 # gcc: warning include_next
1729 # others: ident (gcc notes that some cpps have this one)
1730 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1731 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
1732 push(@line, $lastline);
1733 push(@line_no, $lastline_no);
1736 # Read next line and continuation lines
1737 last unless defined($lastline = <$FH>);
1740 $lastline .= $tmp_line
1741 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
1744 $lastline =~ s/^\s+$//;
1746 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
1751 local($type, $num, $var, $init, $name_printed) = @_;
1752 local($arg) = "ST(" . ($num - 1) . ")";
1754 if ( $init =~ /^=/ ) {
1755 if ($name_printed) {
1756 eval qq/print " $init\\n"/;
1759 eval qq/print "\\t$var $init\\n"/;
1764 if ( $init =~ s/^\+// && $num ) {
1765 &generate_init($type, $num, $var, $name_printed);
1767 elsif ($name_printed) {
1772 eval qq/print "\\t$var;\\n"/;
1776 $deferred .= eval qq/"\\n\\t$init\\n"/;
1782 # work out the line number
1783 my $warn_line_number = $line_no[@line_no - @line -1];
1785 print STDERR "@_ in $filename, line $warn_line_number\n";
1799 local($type, $num, $var) = @_;
1800 local($arg) = "ST(" . ($num - 1) . ")";
1801 local($argoff) = $num - 1;
1805 $type = tidy_type($type);
1806 blurt("Error: '$type' not in typemap"), return
1807 unless defined($type_kind{$type});
1809 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1810 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1811 $tk = $type_kind{$type};
1812 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1813 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1814 print "\t$var" unless $name_printed;
1815 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1816 die "default value not supported with length(NAME) supplied"
1817 if defined $defaults{$var};
1820 $type =~ tr/:/_/ unless $hiertype;
1821 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1822 unless defined $input_expr{$tk};
1823 $expr = $input_expr{$tk};
1824 if ($expr =~ /DO_ARRAY_ELEM/) {
1825 blurt("Error: '$subtype' not in typemap"), return
1826 unless defined($type_kind{$subtype});
1827 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1828 unless defined $input_expr{$type_kind{$subtype}};
1829 $subexpr = $input_expr{$type_kind{$subtype}};
1830 $subexpr =~ s/\$type/\$subtype/g;
1831 $subexpr =~ s/ntype/subtype/g;
1832 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1833 $subexpr =~ s/\n\t/\n\t\t/g;
1834 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1835 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1836 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1838 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1841 if (defined($defaults{$var})) {
1842 $expr =~ s/(\t+)/$1 /g;
1844 if ($name_printed) {
1848 eval qq/print "\\t$var;\\n"/;
1851 if ($defaults{$var} eq 'NO_INIT') {
1852 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1855 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1859 elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1860 if ($name_printed) {
1864 eval qq/print "\\t$var;\\n"/;
1867 $deferred .= eval qq/"\\n$expr;\\n"/;
1871 die "panic: do not know how to handle this branch for function pointers"
1873 eval qq/print "$expr;\\n"/;
1878 sub generate_output {
1879 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1880 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1881 local($argoff) = $num - 1;
1884 $type = tidy_type($type);
1885 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1886 print "\t$arg = sv_newmortal();\n";
1887 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1888 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1891 blurt("Error: '$type' not in typemap"), return
1892 unless defined($type_kind{$type});
1893 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1894 unless defined $output_expr{$type_kind{$type}};
1895 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1896 $ntype =~ s/\(\)//g;
1897 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1898 $expr = $output_expr{$type_kind{$type}};
1899 if ($expr =~ /DO_ARRAY_ELEM/) {
1900 blurt("Error: '$subtype' not in typemap"), return
1901 unless defined($type_kind{$subtype});
1902 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1903 unless defined $output_expr{$type_kind{$subtype}};
1904 $subexpr = $output_expr{$type_kind{$subtype}};
1905 $subexpr =~ s/ntype/subtype/g;
1906 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1907 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1908 $subexpr =~ s/\n\t/\n\t\t/g;
1909 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1910 eval "print qq\a$expr\a";
1912 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1914 elsif ($var eq 'RETVAL') {
1915 if ($expr =~ /^\t\$arg = new/) {
1916 # We expect that $arg has refcnt 1, so we need to
1918 eval "print qq\a$expr\a";
1920 print "\tsv_2mortal(ST($num));\n";
1921 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1923 elsif ($expr =~ /^\s*\$arg\s*=/) {
1924 # We expect that $arg has refcnt >=1, so we need
1926 eval "print qq\a$expr\a";
1928 print "\tsv_2mortal(ST(0));\n";
1929 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1932 # Just hope that the entry would safely write it
1933 # over an already mortalized value. By
1934 # coincidence, something like $arg = &sv_undef
1936 print "\tST(0) = sv_newmortal();\n";
1937 eval "print qq\a$expr\a";
1939 # new mortals don't have set magic
1943 print "\tPUSHs(sv_newmortal());\n";
1945 eval "print qq\a$expr\a";
1947 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1949 elsif ($arg =~ /^ST\(\d+\)$/) {
1950 eval "print qq\a$expr\a";
1952 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1958 my($type, $varname) = @_;
1960 # C++ has :: in types too so skip this
1961 $type =~ tr/:/_/ unless $hiertype;
1962 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1964 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1965 (substr $type, pos $type, 0) = " $varname ";
1968 $type .= "\t$varname";
1975 #########################################################
1977 ExtUtils::ParseXS::CountLines;
1979 our $SECTION_END_MARKER;
1982 my ($class, $cfile, $fh) = @_;
1983 $cfile =~ s/\\/\\\\/g;
1984 $SECTION_END_MARKER = qq{#line --- "$cfile"};
1996 $self->{buffer} .= $_;
1997 while ($self->{buffer} =~ s/^([^\n]*\n)//) {
1999 ++ $self->{line_no};
2000 $line =~ s|^\#line\s+---(?=\s)|#line $self->{line_no}|;
2001 print {$self->{fh}} $line;
2009 $self->PRINT(sprintf($fmt, @_));
2013 # Not necessary if we're careful to end with a "\n"
2015 print {$self->{fh}} $self->{buffer};
2019 # This sub does nothing, but is neccessary for references to be released.
2023 return $SECTION_END_MARKER;