1 package ExtUtils::ParseXS;
5 use 5.006; # We use /??{}/ in regexes
12 use ExtUtils::ParseXS::Utilities qw(
13 standard_typemap_locations
18 our (@ISA, @EXPORT_OK, $VERSION);
20 @EXPORT_OK = qw(process_file);
22 $VERSION = eval $VERSION if $VERSION =~ /_/;
24 # use strict; # One of these days ...
26 my(@XSStack); # Stack of conditionals and INCLUDEs
27 my($XSS_work_idx, $cpp_next_tmp);
30 $ProtoUsed, @InitFileCode, $FH, $proto_re, $Overload, $errors, $Fallback,
31 $hiertype, $WantPrototypes, $WantVersionChk, $WantLineNumbers, $filepathname,
32 $dir, $filename, %IncludedFiles, %input_expr, %output_expr,
33 %type_kind, %proto_letter, $BLOCK_re, $lastline, $lastline_no, $Package,
34 $Prefix, @line, %args_match, %defaults, %var_types, %arg_list, @proto_arg,
35 $processing_arg_with_types, %argtype_seen, %in_out, %lengthof,
36 $proto_in_this_xsub, $scope_in_this_xsub, $interface,
37 $interface_macro, $interface_macro_set, $ProtoThisXSUB, $ScopeThisXSUB,
38 @line_no, $ret_type, $func_name, $Full_func_name, $Packprefix, $Packid,
39 %XsubAliases, %XsubAliasValues, %Interfaces, @Attributes, %outargs, $pname,
45 # Allow for $package->process_file(%hash) in the future
46 my ($pkg, %args) = @_ % 2 ? @_ : (__PACKAGE__, @_);
48 $ProtoUsed = exists $args{prototypes};
68 my ($Is_VMS, $SymSet);
71 # Establish set of global symbols with max length 28, since xsubpp
72 # will later add the 'XS_' prefix.
73 require ExtUtils::XSSymSet;
74 $SymSet = new ExtUtils::XSSymSet 28;
76 @XSStack = ({type => 'none'});
77 ($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
79 $FH = Symbol::gensym();
80 $proto_re = "[" . quotemeta('\$%&*@;[]_') . "]";
83 $Fallback = '&PL_sv_undef';
85 # Most of the 1500 lines below uses these globals. We'll have to
86 # clean this up sometime, probably. For now, we just pull them out
89 $hiertype = $args{hiertype};
90 $WantPrototypes = $args{prototypes};
91 $WantVersionChk = $args{versioncheck};
92 my $except = $args{except} ? ' TRY' : '';
93 $WantLineNumbers = $args{linenumbers};
94 my $WantOptimize = $args{optimize};
95 my $process_inout = $args{inout};
96 my $process_argtypes = $args{argtypes};
97 my @tm = ref $args{typemap} ? @{$args{typemap}} : ($args{typemap});
99 for ($args{filename}) {
100 die "Missing required parameter 'filename'" unless $_;
102 ($dir, $filename) = (dirname($_), basename($_));
103 $filepathname =~ s/\\/\\\\/g;
104 $IncludedFiles{$_}++;
107 # Open the input file
108 open($FH, $args{filename}) or die "cannot open $args{filename}: $!\n";
110 # Open the output file if given as a string. If they provide some
111 # other kind of reference, trust them that we can print to it.
112 if (not ref $args{output}) {
113 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
114 $args{outfile} = $args{output};
118 # Really, we shouldn't have to chdir() or select() in the first
119 # place. For now, just save & restore.
120 my $orig_cwd = cwd();
121 my $orig_fh = select();
125 my $csuffix = $args{csuffix};
127 if ($WantLineNumbers) {
129 if ( $args{outfile} ) {
130 $cfile = $args{outfile};
133 $cfile = $args{filename};
134 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
136 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
137 select PSEUDO_STDOUT;
140 select $args{output};
143 foreach my $typemap (@tm) {
144 die "Can't find $typemap in $pwd\n" unless -r $typemap;
147 push @tm, standard_typemap_locations( \@INC );
149 foreach my $typemap (@tm) {
150 next unless -f $typemap;
151 # skip directories, binary files etc.
152 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
154 open my $TYPEMAP, '<', $typemap
155 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
156 my $mode = 'Typemap';
158 my $current = \$junk;
161 # my $line_no = $. + 1;
163 $mode = 'Input'; $current = \$junk; next;
166 $mode = 'Output'; $current = \$junk; next;
168 if (/^TYPEMAP\s*$/) {
169 $mode = 'Typemap'; $current = \$junk; next;
171 if ($mode eq 'Typemap') {
175 # skip blank lines and comment lines
176 next if /^$/ or /^#/;
177 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
178 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
179 $type = tidy_type($type);
180 $type_kind{$type} = $kind;
181 # prototype defaults to '$'
182 $proto = "\$" unless $proto;
183 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
184 unless ValidProtoString($proto);
185 $proto_letter{$type} = C_string($proto);
190 elsif ($mode eq 'Input') {
192 $input_expr{$_} = '';
193 $current = \$input_expr{$_};
197 $output_expr{$_} = '';
198 $current = \$output_expr{$_};
204 foreach my $value (values %input_expr) {
205 $value =~ s/;*\s+\z//;
206 # Move C pre-processor instructions to column 1 to be strictly ANSI
207 # conformant. Some pre-processors are fussy about this.
208 $value =~ s/^\s+#/#/mg;
210 foreach my $value (values %output_expr) {
212 $value =~ s/^\s+#/#/mg;
217 $bal = qr[(?:(?>[^()]+)|\((??{ $bal })\))*]; # ()-balanced
218 $cast = qr[(?:\(\s*SV\s*\*\s*\)\s*)?]; # Optional (SV*) cast
219 $size = qr[,\s* (??{ $bal }) ]x; # Third arg (to setpvn)
222 foreach my $key (keys %output_expr) {
223 # We can still bootstrap compile 're', because in code re.pm is
224 # available to miniperl, and does not attempt to load the XS code.
227 my ($t, $with_size, $arg, $sarg) =
228 ($output_expr{$key} =~
229 m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
230 \s* \( \s* $cast \$arg \s* ,
231 \s* ( (??{ $bal }) ) # Set from
232 ( (??{ $size }) )? # Possible sizeof set-from
236 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
239 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
241 # Match an XS keyword
242 $BLOCK_re = '\s*(' . join('|', qw(
243 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE
244 OUTPUT CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE
245 VERSIONCHECK INCLUDE INCLUDE_COMMAND SCOPE INTERFACE
246 INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
249 our ($C_group_rex, $C_arg);
250 # Group in C (no support for comments or literals)
251 $C_group_rex = qr/ [({\[]
252 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
254 # Chunk in C without comma at toplevel (no comments):
255 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
256 | (??{ $C_group_rex })
257 | " (?: (?> [^\\"]+ )
259 )* " # String literal
260 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
263 # Identify the version of xsubpp used
266 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
267 * contents of $filename. Do not edit this file, edit $filename instead.
269 * ANY CHANGES MADE HERE WILL BE LOST!
276 print("#line 1 \"$filepathname\"\n")
282 my $podstartline = $.;
285 # We can't just write out a /* */ comment, as our embedded
286 # POD might itself be in a comment. We can't put a /**/
287 # comment inside #if 0, as the C standard says that the source
288 # file is decomposed into preprocessing characters in the stage
289 # before preprocessing commands are executed.
290 # I don't want to leave the text as barewords, because the spec
291 # isn't clear whether macros are expanded before or after
292 # preprocessing commands are executed, and someone pathological
293 # may just have defined one of the 3 words as a macro that does
294 # something strange. Multiline strings are illegal in C, so
295 # the "" we write must be a string literal. And they aren't
296 # concatenated until 2 steps later, so we are safe.
298 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
299 printf("#line %d \"$filepathname\"\n", $. + 1)
305 # At this point $. is at end of file so die won't state the start
306 # of the problem, and as we haven't yet read any lines &death won't
307 # show the correct line in the message either.
308 die ("Error: Unterminated pod in $filename, line $podstartline\n")
311 last if ($Package, $Prefix) =
312 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
316 unless (defined $_) {
317 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
318 exit 0; # Not a fatal error for the caller process
321 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
324 #ifndef PERL_UNUSED_VAR
325 # define PERL_UNUSED_VAR(var) if (0) var = var
331 #ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
332 #define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)
334 /* prototype to pass -Wmissing-prototypes */
336 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params);
339 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params)
341 const GV *const gv = CvGV(cv);
343 PERL_ARGS_ASSERT_CROAK_XS_USAGE;
346 const char *const gvname = GvNAME(gv);
347 const HV *const stash = GvSTASH(gv);
348 const char *const hvname = stash ? HvNAME(stash) : NULL;
351 Perl_croak(aTHX_ "Usage: %s::%s(%s)", hvname, gvname, params);
353 Perl_croak(aTHX_ "Usage: %s(%s)", gvname, params);
355 /* Pants. I don't think that it should be possible to get here. */
356 Perl_croak(aTHX_ "Usage: CODE(0x%"UVxf")(%s)", PTR2UV(cv), params);
359 #undef PERL_ARGS_ASSERT_CROAK_XS_USAGE
361 #ifdef PERL_IMPLICIT_CONTEXT
362 #define croak_xs_usage(a,b) S_croak_xs_usage(aTHX_ a,b)
364 #define croak_xs_usage S_croak_xs_usage
369 /* NOTE: the prototype of newXSproto() is different in versions of perls,
370 * so we define a portable version of newXSproto()
373 #define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
375 #define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
376 #endif /* !defined(newXS_flags) */
380 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
385 my (@BootCode, @outlist, $prepush_done, $xsreturn, $func_header, $orig_args, );
387 while (fetch_para()) {
388 # Print initial preprocessor statements and blank lines
389 while (@line && $line[0] !~ /^[^\#]/) {
390 my $line = shift(@line);
392 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
394 if ($statement eq 'if') {
395 $XSS_work_idx = @XSStack;
396 push(@XSStack, {type => 'if'});
399 death ("Error: `$statement' with no matching `if'")
400 if $XSStack[-1]{type} ne 'if';
401 if ($XSStack[-1]{varname}) {
402 push(@InitFileCode, "#endif\n");
403 push(@BootCode, "#endif");
406 my(@fns) = keys %{$XSStack[-1]{functions}};
407 if ($statement ne 'endif') {
408 # Hide the functions defined in other #if branches, and reset.
409 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
410 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
413 my($tmp) = pop(@XSStack);
414 0 while (--$XSS_work_idx
415 && $XSStack[$XSS_work_idx]{type} ne 'if');
416 # Keep all new defined functions
417 push(@fns, keys %{$tmp->{other_functions}});
418 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
423 next PARAGRAPH unless @line;
425 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
426 # We are inside an #if, but have not yet #defined its xsubpp variable.
427 print "#define $cpp_next_tmp 1\n\n";
428 push(@InitFileCode, "#if $cpp_next_tmp\n");
429 push(@BootCode, "#if $cpp_next_tmp");
430 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
433 death ("Code is not inside a function"
434 ." (maybe last function was ended by a blank line "
435 ." followed by a statement on column one?)")
436 if $line[0] =~ /^\s/;
438 my ($class, $externC, $static, $ellipsis, $wantRETVAL, $RETVAL_no_return);
439 my (@fake_INPUT_pre); # For length(s) generated variables
442 # initialize info arrays
448 undef($processing_arg_with_types);
449 undef(%argtype_seen);
453 undef($proto_in_this_xsub);
454 undef($scope_in_this_xsub);
456 undef($prepush_done);
457 $interface_macro = 'XSINTERFACE_FUNC';
458 $interface_macro_set = 'XSINTERFACE_FUNC_SET';
459 $ProtoThisXSUB = $WantPrototypes;
464 while (my $kwd = check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
466 &{"${kwd}_handler"}();
468 next PARAGRAPH unless @line;
472 if (check_keyword("BOOT")) {
474 push (@BootCode, "#line $line_no[@line_no - @line] \"$filepathname\"")
475 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
476 push (@BootCode, @line, "");
480 # extract return type, function name and arguments
481 ($ret_type) = tidy_type($_);
482 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
484 # Allow one-line ANSI-like declaration
487 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
489 # a function definition needs at least 2 lines
490 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
493 $externC = 1 if $ret_type =~ s/^extern "C"\s+//;
494 $static = 1 if $ret_type =~ s/^static\s+//;
496 $func_header = shift(@line);
497 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
498 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
500 ($class, $func_name, $orig_args) = ($1, $2, $3);
501 $class = "$4 $class" if $4;
502 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
504 ($clean_func_name = $func_name) =~ s/^$Prefix//;
505 $Full_func_name = "${Packid}_$clean_func_name";
507 $Full_func_name = $SymSet->addsym($Full_func_name);
510 # Check for duplicate function definition
511 for my $tmp (@XSStack) {
512 next unless defined $tmp->{functions}{$Full_func_name};
513 Warn("Warning: duplicate function definition '$clean_func_name' detected");
516 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++;
517 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
520 $orig_args =~ s/\\\s*/ /g; # process line continuations
523 my %only_C_inlist; # Not in the signature of Perl function
524 if ($process_argtypes and $orig_args =~ /\S/) {
525 my $args = "$orig_args ,";
526 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
527 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
531 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
532 my ($pre, $name) = ($arg =~ /(.*?) \s*
533 \b ( \w+ | length\( \s*\w+\s* \) )
535 next unless defined($pre) && length($pre);
538 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
540 $out_type = $type if $type ne 'IN';
541 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
542 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
545 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
546 $name = "XSauto_length_of_$1";
548 die "Default value on length() argument: `$_'"
551 if (length $pre or $islength) { # Has a type
553 push @fake_INPUT_pre, $arg;
556 push @fake_INPUT, $arg;
558 # warn "pushing '$arg'\n";
559 $argtype_seen{$name}++;
560 $_ = "$name$default"; # Assigns to @args
562 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
563 push @outlist, $name if $out_type =~ /OUTLIST$/;
564 $in_out{$name} = $out_type if $out_type;
568 @args = split(/\s*,\s*/, $orig_args);
569 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
573 @args = split(/\s*,\s*/, $orig_args);
575 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
577 next if $out_type eq 'IN';
578 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
579 push @outlist, $name if $out_type =~ /OUTLIST$/;
580 $in_out{$_} = $out_type;
584 if (defined($class)) {
585 my $arg0 = ((defined($static) or $func_name eq 'new')
587 unshift(@args, $arg0);
592 my $report_args = '';
593 foreach my $i (0 .. $#args) {
594 if ($args[$i] =~ s/\.\.\.//) {
596 if ($args[$i] eq '' && $i == $#args) {
597 $report_args .= ", ...";
602 if ($only_C_inlist{$args[$i]}) {
603 push @args_num, undef;
606 push @args_num, ++$num_args;
607 $report_args .= ", $args[$i]";
609 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
612 $defaults{$args[$i]} = $2;
613 $defaults{$args[$i]} =~ s/"/\\"/g;
615 $proto_arg[$i+1] = '$';
617 $min_args = $num_args - $extra_args;
618 $report_args =~ s/"/\\"/g;
619 $report_args =~ s/^,\s+//;
620 my @func_args = @args;
621 shift @func_args if defined($class);
624 s/^/&/ if $in_out{$_};
626 $func_args = join(", ", @func_args);
627 @args_match{@args} = @args_num;
629 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
630 $CODE = grep(/^\s*CODE\s*:/, @line);
631 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
632 # to set explicit return values.
633 $EXPLICIT_RETURN = ($CODE &&
634 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
635 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
636 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
638 $xsreturn = 1 if $EXPLICIT_RETURN;
640 $externC = $externC ? qq[extern "C"] : "";
642 # print function header
645 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
646 #XS(XS_${Full_func_name})
654 print Q(<<"EOF") if $ALIAS;
657 print Q(<<"EOF") if $INTERFACE;
658 # dXSFUNCTION($ret_type);
661 $cond = ($min_args ? qq(items < $min_args) : 0);
663 elsif ($min_args == $num_args) {
664 $cond = qq(items != $min_args);
667 $cond = qq(items < $min_args || items > $num_args);
670 print Q(<<"EOF") if $except;
678 # croak_xs_usage(cv, "$report_args");
682 # cv likely to be unused
684 # PERL_UNUSED_VAR(cv); /* -W */
688 #gcc -Wall: if an xsub has PPCODE is used
689 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
690 #hence `ax' (setup by dXSARGS) is unused
691 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
692 #but such a move could break third-party extensions
693 print Q(<<"EOF") if $PPCODE;
694 # PERL_UNUSED_VAR(ax); /* -Wall */
697 print Q(<<"EOF") if $PPCODE;
701 # Now do a block of some sort.
704 $cond = ''; # last CASE: condidional
705 push(@line, "$END:");
706 push(@line_no, $line_no[-1]);
710 &CASE_handler if check_keyword("CASE");
715 # do initialization of input variables
723 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
725 print Q(<<"EOF") if $ScopeThisXSUB;
730 if (!$thisdone && defined($class)) {
731 if (defined($static) or $func_name eq 'new') {
733 $var_types{"CLASS"} = "char *";
734 &generate_init("char *", 1, "CLASS");
738 $var_types{"THIS"} = "$class *";
739 &generate_init("$class *", 1, "THIS");
744 if (/^\s*NOT_IMPLEMENTED_YET/) {
745 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
749 if ($ret_type ne "void") {
750 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
752 $args_match{"RETVAL"} = 0;
753 $var_types{"RETVAL"} = $ret_type;
755 if $WantOptimize and $targetable{$type_kind{$ret_type}};
758 if (@fake_INPUT or @fake_INPUT_pre) {
759 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
761 $processing_arg_with_types = 1;
766 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
768 if (check_keyword("PPCODE")) {
770 death ("PPCODE must be last thing") if @line;
771 print "\tLEAVE;\n" if $ScopeThisXSUB;
772 print "\tPUTBACK;\n\treturn;\n";
774 elsif (check_keyword("CODE")) {
777 elsif (defined($class) and $func_name eq "DESTROY") {
779 print "delete THIS;\n";
783 if ($ret_type ne "void") {
787 if (defined($static)) {
788 if ($func_name eq 'new') {
789 $func_name = "$class";
795 elsif (defined($class)) {
796 if ($func_name eq 'new') {
797 $func_name .= " $class";
803 $func_name =~ s/^\Q$args{'s'}//
804 if exists $args{'s'};
805 $func_name = 'XSFUNCTION' if $interface;
806 print "$func_name($func_args);\n";
810 # do output variables
811 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
812 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
813 # $wantRETVAL set if 'RETVAL =' autogenerated
814 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
816 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
818 &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
819 for grep $in_out{$_} =~ /OUT$/, keys %in_out;
821 # all OUTPUT done, so now push the return value on the stack
822 if ($gotRETVAL && $RETVAL_code) {
823 print "\t$RETVAL_code\n";
825 elsif ($gotRETVAL || $wantRETVAL) {
826 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
828 my $type = $ret_type;
830 # 0: type, 1: with_size, 2: how, 3: how_size
831 if ($t and not $t->[1] and $t->[0] eq 'p') {
832 # PUSHp corresponds to setpvn. Treate setpv directly
833 my $what = eval qq("$t->[2]");
836 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
840 my $what = eval qq("$t->[2]");
844 $size = '' unless defined $size;
845 $size = eval qq("$size");
847 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
851 # RETVAL almost never needs SvSETMAGIC()
852 &generate_output($ret_type, 0, 'RETVAL', 0);
856 $xsreturn = 1 if $ret_type ne "void";
859 print "\tXSprePUSH;" if $c and not $prepush_done;
860 print "\tEXTEND(SP,$c);\n" if $c;
862 generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
865 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
867 print Q(<<"EOF") if $ScopeThisXSUB;
870 print Q(<<"EOF") if $ScopeThisXSUB and not $PPCODE;
874 # print function trailer
878 print Q(<<"EOF") if $except;
881 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
884 if (check_keyword("CASE")) {
885 blurt ("Error: No `CASE:' at top of function")
887 $_ = "CASE: $_"; # Restore CASE: label
890 last if $_ eq "$END:";
891 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
894 print Q(<<"EOF") if $except;
896 # Perl_croak(aTHX_ errbuf);
900 print Q(<<"EOF") unless $PPCODE;
901 # XSRETURN($xsreturn);
905 print Q(<<"EOF") unless $PPCODE;
915 our $newXS = "newXS";
918 # Build the prototype string for the xsub
919 if ($ProtoThisXSUB) {
920 $newXS = "newXSproto_portable";
922 if ($ProtoThisXSUB eq 2) {
923 # User has specified empty prototype
925 elsif ($ProtoThisXSUB eq 1) {
927 if ($min_args < $num_args) {
929 $proto_arg[$min_args] .= ";";
931 push @proto_arg, "$s\@"
934 $proto = join ("", grep defined, @proto_arg);
937 # User has specified a prototype
938 $proto = $ProtoThisXSUB;
940 $proto = qq{, "$proto"};
944 $XsubAliases{$pname} = 0
945 unless defined $XsubAliases{$pname};
946 while ( ($name, $value) = each %XsubAliases) {
947 push(@InitFileCode, Q(<<"EOF"));
948 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
949 # XSANY.any_i32 = $value;
953 elsif (@Attributes) {
954 push(@InitFileCode, Q(<<"EOF"));
955 # cv = ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);
956 # apply_attrs_string("$Package", cv, "@Attributes", 0);
960 while ( ($name, $value) = each %Interfaces) {
961 $name = "$Package\::$name" unless $name =~ /::/;
962 push(@InitFileCode, Q(<<"EOF"));
963 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
964 # $interface_macro_set(cv,$value);
968 elsif($newXS eq 'newXS'){ # work around P5NCI's empty newXS macro
970 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
974 " (void)${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
978 if ($Overload) { # make it findable with fetchmethod
980 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
981 #XS(XS_${Packid}_nil)
988 unshift(@InitFileCode, <<"MAKE_FETCHMETHOD_WORK");
989 /* Making a sub named "${Package}::()" allows the package */
990 /* to be findable via fetchmethod(), and causes */
991 /* overload::Overloaded("${Package}") to return true. */
992 (void)${newXS}("${Package}::()", XS_${Packid}_nil, file$proto);
993 MAKE_FETCHMETHOD_WORK
996 # print initialization routine
1005 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1006 #XS(boot_$Module_cname)
1018 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
1019 #file name argument. If the wrong qualifier is used, it causes breakage with
1020 #C++ compilers and warnings with recent gcc.
1021 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1022 #so `file' is unused
1023 print Q(<<"EOF") if $Full_func_name;
1024 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
1025 # char* file = __FILE__;
1027 # const char* file = __FILE__;
1034 # PERL_UNUSED_VAR(cv); /* -W */
1035 # PERL_UNUSED_VAR(items); /* -W */
1038 print Q(<<"EOF") if $WantVersionChk;
1039 # XS_VERSION_BOOTCHECK;
1043 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1049 print Q(<<"EOF") if ($Overload);
1050 # /* register the overloading (type 'A') magic */
1051 # PL_amagic_generation++;
1052 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1053 # /* mentioned above, and looks in the SV* slot of it for */
1054 # /* the "fallback" status. */
1056 # get_sv( "${Package}::()", TRUE ),
1061 print @InitFileCode;
1063 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1068 print "\n /* Initialisation Section */\n\n";
1071 print "\n /* End of Initialisation Section */\n\n";
1075 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
1076 # if (PL_unitcheckav)
1077 # call_list(PL_scopestack_ix, PL_unitcheckav);
1087 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1092 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
1098 sub errors { $errors }
1100 # Input: ($_, @line) == unparsed input.
1101 # Output: ($_, @line) == (rest of line, following lines).
1102 # Return: the matched keyword if found, otherwise 0
1104 $_ = shift(@line) while !/\S/ && @line;
1105 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1109 # the "do" is required for right semantics
1110 do { $_ = shift(@line) } while !/\S/ && @line;
1112 print("#line ", $line_no[@line_no - @line -1], " \"$filepathname\"\n")
1113 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1114 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1117 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
1123 while (!/\S/ && @line) {
1127 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1134 sub process_keyword($) {
1139 &{"${kwd}_handler"}()
1140 while $kwd = check_keyword($pattern);
1145 blurt ("Error: `CASE:' after unconditional `CASE:'")
1146 if $condnum && $cond eq '';
1148 trim_whitespace($cond);
1149 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
1154 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1155 last if /^\s*NOT_IMPLEMENTED_YET/;
1156 next unless /\S/; # skip blank lines
1158 trim_whitespace($_);
1161 # remove trailing semicolon if no initialisation
1162 s/\s*;$//g unless /[=;+].*\S/;
1164 # Process the length(foo) declarations
1165 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1166 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1167 $lengthof{$2} = $name;
1168 # $islengthof{$name} = $1;
1169 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1172 # check for optional initialisation code
1174 $var_init = $1 if s/\s*([=;+].*)$//s;
1175 $var_init =~ s/"/\\"/g;
1178 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1179 or blurt("Error: invalid argument declaration '$line'"), next;
1181 # Check for duplicate definitions
1182 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
1183 if $arg_list{$var_name}++
1184 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
1186 $thisdone |= $var_name eq "THIS";
1187 $retvaldone |= $var_name eq "RETVAL";
1188 $var_types{$var_name} = $var_type;
1189 # XXXX This check is a safeguard against the unfinished conversion of
1190 # generate_init(). When generate_init() is fixed,
1191 # one can use 2-args map_type() unconditionally.
1192 if ($var_type =~ / \( \s* \* \s* \) /x) {
1193 # Function pointers are not yet supported with &output_init!
1194 print "\t" . &map_type($var_type, $var_name);
1198 print "\t" . &map_type($var_type);
1201 $var_num = $args_match{$var_name};
1203 $proto_arg[$var_num] = ProtoString($var_type)
1205 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
1206 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1207 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
1208 and $var_init !~ /\S/) {
1209 if ($name_printed) {
1213 print "\t$var_name;\n";
1216 elsif ($var_init =~ /\S/) {
1217 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
1220 # generate initialization code
1221 &generate_init($var_type, $var_num, $var_name, $name_printed);
1229 sub OUTPUT_handler {
1230 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1232 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1233 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
1236 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1237 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1238 if $outargs{$outarg} ++;
1239 if (!$gotRETVAL and $outarg eq 'RETVAL') {
1240 # deal with RETVAL last
1241 $RETVAL_code = $outcode;
1245 blurt ("Error: OUTPUT $outarg not an argument"), next
1246 unless defined($args_match{$outarg});
1247 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1248 unless defined $var_types{$outarg};
1249 $var_num = $args_match{$outarg};
1251 print "\t$outcode\n";
1252 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
1255 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
1257 delete $in_out{$outarg} # No need to auto-OUTPUT
1258 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
1262 sub C_ARGS_handler() {
1263 my $in = merge_section();
1265 trim_whitespace($in);
1269 sub INTERFACE_MACRO_handler() {
1270 my $in = merge_section();
1272 trim_whitespace($in);
1273 if ($in =~ /\s/) { # two
1274 ($interface_macro, $interface_macro_set) = split ' ', $in;
1277 $interface_macro = $in;
1278 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
1280 $interface = 1; # local
1281 $Interfaces = 1; # global
1284 sub INTERFACE_handler() {
1285 my $in = merge_section();
1287 trim_whitespace($in);
1289 foreach (split /[\s,]+/, $in) {
1291 $name =~ s/^$Prefix//;
1292 $Interfaces{$name} = $_;
1295 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
1297 $interface = 1; # local
1298 $Interfaces = 1; # global
1301 sub CLEANUP_handler() { print_section() }
1302 sub PREINIT_handler() { print_section() }
1303 sub POSTCALL_handler() { print_section() }
1304 sub INIT_handler() { print_section() }
1312 # Parse alias definitions
1314 # alias = value alias = value ...
1316 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1318 $orig_alias = $alias;
1321 # check for optional package definition in the alias
1322 $alias = $Packprefix . $alias if $alias !~ /::/;
1324 # check for duplicate alias name & duplicate value
1325 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
1326 if defined $XsubAliases{$alias};
1328 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
1329 if $XsubAliasValues{$value};
1332 $XsubAliases{$alias} = $value;
1333 $XsubAliasValues{$value} = $orig_alias;
1336 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
1340 sub ATTRS_handler () {
1341 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1343 trim_whitespace($_);
1344 push @Attributes, $_;
1348 sub ALIAS_handler () {
1349 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1351 trim_whitespace($_);
1352 GetAliases($_) if $_;
1356 sub OVERLOAD_handler() {
1357 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1359 trim_whitespace($_);
1360 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1361 $Overload = 1 unless $Overload;
1362 my $overload = "$Package\::(".$1;
1364 " (void)${newXS}(\"$overload\", XS_$Full_func_name, file$proto);\n");
1369 sub FALLBACK_handler() {
1370 # the rest of the current line should contain either TRUE,
1373 trim_whitespace($_);
1375 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1376 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1377 UNDEF => "&PL_sv_undef",
1380 # check for valid FALLBACK value
1381 death ("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1383 $Fallback = $map{uc $_};
1387 sub REQUIRE_handler () {
1388 # the rest of the current line should contain a version number
1391 trim_whitespace($Ver);
1393 death ("Error: REQUIRE expects a version number")
1396 # check that the version number is of the form n.n
1397 death ("Error: REQUIRE: expected a number, got '$Ver'")
1398 unless $Ver =~ /^\d+(\.\d*)?/;
1400 death ("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1401 unless $VERSION >= $Ver;
1404 sub VERSIONCHECK_handler () {
1405 # the rest of the current line should contain either ENABLE or
1408 trim_whitespace($_);
1410 # check for ENABLE/DISABLE
1411 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
1412 unless /^(ENABLE|DISABLE)/i;
1414 $WantVersionChk = 1 if $1 eq 'ENABLE';
1415 $WantVersionChk = 0 if $1 eq 'DISABLE';
1419 sub PROTOTYPE_handler () {
1422 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1423 if $proto_in_this_xsub ++;
1425 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1428 trim_whitespace($_);
1429 if ($_ eq 'DISABLE') {
1432 elsif ($_ eq 'ENABLE') {
1436 # remove any whitespace
1438 death("Error: Invalid prototype '$_'")
1439 unless ValidProtoString($_);
1440 $ProtoThisXSUB = C_string($_);
1444 # If no prototype specified, then assume empty prototype ""
1445 $ProtoThisXSUB = 2 unless $specified;
1450 sub SCOPE_handler () {
1451 death("Error: Only 1 SCOPE declaration allowed per xsub")
1452 if $scope_in_this_xsub ++;
1454 trim_whitespace($_);
1455 death ("Error: SCOPE: ENABLE/DISABLE")
1456 unless /^(ENABLE|DISABLE)\b/i;
1457 $ScopeThisXSUB = ( uc($1) eq 'ENABLE' );
1460 sub PROTOTYPES_handler () {
1461 # the rest of the current line should contain either ENABLE or
1464 trim_whitespace($_);
1466 # check for ENABLE/DISABLE
1467 death ("Error: PROTOTYPES: ENABLE/DISABLE")
1468 unless /^(ENABLE|DISABLE)/i;
1470 $WantPrototypes = 1 if $1 eq 'ENABLE';
1471 $WantPrototypes = 0 if $1 eq 'DISABLE';
1476 # Save the current file context.
1479 LastLine => $lastline,
1480 LastLineNo => $lastline_no,
1482 LineNo => \@line_no,
1483 Filename => $filename,
1484 Filepathname => $filepathname,
1486 IsPipe => scalar($filename =~ /\|\s*$/),
1492 sub INCLUDE_handler () {
1493 # the rest of the current line should contain a valid filename
1495 trim_whitespace($_);
1497 death("INCLUDE: filename missing")
1500 death("INCLUDE: output pipe is illegal")
1503 # simple minded recursion detector
1504 death("INCLUDE loop detected")
1505 if $IncludedFiles{$_};
1507 ++ $IncludedFiles{$_} unless /\|\s*$/;
1509 if (/\|\s*$/ && /^\s*perl\s/) {
1510 Warn("The INCLUDE directive with a command is discouraged." .
1511 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1512 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1513 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1514 " the use of \$^X as the currently running perl, see" .
1515 " 'perldoc perlxs' for details.");
1520 $FH = Symbol::gensym();
1523 open ($FH, "$_") or death("Cannot open '$_': $!");
1527 #/* INCLUDE: Including '$_' from '$filename' */
1532 $filepathname = File::Spec->catfile($dir, $filename);
1534 # Prime the pump by reading the first
1537 # skip leading blank lines
1539 last unless /^\s*$/;
1548 my @args = split /\s+/, $cmd;
1551 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1553 return join (' ', ($cmd, @args));
1556 sub INCLUDE_COMMAND_handler () {
1557 # the rest of the current line should contain a valid command
1559 trim_whitespace($_);
1561 $_ = QuoteArgs($_) if $^O eq 'VMS';
1563 death("INCLUDE_COMMAND: command missing")
1566 death("INCLUDE_COMMAND: pipes are illegal")
1567 if /^\s*\|/ or /\|\s*$/;
1569 PushXSStack( IsPipe => 1 );
1571 $FH = Symbol::gensym();
1573 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1574 # the same perl interpreter as we're currently running
1578 open ($FH, "-|", "$_")
1579 or death("Cannot run command '$_' to include its output: $!");
1583 #/* INCLUDE_COMMAND: Including output of '$_' from '$filename' */
1588 $filepathname = $filename;
1589 $filepathname =~ s/\"/\\"/g;
1591 # Prime the pump by reading the first
1594 # skip leading blank lines
1596 last unless /^\s*$/;
1604 return 0 unless $XSStack[-1]{type} eq 'file';
1606 my $data = pop @XSStack;
1607 my $ThisFile = $filename;
1608 my $isPipe = $data->{IsPipe};
1610 -- $IncludedFiles{$filename}
1615 $FH = $data->{Handle};
1616 # $filename is the leafname, which for some reason isused for diagnostic
1617 # messages, whereas $filepathname is the full pathname, and is used for
1619 $filename = $data->{Filename};
1620 $filepathname = $data->{Filepathname};
1621 $lastline = $data->{LastLine};
1622 $lastline_no = $data->{LastLineNo};
1623 @line = @{ $data->{Line} };
1624 @line_no = @{ $data->{LineNo} };
1626 if ($isPipe and $? ) {
1628 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
1634 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
1641 sub ValidProtoString ($) {
1644 if ( $string =~ /^$proto_re+$/ ) {
1654 $string =~ s[\\][\\\\]g;
1658 sub ProtoString ($) {
1661 $proto_letter{$type} or "\$";
1665 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
1667 my ($cpp, $cpplevel);
1669 if ($cpp =~ /^\#\s*if/) {
1672 elsif (!$cpplevel) {
1673 Warn("Warning: #else/elif/endif without #if in this function");
1674 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
1675 if $XSStack[-1]{type} eq 'if';
1678 elsif ($cpp =~ /^\#\s*endif/) {
1682 Warn("Warning: #if without #endif in this function") if $cpplevel;
1690 $text =~ s/\[\[/{/g;
1691 $text =~ s/\]\]/}/g;
1695 # Read next xsub into @line from ($lastline, <$FH>).
1698 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
1699 if !defined $lastline && $XSStack[-1]{type} eq 'if';
1702 return PopFile() if !defined $lastline;
1705 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1707 $Package = defined($2) ? $2 : ''; # keep -w happy
1708 $Prefix = defined($3) ? $3 : ''; # keep -w happy
1709 $Prefix = quotemeta $Prefix;
1710 ($Module_cname = $Module) =~ s/\W/_/g;
1711 ($Packid = $Package) =~ tr/:/_/;
1712 $Packprefix = $Package;
1713 $Packprefix .= "::" if $Packprefix ne "";
1718 # Skip embedded PODs
1719 while ($lastline =~ /^=/) {
1720 while ($lastline = <$FH>) {
1721 last if ($lastline =~ /^=cut\s*$/);
1723 death ("Error: Unterminated pod") unless $lastline;
1726 $lastline =~ s/^\s+$//;
1728 if ($lastline !~ /^\s*#/ ||
1730 # ANSI: if ifdef ifndef elif else endif define undef
1732 # gcc: warning include_next
1734 # others: ident (gcc notes that some cpps have this one)
1735 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1736 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
1737 push(@line, $lastline);
1738 push(@line_no, $lastline_no);
1741 # Read next line and continuation lines
1742 last unless defined($lastline = <$FH>);
1745 $lastline .= $tmp_line
1746 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
1749 $lastline =~ s/^\s+$//;
1751 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
1756 local($type, $num, $var, $init, $name_printed) = @_;
1757 local($arg) = "ST(" . ($num - 1) . ")";
1759 if ( $init =~ /^=/ ) {
1760 if ($name_printed) {
1761 eval qq/print " $init\\n"/;
1764 eval qq/print "\\t$var $init\\n"/;
1769 if ( $init =~ s/^\+// && $num ) {
1770 &generate_init($type, $num, $var, $name_printed);
1772 elsif ($name_printed) {
1777 eval qq/print "\\t$var;\\n"/;
1781 $deferred .= eval qq/"\\n\\t$init\\n"/;
1787 # work out the line number
1788 my $warn_line_number = $line_no[@line_no - @line -1];
1790 print STDERR "@_ in $filename, line $warn_line_number\n";
1804 local($type, $num, $var) = @_;
1805 local($arg) = "ST(" . ($num - 1) . ")";
1806 local($argoff) = $num - 1;
1810 $type = tidy_type($type);
1811 blurt("Error: '$type' not in typemap"), return
1812 unless defined($type_kind{$type});
1814 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1815 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1816 $tk = $type_kind{$type};
1817 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1818 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1819 print "\t$var" unless $name_printed;
1820 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1821 die "default value not supported with length(NAME) supplied"
1822 if defined $defaults{$var};
1825 $type =~ tr/:/_/ unless $hiertype;
1826 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1827 unless defined $input_expr{$tk};
1828 $expr = $input_expr{$tk};
1829 if ($expr =~ /DO_ARRAY_ELEM/) {
1830 blurt("Error: '$subtype' not in typemap"), return
1831 unless defined($type_kind{$subtype});
1832 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1833 unless defined $input_expr{$type_kind{$subtype}};
1834 $subexpr = $input_expr{$type_kind{$subtype}};
1835 $subexpr =~ s/\$type/\$subtype/g;
1836 $subexpr =~ s/ntype/subtype/g;
1837 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1838 $subexpr =~ s/\n\t/\n\t\t/g;
1839 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1840 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1841 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1843 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1846 if (defined($defaults{$var})) {
1847 $expr =~ s/(\t+)/$1 /g;
1849 if ($name_printed) {
1853 eval qq/print "\\t$var;\\n"/;
1856 if ($defaults{$var} eq 'NO_INIT') {
1857 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1860 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1864 elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1865 if ($name_printed) {
1869 eval qq/print "\\t$var;\\n"/;
1872 $deferred .= eval qq/"\\n$expr;\\n"/;
1876 die "panic: do not know how to handle this branch for function pointers"
1878 eval qq/print "$expr;\\n"/;
1883 sub generate_output {
1884 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1885 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1886 local($argoff) = $num - 1;
1889 $type = tidy_type($type);
1890 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1891 print "\t$arg = sv_newmortal();\n";
1892 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1893 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1896 blurt("Error: '$type' not in typemap"), return
1897 unless defined($type_kind{$type});
1898 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1899 unless defined $output_expr{$type_kind{$type}};
1900 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1901 $ntype =~ s/\(\)//g;
1902 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1903 $expr = $output_expr{$type_kind{$type}};
1904 if ($expr =~ /DO_ARRAY_ELEM/) {
1905 blurt("Error: '$subtype' not in typemap"), return
1906 unless defined($type_kind{$subtype});
1907 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1908 unless defined $output_expr{$type_kind{$subtype}};
1909 $subexpr = $output_expr{$type_kind{$subtype}};
1910 $subexpr =~ s/ntype/subtype/g;
1911 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1912 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1913 $subexpr =~ s/\n\t/\n\t\t/g;
1914 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1915 eval "print qq\a$expr\a";
1917 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1919 elsif ($var eq 'RETVAL') {
1920 if ($expr =~ /^\t\$arg = new/) {
1921 # We expect that $arg has refcnt 1, so we need to
1923 eval "print qq\a$expr\a";
1925 print "\tsv_2mortal(ST($num));\n";
1926 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1928 elsif ($expr =~ /^\s*\$arg\s*=/) {
1929 # We expect that $arg has refcnt >=1, so we need
1931 eval "print qq\a$expr\a";
1933 print "\tsv_2mortal(ST(0));\n";
1934 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1937 # Just hope that the entry would safely write it
1938 # over an already mortalized value. By
1939 # coincidence, something like $arg = &sv_undef
1941 print "\tST(0) = sv_newmortal();\n";
1942 eval "print qq\a$expr\a";
1944 # new mortals don't have set magic
1948 print "\tPUSHs(sv_newmortal());\n";
1950 eval "print qq\a$expr\a";
1952 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1954 elsif ($arg =~ /^ST\(\d+\)$/) {
1955 eval "print qq\a$expr\a";
1957 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1963 my($type, $varname) = @_;
1965 # C++ has :: in types too so skip this
1966 $type =~ tr/:/_/ unless $hiertype;
1967 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1969 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1970 (substr $type, pos $type, 0) = " $varname ";
1973 $type .= "\t$varname";
1980 #########################################################
1982 ExtUtils::ParseXS::CountLines;
1984 our $SECTION_END_MARKER;
1987 my ($class, $cfile, $fh) = @_;
1988 $cfile =~ s/\\/\\\\/g;
1989 $SECTION_END_MARKER = qq{#line --- "$cfile"};
2001 $self->{buffer} .= $_;
2002 while ($self->{buffer} =~ s/^([^\n]*\n)//) {
2004 ++ $self->{line_no};
2005 $line =~ s|^\#line\s+---(?=\s)|#line $self->{line_no}|;
2006 print {$self->{fh}} $line;
2014 $self->PRINT(sprintf($fmt, @_));
2018 # Not necessary if we're careful to end with a "\n"
2020 print {$self->{fh}} $self->{buffer};
2024 # This sub does nothing, but is neccessary for references to be released.
2028 return $SECTION_END_MARKER;