1 package ExtUtils::ParseXS;
3 use 5.006; # We use /??{}/ in regexes
10 use ExtUtils::ParseXS::Utilities qw(
11 standard_typemap_locations
15 our (@ISA, @EXPORT_OK, $VERSION);
17 @EXPORT_OK = qw(process_file);
18 $VERSION = '2.2210_01';
19 $VERSION = eval $VERSION if $VERSION =~ /_/;
21 # use strict; # One of these days...
23 my(@XSStack); # Stack of conditionals and INCLUDEs
24 my($XSS_work_idx, $cpp_next_tmp);
26 our (%input_expr, %output_expr, $ProtoUsed, @InitFileCode, $FH,
27 $proto_re, $Overload, $errors, $Fallback, $cplusplus, $hiertype,
28 $WantPrototypes, $WantVersionChk, $except, $WantLineNumbers,
29 $WantOptimize, $process_inout, $process_argtypes, @tm, $dir,
30 $filename, $filepathname, %IncludedFiles, %type_kind, %proto_letter,
31 %targetable, $BLOCK_re, $lastline, $lastline_no, $Package, $Prefix,
32 @line, @BootCode, %args_match, %defaults, %var_types, %arg_list, @proto_arg,
33 $processing_arg_with_types, %argtype_seen, @outlist, %in_out, %lengthof,
34 $proto_in_this_xsub, $scope_in_this_xsub, $interface, $prepush_done,
35 $interface_macro, $interface_macro_set, $ProtoThisXSUB, $ScopeThisXSUB,
36 $xsreturn, @line_no, $ret_type, $func_header, $orig_args,
41 # Allow for $package->process_file(%hash) in the future
42 my ($pkg, %args) = @_ % 2 ? @_ : (__PACKAGE__, @_);
44 $ProtoUsed = exists $args{prototypes};
48 # 'C++' => 0, # Doesn't seem to *do* anything...
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 $cplusplus = $args{'C++'};
88 $hiertype = $args{hiertype};
89 $WantPrototypes = $args{prototypes};
90 $WantVersionChk = $args{versioncheck};
91 $except = $args{except} ? ' TRY' : '';
92 $WantLineNumbers = $args{linenumbers};
93 $WantOptimize = $args{optimize};
94 $process_inout = $args{inout};
95 $process_argtypes = $args{argtypes};
96 @tm = ref $args{typemap} ? @{$args{typemap}} : ($args{typemap});
98 for ($args{filename}) {
99 die "Missing required parameter 'filename'" unless $_;
101 ($dir, $filename) = (dirname($_), basename($_));
102 $filepathname =~ s/\\/\\\\/g;
103 $IncludedFiles{$_}++;
106 # Open the input file
107 open($FH, $args{filename}) or die "cannot open $args{filename}: $!\n";
109 # Open the output file if given as a string. If they provide some
110 # other kind of reference, trust them that we can print to it.
111 if (not ref $args{output}) {
112 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
113 $args{outfile} = $args{output};
117 # Really, we shouldn't have to chdir() or select() in the first
118 # place. For now, just save & restore.
119 my $orig_cwd = cwd();
120 my $orig_fh = select();
124 my $csuffix = $args{csuffix};
126 if ($WantLineNumbers) {
128 if ( $args{outfile} ) {
129 $cfile = $args{outfile};
132 $cfile = $args{filename};
133 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
135 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
136 select PSEUDO_STDOUT;
139 select $args{output};
142 foreach my $typemap (@tm) {
143 die "Can't find $typemap in $pwd\n" unless -r $typemap;
146 push @tm, standard_typemap_locations( \@INC );
148 foreach my $typemap (@tm) {
149 next unless -f $typemap;
150 # skip directories, binary files etc.
151 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
153 open(TYPEMAP, $typemap)
154 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
155 my $mode = 'Typemap';
157 my $current = \$junk;
160 my $line_no = $. + 1;
162 $mode = 'Input'; $current = \$junk; next;
165 $mode = 'Output'; $current = \$junk; next;
167 if (/^TYPEMAP\s*$/) {
168 $mode = 'Typemap'; $current = \$junk; next;
170 if ($mode eq 'Typemap') {
174 # skip blank lines and comment lines
175 next if /^$/ or /^#/;
176 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
177 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
178 $type = TidyType($type);
179 $type_kind{$type} = $kind;
180 # prototype defaults to '$'
181 $proto = "\$" unless $proto;
182 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
183 unless ValidProtoString($proto);
184 $proto_letter{$type} = C_string($proto);
189 elsif ($mode eq 'Input') {
191 $input_expr{$_} = '';
192 $current = \$input_expr{$_};
196 $output_expr{$_} = '';
197 $current = \$output_expr{$_};
203 foreach my $value (values %input_expr) {
204 $value =~ s/;*\s+\z//;
205 # Move C pre-processor instructions to column 1 to be strictly ANSI
206 # conformant. Some pre-processors are fussy about this.
207 $value =~ s/^\s+#/#/mg;
209 foreach my $value (values %output_expr) {
211 $value =~ s/^\s+#/#/mg;
215 our $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)
219 foreach my $key (keys %output_expr) {
220 # We can still bootstrap compile 're', because in code re.pm is
221 # available to miniperl, and does not attempt to load the XS code.
224 my ($t, $with_size, $arg, $sarg) =
225 ($output_expr{$key} =~
226 m[^ \s+ sv_set ( [iunp] ) v (n)? # Type, is_setpvn
227 \s* \( \s* $cast \$arg \s* ,
228 \s* ( (??{ $bal }) ) # Set from
229 ( (??{ $size }) )? # Possible sizeof set-from
233 $targetable{$key} = [$t, $with_size, $arg, $sarg] if $t;
236 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
238 # Match an XS keyword
239 $BLOCK_re = '\s*(' . join('|', qw(
240 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE
241 OUTPUT CLEANUP ALIAS ATTRS PROTOTYPES PROTOTYPE
242 VERSIONCHECK INCLUDE INCLUDE_COMMAND SCOPE INTERFACE
243 INTERFACE_MACRO C_ARGS POSTCALL OVERLOAD FALLBACK
246 our ($C_group_rex, $C_arg);
247 # Group in C (no support for comments or literals)
248 $C_group_rex = qr/ [({\[]
249 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
251 # Chunk in C without comma at toplevel (no comments):
252 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
253 | (??{ $C_group_rex })
254 | " (?: (?> [^\\"]+ )
256 )* " # String literal
257 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
260 # Identify the version of xsubpp used
263 * This file was venerated automatically by ExtUtils::ParseXS version $VERSION from the
264 * contents of $filename. Do not edit this file, edit $filename instead.
266 * ANY CHANGES MADE HERE WILL BE LOST!
273 print("#line 1 \"$filepathname\"\n")
279 my $podstartline = $.;
282 # We can't just write out a /* */ comment, as our embedded
283 # POD might itself be in a comment. We can't put a /**/
284 # comment inside #if 0, as the C standard says that the source
285 # file is decomposed into preprocessing characters in the stage
286 # before preprocessing commands are executed.
287 # I don't want to leave the text as barewords, because the spec
288 # isn't clear whether macros are expanded before or after
289 # preprocessing commands are executed, and someone pathological
290 # may just have defined one of the 3 words as a macro that does
291 # something strange. Multiline strings are illegal in C, so
292 # the "" we write must be a string literal. And they aren't
293 # concatenated until 2 steps later, so we are safe.
295 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
296 printf("#line %d \"$filepathname\"\n", $. + 1)
302 # At this point $. is at end of file so die won't state the start
303 # of the problem, and as we haven't yet read any lines &death won't
304 # show the correct line in the message either.
305 die ("Error: Unterminated pod in $filename, line $podstartline\n")
308 last if ($Package, $Prefix) =
309 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
313 unless (defined $_) {
314 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
315 exit 0; # Not a fatal error for the caller process
318 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
321 #ifndef PERL_UNUSED_VAR
322 # define PERL_UNUSED_VAR(var) if (0) var = var
328 #ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
329 #define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)
331 /* prototype to pass -Wmissing-prototypes */
333 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params);
336 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params)
338 const GV *const gv = CvGV(cv);
340 PERL_ARGS_ASSERT_CROAK_XS_USAGE;
343 const char *const gvname = GvNAME(gv);
344 const HV *const stash = GvSTASH(gv);
345 const char *const hvname = stash ? HvNAME(stash) : NULL;
348 Perl_croak(aTHX_ "Usage: %s::%s(%s)", hvname, gvname, params);
350 Perl_croak(aTHX_ "Usage: %s(%s)", gvname, params);
352 /* Pants. I don't think that it should be possible to get here. */
353 Perl_croak(aTHX_ "Usage: CODE(0x%"UVxf")(%s)", PTR2UV(cv), params);
356 #undef PERL_ARGS_ASSERT_CROAK_XS_USAGE
358 #ifdef PERL_IMPLICIT_CONTEXT
359 #define croak_xs_usage(a,b) S_croak_xs_usage(aTHX_ a,b)
361 #define croak_xs_usage S_croak_xs_usage
366 /* NOTE: the prototype of newXSproto() is different in versions of perls,
367 * so we define a portable version of newXSproto()
370 #define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
372 #define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
373 #endif /* !defined(newXS_flags) */
377 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
383 while (fetch_para()) {
384 # Print initial preprocessor statements and blank lines
385 while (@line && $line[0] !~ /^[^\#]/) {
386 my $line = shift(@line);
388 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
390 if ($statement eq 'if') {
391 $XSS_work_idx = @XSStack;
392 push(@XSStack, {type => 'if'});
395 death ("Error: `$statement' with no matching `if'")
396 if $XSStack[-1]{type} ne 'if';
397 if ($XSStack[-1]{varname}) {
398 push(@InitFileCode, "#endif\n");
399 push(@BootCode, "#endif");
402 my(@fns) = keys %{$XSStack[-1]{functions}};
403 if ($statement ne 'endif') {
404 # Hide the functions defined in other #if branches, and reset.
405 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
406 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
409 my($tmp) = pop(@XSStack);
410 0 while (--$XSS_work_idx
411 && $XSStack[$XSS_work_idx]{type} ne 'if');
412 # Keep all new defined functions
413 push(@fns, keys %{$tmp->{other_functions}});
414 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
419 next PARAGRAPH unless @line;
421 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
422 # We are inside an #if, but have not yet #defined its xsubpp variable.
423 print "#define $cpp_next_tmp 1\n\n";
424 push(@InitFileCode, "#if $cpp_next_tmp\n");
425 push(@BootCode, "#if $cpp_next_tmp");
426 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
429 death ("Code is not inside a function"
430 ." (maybe last function was ended by a blank line "
431 ." followed by a statement on column one?)")
432 if $line[0] =~ /^\s/;
434 my ($class, $externC, $static, $ellipsis, $wantRETVAL, $RETVAL_no_return);
435 my (@fake_INPUT_pre); # For length(s) generated variables
438 # initialize info arrays
444 undef($processing_arg_with_types);
445 undef(%argtype_seen);
449 undef($proto_in_this_xsub);
450 undef($scope_in_this_xsub);
452 undef($prepush_done);
453 $interface_macro = 'XSINTERFACE_FUNC';
454 $interface_macro_set = 'XSINTERFACE_FUNC_SET';
455 $ProtoThisXSUB = $WantPrototypes;
460 while (my $kwd = check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
461 &{"${kwd}_handler"}();
462 next PARAGRAPH unless @line;
466 if (check_keyword("BOOT")) {
468 push (@BootCode, "#line $line_no[@line_no - @line] \"$filepathname\"")
469 if $WantLineNumbers && $line[0] !~ /^\s*#\s*line\b/;
470 push (@BootCode, @line, "");
474 # extract return type, function name and arguments
475 ($ret_type) = TidyType($_);
476 $RETVAL_no_return = 1 if $ret_type =~ s/^NO_OUTPUT\s+//;
478 # Allow one-line ANSI-like declaration
481 and $ret_type =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
483 # a function definition needs at least 2 lines
484 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
487 $externC = 1 if $ret_type =~ s/^extern "C"\s+//;
488 $static = 1 if $ret_type =~ s/^static\s+//;
490 $func_header = shift(@line);
491 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
492 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
494 ($class, $func_name, $orig_args) = ($1, $2, $3);
495 $class = "$4 $class" if $4;
496 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
497 ($clean_func_name = $func_name) =~ s/^$Prefix//;
498 $Full_func_name = "${Packid}_$clean_func_name";
500 $Full_func_name = $SymSet->addsym($Full_func_name);
503 # Check for duplicate function definition
504 for my $tmp (@XSStack) {
505 next unless defined $tmp->{functions}{$Full_func_name};
506 Warn("Warning: duplicate function definition '$clean_func_name' detected");
509 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++;
510 %XsubAliases = %XsubAliasValues = %Interfaces = @Attributes = ();
513 $orig_args =~ s/\\\s*/ /g; # process line continuations
516 my %only_C_inlist; # Not in the signature of Perl function
517 if ($process_argtypes and $orig_args =~ /\S/) {
518 my $args = "$orig_args ,";
519 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
520 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
524 my ($arg, $default) = / ( [^=]* ) ( (?: = .* )? ) /x;
525 my ($pre, $name) = ($arg =~ /(.*?) \s*
526 \b ( \w+ | length\( \s*\w+\s* \) )
528 next unless defined($pre) && length($pre);
531 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
533 $out_type = $type if $type ne 'IN';
534 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
535 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
538 if ($name =~ /^length\( \s* (\w+) \s* \)\z/x) {
539 $name = "XSauto_length_of_$1";
541 die "Default value on length() argument: `$_'"
544 if (length $pre or $islength) { # Has a type
546 push @fake_INPUT_pre, $arg;
549 push @fake_INPUT, $arg;
551 # warn "pushing '$arg'\n";
552 $argtype_seen{$name}++;
553 $_ = "$name$default"; # Assigns to @args
555 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
556 push @outlist, $name if $out_type =~ /OUTLIST$/;
557 $in_out{$name} = $out_type if $out_type;
561 @args = split(/\s*,\s*/, $orig_args);
562 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
566 @args = split(/\s*,\s*/, $orig_args);
568 if ($process_inout and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
570 next if $out_type eq 'IN';
571 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
572 push @outlist, $name if $out_type =~ /OUTLIST$/;
573 $in_out{$_} = $out_type;
577 if (defined($class)) {
578 my $arg0 = ((defined($static) or $func_name eq 'new')
580 unshift(@args, $arg0);
585 my $report_args = '';
586 foreach my $i (0 .. $#args) {
587 if ($args[$i] =~ s/\.\.\.//) {
589 if ($args[$i] eq '' && $i == $#args) {
590 $report_args .= ", ...";
595 if ($only_C_inlist{$args[$i]}) {
596 push @args_num, undef;
599 push @args_num, ++$num_args;
600 $report_args .= ", $args[$i]";
602 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
605 $defaults{$args[$i]} = $2;
606 $defaults{$args[$i]} =~ s/"/\\"/g;
608 $proto_arg[$i+1] = '$';
610 $min_args = $num_args - $extra_args;
611 $report_args =~ s/"/\\"/g;
612 $report_args =~ s/^,\s+//;
613 my @func_args = @args;
614 shift @func_args if defined($class);
617 s/^/&/ if $in_out{$_};
619 $func_args = join(", ", @func_args);
620 @args_match{@args} = @args_num;
622 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
623 $CODE = grep(/^\s*CODE\s*:/, @line);
624 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
625 # to set explicit return values.
626 $EXPLICIT_RETURN = ($CODE &&
627 ("@line" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
628 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
629 $INTERFACE = grep(/^\s*INTERFACE\s*:/, @line);
631 $xsreturn = 1 if $EXPLICIT_RETURN;
633 $externC = $externC ? qq[extern "C"] : "";
635 # print function header
638 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
639 #XS(XS_${Full_func_name})
647 print Q(<<"EOF") if $ALIAS;
650 print Q(<<"EOF") if $INTERFACE;
651 # dXSFUNCTION($ret_type);
654 $cond = ($min_args ? qq(items < $min_args) : 0);
656 elsif ($min_args == $num_args) {
657 $cond = qq(items != $min_args);
660 $cond = qq(items < $min_args || items > $num_args);
663 print Q(<<"EOF") if $except;
671 # croak_xs_usage(cv, "$report_args");
675 # cv likely to be unused
677 # PERL_UNUSED_VAR(cv); /* -W */
681 #gcc -Wall: if an xsub has PPCODE is used
682 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
683 #hence `ax' (setup by dXSARGS) is unused
684 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
685 #but such a move could break third-party extensions
686 print Q(<<"EOF") if $PPCODE;
687 # PERL_UNUSED_VAR(ax); /* -Wall */
690 print Q(<<"EOF") if $PPCODE;
694 # Now do a block of some sort.
697 $cond = ''; # last CASE: condidional
698 push(@line, "$END:");
699 push(@line_no, $line_no[-1]);
703 &CASE_handler if check_keyword("CASE");
708 # do initialization of input variables
716 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
718 print Q(<<"EOF") if $ScopeThisXSUB;
723 if (!$thisdone && defined($class)) {
724 if (defined($static) or $func_name eq 'new') {
726 $var_types{"CLASS"} = "char *";
727 &generate_init("char *", 1, "CLASS");
731 $var_types{"THIS"} = "$class *";
732 &generate_init("$class *", 1, "THIS");
737 if (/^\s*NOT_IMPLEMENTED_YET/) {
738 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
742 if ($ret_type ne "void") {
743 print "\t" . &map_type($ret_type, 'RETVAL') . ";\n"
745 $args_match{"RETVAL"} = 0;
746 $var_types{"RETVAL"} = $ret_type;
748 if $WantOptimize and $targetable{$type_kind{$ret_type}};
751 if (@fake_INPUT or @fake_INPUT_pre) {
752 unshift @line, @fake_INPUT_pre, @fake_INPUT, $_;
754 $processing_arg_with_types = 1;
759 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
761 if (check_keyword("PPCODE")) {
763 death ("PPCODE must be last thing") if @line;
764 print "\tLEAVE;\n" if $ScopeThisXSUB;
765 print "\tPUTBACK;\n\treturn;\n";
767 elsif (check_keyword("CODE")) {
770 elsif (defined($class) and $func_name eq "DESTROY") {
772 print "delete THIS;\n";
776 if ($ret_type ne "void") {
780 if (defined($static)) {
781 if ($func_name eq 'new') {
782 $func_name = "$class";
788 elsif (defined($class)) {
789 if ($func_name eq 'new') {
790 $func_name .= " $class";
796 $func_name =~ s/^\Q$args{'s'}//
797 if exists $args{'s'};
798 $func_name = 'XSFUNCTION' if $interface;
799 print "$func_name($func_args);\n";
803 # do output variables
804 $gotRETVAL = 0; # 1 if RETVAL seen in OUTPUT section;
805 undef $RETVAL_code ; # code to set RETVAL (from OUTPUT section);
806 # $wantRETVAL set if 'RETVAL =' autogenerated
807 ($wantRETVAL, $ret_type) = (0, 'void') if $RETVAL_no_return;
809 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
811 &generate_output($var_types{$_}, $args_match{$_}, $_, $DoSetMagic)
812 for grep $in_out{$_} =~ /OUT$/, keys %in_out;
814 # all OUTPUT done, so now push the return value on the stack
815 if ($gotRETVAL && $RETVAL_code) {
816 print "\t$RETVAL_code\n";
818 elsif ($gotRETVAL || $wantRETVAL) {
819 my $t = $WantOptimize && $targetable{$type_kind{$ret_type}};
821 my $type = $ret_type;
823 # 0: type, 1: with_size, 2: how, 3: how_size
824 if ($t and not $t->[1] and $t->[0] eq 'p') {
825 # PUSHp corresponds to setpvn. Treate setpv directly
826 my $what = eval qq("$t->[2]");
829 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
833 my $what = eval qq("$t->[2]");
837 $size = '' unless defined $size;
838 $size = eval qq("$size");
840 print "\tXSprePUSH; PUSH$t->[0]($what$size);\n";
844 # RETVAL almost never needs SvSETMAGIC()
845 &generate_output($ret_type, 0, 'RETVAL', 0);
849 $xsreturn = 1 if $ret_type ne "void";
852 print "\tXSprePUSH;" if $c and not $prepush_done;
853 print "\tEXTEND(SP,$c);\n" if $c;
855 generate_output($var_types{$_}, $num++, $_, 0, 1) for @outlist;
858 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
860 print Q(<<"EOF") if $ScopeThisXSUB;
863 print Q(<<"EOF") if $ScopeThisXSUB and not $PPCODE;
867 # print function trailer
871 print Q(<<"EOF") if $except;
874 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
877 if (check_keyword("CASE")) {
878 blurt ("Error: No `CASE:' at top of function")
880 $_ = "CASE: $_"; # Restore CASE: label
883 last if $_ eq "$END:";
884 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
887 print Q(<<"EOF") if $except;
889 # Perl_croak(aTHX_ errbuf);
893 print Q(<<"EOF") unless $PPCODE;
894 # XSRETURN($xsreturn);
898 print Q(<<"EOF") unless $PPCODE;
908 our $newXS = "newXS";
911 # Build the prototype string for the xsub
912 if ($ProtoThisXSUB) {
913 $newXS = "newXSproto_portable";
915 if ($ProtoThisXSUB eq 2) {
916 # User has specified empty prototype
918 elsif ($ProtoThisXSUB eq 1) {
920 if ($min_args < $num_args) {
922 $proto_arg[$min_args] .= ";";
924 push @proto_arg, "$s\@"
927 $proto = join ("", grep defined, @proto_arg);
930 # User has specified a prototype
931 $proto = $ProtoThisXSUB;
933 $proto = qq{, "$proto"};
937 $XsubAliases{$pname} = 0
938 unless defined $XsubAliases{$pname};
939 while ( ($name, $value) = each %XsubAliases) {
940 push(@InitFileCode, Q(<<"EOF"));
941 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
942 # XSANY.any_i32 = $value;
946 elsif (@Attributes) {
947 push(@InitFileCode, Q(<<"EOF"));
948 # cv = ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);
949 # apply_attrs_string("$Package", cv, "@Attributes", 0);
953 while ( ($name, $value) = each %Interfaces) {
954 $name = "$Package\::$name" unless $name =~ /::/;
955 push(@InitFileCode, Q(<<"EOF"));
956 # cv = ${newXS}(\"$name\", XS_$Full_func_name, file$proto);
957 # $interface_macro_set(cv,$value);
961 elsif($newXS eq 'newXS'){ # work around P5NCI's empty newXS macro
963 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
967 " (void)${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
971 if ($Overload) # make it findable with fetchmethod
974 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
975 #XS(XS_${Packid}_nil)
982 unshift(@InitFileCode, <<"MAKE_FETCHMETHOD_WORK");
983 /* Making a sub named "${Package}::()" allows the package */
984 /* to be findable via fetchmethod(), and causes */
985 /* overload::Overloaded("${Package}") to return true. */
986 (void)${newXS}("${Package}::()", XS_${Packid}_nil, file$proto);
987 MAKE_FETCHMETHOD_WORK
990 # print initialization routine
999 #XS(boot_$Module_cname); /* prototype to pass -Wmissing-prototypes */
1000 #XS(boot_$Module_cname)
1012 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
1013 #file name argument. If the wrong qualifier is used, it causes breakage with
1014 #C++ compilers and warnings with recent gcc.
1015 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
1016 #so `file' is unused
1017 print Q(<<"EOF") if $Full_func_name;
1018 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
1019 # char* file = __FILE__;
1021 # const char* file = __FILE__;
1028 # PERL_UNUSED_VAR(cv); /* -W */
1029 # PERL_UNUSED_VAR(items); /* -W */
1032 print Q(<<"EOF") if $WantVersionChk;
1033 # XS_VERSION_BOOTCHECK;
1037 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1043 print Q(<<"EOF") if ($Overload);
1044 # /* register the overloading (type 'A') magic */
1045 # PL_amagic_generation++;
1046 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1047 # /* mentioned above, and looks in the SV* slot of it for */
1048 # /* the "fallback" status. */
1050 # get_sv( "${Package}::()", TRUE ),
1055 print @InitFileCode;
1057 print Q(<<"EOF") if defined $XsubAliases or defined $Interfaces;
1062 print "\n /* Initialisation Section */\n\n";
1065 print "\n /* End of Initialisation Section */\n\n";
1069 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
1070 # if (PL_unitcheckav)
1071 # call_list(PL_scopestack_ix, PL_unitcheckav);
1081 warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1086 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
1092 sub errors { $errors }
1097 # rationalise any '*' by joining them into bunches and removing whitespace
1101 # change multiple whitespace into a single space
1104 # trim leading & trailing whitespace
1105 trim_whitespace($_);
1110 # Input: ($_, @line) == unparsed input.
1111 # Output: ($_, @line) == (rest of line, following lines).
1112 # Return: the matched keyword if found, otherwise 0
1114 $_ = shift(@line) while !/\S/ && @line;
1115 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1119 # the "do" is required for right semantics
1120 do { $_ = shift(@line) } while !/\S/ && @line;
1122 print("#line ", $line_no[@line_no - @line -1], " \"$filepathname\"\n")
1123 if $WantLineNumbers && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1124 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1127 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $WantLineNumbers;
1133 while (!/\S/ && @line) {
1137 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
1144 sub process_keyword($) {
1148 &{"${kwd}_handler"}()
1149 while $kwd = check_keyword($pattern);
1153 blurt ("Error: `CASE:' after unconditional `CASE:'")
1154 if $condnum && $cond eq '';
1156 trim_whitespace($cond);
1157 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
1162 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1163 last if /^\s*NOT_IMPLEMENTED_YET/;
1164 next unless /\S/; # skip blank lines
1166 trim_whitespace($_);
1169 # remove trailing semicolon if no initialisation
1170 s/\s*;$//g unless /[=;+].*\S/;
1172 # Process the length(foo) declarations
1173 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1174 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1175 $lengthof{$2} = $name;
1176 # $islengthof{$name} = $1;
1177 $deferred .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1180 # check for optional initialisation code
1182 $var_init = $1 if s/\s*([=;+].*)$//s;
1183 $var_init =~ s/"/\\"/g;
1186 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1187 or blurt("Error: invalid argument declaration '$line'"), next;
1189 # Check for duplicate definitions
1190 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
1191 if $arg_list{$var_name}++
1192 or defined $argtype_seen{$var_name} and not $processing_arg_with_types;
1194 $thisdone |= $var_name eq "THIS";
1195 $retvaldone |= $var_name eq "RETVAL";
1196 $var_types{$var_name} = $var_type;
1197 # XXXX This check is a safeguard against the unfinished conversion of
1198 # generate_init(). When generate_init() is fixed,
1199 # one can use 2-args map_type() unconditionally.
1200 if ($var_type =~ / \( \s* \* \s* \) /x) {
1201 # Function pointers are not yet supported with &output_init!
1202 print "\t" . &map_type($var_type, $var_name);
1206 print "\t" . &map_type($var_type);
1209 $var_num = $args_match{$var_name};
1211 $proto_arg[$var_num] = ProtoString($var_type)
1213 $func_args =~ s/\b($var_name)\b/&$1/ if $var_addr;
1214 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1215 or $in_out{$var_name} and $in_out{$var_name} =~ /^OUT/
1216 and $var_init !~ /\S/) {
1217 if ($name_printed) {
1221 print "\t$var_name;\n";
1224 elsif ($var_init =~ /\S/) {
1225 &output_init($var_type, $var_num, $var_name, $var_init, $name_printed);
1228 # generate initialization code
1229 &generate_init($var_type, $var_num, $var_name, $name_printed);
1237 sub OUTPUT_handler {
1238 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1240 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1241 $DoSetMagic = ($1 eq "ENABLE" ? 1 : 0);
1244 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1245 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1246 if $outargs{$outarg} ++;
1247 if (!$gotRETVAL and $outarg eq 'RETVAL') {
1248 # deal with RETVAL last
1249 $RETVAL_code = $outcode;
1253 blurt ("Error: OUTPUT $outarg not an argument"), next
1254 unless defined($args_match{$outarg});
1255 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1256 unless defined $var_types{$outarg};
1257 $var_num = $args_match{$outarg};
1259 print "\t$outcode\n";
1260 print "\tSvSETMAGIC(ST(" , $var_num-1 , "));\n" if $DoSetMagic;
1263 &generate_output($var_types{$outarg}, $var_num, $outarg, $DoSetMagic);
1265 delete $in_out{$outarg} # No need to auto-OUTPUT
1266 if exists $in_out{$outarg} and $in_out{$outarg} =~ /OUT$/;
1270 sub C_ARGS_handler() {
1271 my $in = merge_section();
1273 trim_whitespace($in);
1277 sub INTERFACE_MACRO_handler() {
1278 my $in = merge_section();
1280 trim_whitespace($in);
1281 if ($in =~ /\s/) { # two
1282 ($interface_macro, $interface_macro_set) = split ' ', $in;
1285 $interface_macro = $in;
1286 $interface_macro_set = 'UNKNOWN_CVT'; # catch later
1288 $interface = 1; # local
1289 $Interfaces = 1; # global
1292 sub INTERFACE_handler() {
1293 my $in = merge_section();
1295 trim_whitespace($in);
1297 foreach (split /[\s,]+/, $in) {
1299 $name =~ s/^$Prefix//;
1300 $Interfaces{$name} = $_;
1303 # XSFUNCTION = $interface_macro($ret_type,cv,XSANY.any_dptr);
1305 $interface = 1; # local
1306 $Interfaces = 1; # global
1309 sub CLEANUP_handler() { print_section() }
1310 sub PREINIT_handler() { print_section() }
1311 sub POSTCALL_handler() { print_section() }
1312 sub INIT_handler() { print_section() }
1320 # Parse alias definitions
1322 # alias = value alias = value ...
1324 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1326 $orig_alias = $alias;
1329 # check for optional package definition in the alias
1330 $alias = $Packprefix . $alias if $alias !~ /::/;
1332 # check for duplicate alias name & duplicate value
1333 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
1334 if defined $XsubAliases{$alias};
1336 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
1337 if $XsubAliasValues{$value};
1340 $XsubAliases{$alias} = $value;
1341 $XsubAliasValues{$value} = $orig_alias;
1344 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
1348 sub ATTRS_handler () {
1349 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1351 trim_whitespace($_);
1352 push @Attributes, $_;
1356 sub ALIAS_handler () {
1357 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1359 trim_whitespace($_);
1360 GetAliases($_) if $_;
1364 sub OVERLOAD_handler() {
1365 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1367 trim_whitespace($_);
1368 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1369 $Overload = 1 unless $Overload;
1370 my $overload = "$Package\::(".$1;
1372 " (void)${newXS}(\"$overload\", XS_$Full_func_name, file$proto);\n");
1377 sub FALLBACK_handler() {
1378 # the rest of the current line should contain either TRUE,
1381 trim_whitespace($_);
1383 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1384 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1385 UNDEF => "&PL_sv_undef",
1388 # check for valid FALLBACK value
1389 death ("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1391 $Fallback = $map{uc $_};
1395 sub REQUIRE_handler () {
1396 # the rest of the current line should contain a version number
1399 trim_whitespace($Ver);
1401 death ("Error: REQUIRE expects a version number")
1404 # check that the version number is of the form n.n
1405 death ("Error: REQUIRE: expected a number, got '$Ver'")
1406 unless $Ver =~ /^\d+(\.\d*)?/;
1408 death ("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1409 unless $VERSION >= $Ver;
1412 sub VERSIONCHECK_handler () {
1413 # the rest of the current line should contain either ENABLE or
1416 trim_whitespace($_);
1418 # check for ENABLE/DISABLE
1419 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
1420 unless /^(ENABLE|DISABLE)/i;
1422 $WantVersionChk = 1 if $1 eq 'ENABLE';
1423 $WantVersionChk = 0 if $1 eq 'DISABLE';
1427 sub PROTOTYPE_handler () {
1430 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1431 if $proto_in_this_xsub ++;
1433 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
1436 trim_whitespace($_);
1437 if ($_ eq 'DISABLE') {
1440 elsif ($_ eq 'ENABLE') {
1444 # remove any whitespace
1446 death("Error: Invalid prototype '$_'")
1447 unless ValidProtoString($_);
1448 $ProtoThisXSUB = C_string($_);
1452 # If no prototype specified, then assume empty prototype ""
1453 $ProtoThisXSUB = 2 unless $specified;
1458 sub SCOPE_handler () {
1459 death("Error: Only 1 SCOPE declaration allowed per xsub")
1460 if $scope_in_this_xsub ++;
1462 trim_whitespace($_);
1463 death ("Error: SCOPE: ENABLE/DISABLE")
1464 unless /^(ENABLE|DISABLE)\b/i;
1465 $ScopeThisXSUB = ( uc($1) eq 'ENABLE' );
1468 sub PROTOTYPES_handler () {
1469 # the rest of the current line should contain either ENABLE or
1472 trim_whitespace($_);
1474 # check for ENABLE/DISABLE
1475 death ("Error: PROTOTYPES: ENABLE/DISABLE")
1476 unless /^(ENABLE|DISABLE)/i;
1478 $WantPrototypes = 1 if $1 eq 'ENABLE';
1479 $WantPrototypes = 0 if $1 eq 'DISABLE';
1484 # Save the current file context.
1487 LastLine => $lastline,
1488 LastLineNo => $lastline_no,
1490 LineNo => \@line_no,
1491 Filename => $filename,
1492 Filepathname => $filepathname,
1494 IsPipe => scalar($filename =~ /\|\s*$/),
1500 sub INCLUDE_handler () {
1501 # the rest of the current line should contain a valid filename
1503 trim_whitespace($_);
1505 death("INCLUDE: filename missing")
1508 death("INCLUDE: output pipe is illegal")
1511 # simple minded recursion detector
1512 death("INCLUDE loop detected")
1513 if $IncludedFiles{$_};
1515 ++ $IncludedFiles{$_} unless /\|\s*$/;
1517 if (/\|\s*$/ && /^\s*perl\s/) {
1518 Warn("The INCLUDE directive with a command is discouraged." .
1519 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1520 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1521 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1522 " the use of \$^X as the currently running perl, see" .
1523 " 'perldoc perlxs' for details.");
1528 $FH = Symbol::gensym();
1531 open ($FH, "$_") or death("Cannot open '$_': $!");
1535 #/* INCLUDE: Including '$_' from '$filename' */
1540 $filepathname = File::Spec->catfile($dir, $filename);
1542 # Prime the pump by reading the first
1545 # skip leading blank lines
1547 last unless /^\s*$/;
1556 my @args = split /\s+/, $cmd;
1559 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1561 return join (' ', ($cmd, @args));
1564 sub INCLUDE_COMMAND_handler () {
1565 # the rest of the current line should contain a valid command
1567 trim_whitespace($_);
1569 $_ = QuoteArgs($_) if $^O eq 'VMS';
1571 death("INCLUDE_COMMAND: command missing")
1574 death("INCLUDE_COMMAND: pipes are illegal")
1575 if /^\s*\|/ or /\|\s*$/;
1577 PushXSStack( IsPipe => 1 );
1579 $FH = Symbol::gensym();
1581 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1582 # the same perl interpreter as we're currently running
1586 open ($FH, "-|", "$_")
1587 or death("Cannot run command '$_' to include its output: $!");
1591 #/* INCLUDE_COMMAND: Including output of '$_' from '$filename' */
1596 $filepathname = $filename;
1597 $filepathname =~ s/\"/\\"/g;
1599 # Prime the pump by reading the first
1602 # skip leading blank lines
1604 last unless /^\s*$/;
1612 return 0 unless $XSStack[-1]{type} eq 'file';
1614 my $data = pop @XSStack;
1615 my $ThisFile = $filename;
1616 my $isPipe = $data->{IsPipe};
1618 -- $IncludedFiles{$filename}
1623 $FH = $data->{Handle};
1624 # $filename is the leafname, which for some reason isused for diagnostic
1625 # messages, whereas $filepathname is the full pathname, and is used for
1627 $filename = $data->{Filename};
1628 $filepathname = $data->{Filepathname};
1629 $lastline = $data->{LastLine};
1630 $lastline_no = $data->{LastLineNo};
1631 @line = @{ $data->{Line} };
1632 @line_no = @{ $data->{LineNo} };
1634 if ($isPipe and $? ) {
1636 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
1642 #/* INCLUDE: Returning to '$filename' from '$ThisFile' */
1649 sub ValidProtoString ($) {
1652 if ( $string =~ /^$proto_re+$/ ) {
1662 $string =~ s[\\][\\\\]g;
1666 sub ProtoString ($) {
1669 $proto_letter{$type} or "\$";
1673 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
1675 my ($cpp, $cpplevel);
1677 if ($cpp =~ /^\#\s*if/) {
1680 elsif (!$cpplevel) {
1681 Warn("Warning: #else/elif/endif without #if in this function");
1682 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
1683 if $XSStack[-1]{type} eq 'if';
1686 elsif ($cpp =~ /^\#\s*endif/) {
1690 Warn("Warning: #if without #endif in this function") if $cpplevel;
1698 $text =~ s/\[\[/{/g;
1699 $text =~ s/\]\]/}/g;
1703 # Read next xsub into @line from ($lastline, <$FH>).
1706 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
1707 if !defined $lastline && $XSStack[-1]{type} eq 'if';
1710 return PopFile() if !defined $lastline;
1713 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1715 $Package = defined($2) ? $2 : ''; # keep -w happy
1716 $Prefix = defined($3) ? $3 : ''; # keep -w happy
1717 $Prefix = quotemeta $Prefix;
1718 ($Module_cname = $Module) =~ s/\W/_/g;
1719 ($Packid = $Package) =~ tr/:/_/;
1720 $Packprefix = $Package;
1721 $Packprefix .= "::" if $Packprefix ne "";
1726 # Skip embedded PODs
1727 while ($lastline =~ /^=/) {
1728 while ($lastline = <$FH>) {
1729 last if ($lastline =~ /^=cut\s*$/);
1731 death ("Error: Unterminated pod") unless $lastline;
1734 $lastline =~ s/^\s+$//;
1736 if ($lastline !~ /^\s*#/ ||
1738 # ANSI: if ifdef ifndef elif else endif define undef
1740 # gcc: warning include_next
1742 # others: ident (gcc notes that some cpps have this one)
1743 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1744 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
1745 push(@line, $lastline);
1746 push(@line_no, $lastline_no);
1749 # Read next line and continuation lines
1750 last unless defined($lastline = <$FH>);
1753 $lastline .= $tmp_line
1754 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
1757 $lastline =~ s/^\s+$//;
1759 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
1764 local($type, $num, $var, $init, $name_printed) = @_;
1765 local($arg) = "ST(" . ($num - 1) . ")";
1767 if ( $init =~ /^=/ ) {
1768 if ($name_printed) {
1769 eval qq/print " $init\\n"/;
1772 eval qq/print "\\t$var $init\\n"/;
1777 if ( $init =~ s/^\+// && $num ) {
1778 &generate_init($type, $num, $var, $name_printed);
1780 elsif ($name_printed) {
1785 eval qq/print "\\t$var;\\n"/;
1789 $deferred .= eval qq/"\\n\\t$init\\n"/;
1795 # work out the line number
1796 my $line_no = $line_no[@line_no - @line -1];
1798 print STDERR "@_ in $filename, line $line_no\n";
1812 local($type, $num, $var) = @_;
1813 local($arg) = "ST(" . ($num - 1) . ")";
1814 local($argoff) = $num - 1;
1818 $type = TidyType($type);
1819 blurt("Error: '$type' not in typemap"), return
1820 unless defined($type_kind{$type});
1822 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1823 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1824 $tk = $type_kind{$type};
1825 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1826 if ($tk eq 'T_PV' and exists $lengthof{$var}) {
1827 print "\t$var" unless $name_printed;
1828 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1829 die "default value not supported with length(NAME) supplied"
1830 if defined $defaults{$var};
1833 $type =~ tr/:/_/ unless $hiertype;
1834 blurt("Error: No INPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1835 unless defined $input_expr{$tk};
1836 $expr = $input_expr{$tk};
1837 if ($expr =~ /DO_ARRAY_ELEM/) {
1838 blurt("Error: '$subtype' not in typemap"), return
1839 unless defined($type_kind{$subtype});
1840 blurt("Error: No INPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1841 unless defined $input_expr{$type_kind{$subtype}};
1842 $subexpr = $input_expr{$type_kind{$subtype}};
1843 $subexpr =~ s/\$type/\$subtype/g;
1844 $subexpr =~ s/ntype/subtype/g;
1845 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1846 $subexpr =~ s/\n\t/\n\t\t/g;
1847 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1848 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1849 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1851 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1854 if (defined($defaults{$var})) {
1855 $expr =~ s/(\t+)/$1 /g;
1857 if ($name_printed) {
1861 eval qq/print "\\t$var;\\n"/;
1864 if ($defaults{$var} eq 'NO_INIT') {
1865 $deferred .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1868 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1872 elsif ($ScopeThisXSUB or $expr !~ /^\s*\$var =/) {
1873 if ($name_printed) {
1877 eval qq/print "\\t$var;\\n"/;
1880 $deferred .= eval qq/"\\n$expr;\\n"/;
1884 die "panic: do not know how to handle this branch for function pointers"
1886 eval qq/print "$expr;\\n"/;
1891 sub generate_output {
1892 local($type, $num, $var, $do_setmagic, $do_push) = @_;
1893 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
1894 local($argoff) = $num - 1;
1897 $type = TidyType($type);
1898 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1899 print "\t$arg = sv_newmortal();\n";
1900 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1901 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1904 blurt("Error: '$type' not in typemap"), return
1905 unless defined($type_kind{$type});
1906 blurt("Error: No OUTPUT definition for type '$type', typekind '$type_kind{$type}' found"), return
1907 unless defined $output_expr{$type_kind{$type}};
1908 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1909 $ntype =~ s/\(\)//g;
1910 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1911 $expr = $output_expr{$type_kind{$type}};
1912 if ($expr =~ /DO_ARRAY_ELEM/) {
1913 blurt("Error: '$subtype' not in typemap"), return
1914 unless defined($type_kind{$subtype});
1915 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$type_kind{$subtype}' found"), return
1916 unless defined $output_expr{$type_kind{$subtype}};
1917 $subexpr = $output_expr{$type_kind{$subtype}};
1918 $subexpr =~ s/ntype/subtype/g;
1919 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1920 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1921 $subexpr =~ s/\n\t/\n\t\t/g;
1922 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1923 eval "print qq\a$expr\a";
1925 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1927 elsif ($var eq 'RETVAL') {
1928 if ($expr =~ /^\t\$arg = new/) {
1929 # We expect that $arg has refcnt 1, so we need to
1931 eval "print qq\a$expr\a";
1933 print "\tsv_2mortal(ST($num));\n";
1934 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1936 elsif ($expr =~ /^\s*\$arg\s*=/) {
1937 # We expect that $arg has refcnt >=1, so we need
1939 eval "print qq\a$expr\a";
1941 print "\tsv_2mortal(ST(0));\n";
1942 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1945 # Just hope that the entry would safely write it
1946 # over an already mortalized value. By
1947 # coincidence, something like $arg = &sv_undef
1949 print "\tST(0) = sv_newmortal();\n";
1950 eval "print qq\a$expr\a";
1952 # new mortals don't have set magic
1956 print "\tPUSHs(sv_newmortal());\n";
1958 eval "print qq\a$expr\a";
1960 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1962 elsif ($arg =~ /^ST\(\d+\)$/) {
1963 eval "print qq\a$expr\a";
1965 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1971 my($type, $varname) = @_;
1973 # C++ has :: in types too so skip this
1974 $type =~ tr/:/_/ unless $hiertype;
1975 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1977 if ($varname && $type =~ / \( \s* \* (?= \s* \) ) /xg) {
1978 (substr $type, pos $type, 0) = " $varname ";
1981 $type .= "\t$varname";
1988 #########################################################
1990 ExtUtils::ParseXS::CountLines;
1992 our $SECTION_END_MARKER;
1995 my ($class, $cfile, $fh) = @_;
1996 $cfile =~ s/\\/\\\\/g;
1997 $SECTION_END_MARKER = qq{#line --- "$cfile"};
2009 $self->{buffer} .= $_;
2010 while ($self->{buffer} =~ s/^([^\n]*\n)//) {
2012 ++ $self->{line_no};
2013 $line =~ s|^\#line\s+---(?=\s)|#line $self->{line_no}|;
2014 print {$self->{fh}} $line;
2022 $self->PRINT(sprintf($fmt, @_));
2026 # Not necessary if we're careful to end with a "\n"
2028 print {$self->{fh}} $self->{buffer};
2032 # This sub does nothing, but is neccessary for references to be released.
2036 return $SECTION_END_MARKER;