1 package ExtUtils::ParseXS;
4 use 5.006; # We use /??{}/ in regexes
11 use ExtUtils::ParseXS::Constants ();
12 use ExtUtils::ParseXS::CountLines;
13 use ExtUtils::ParseXS::Utilities qw(
14 standard_typemap_locations
24 our @ISA = qw(Exporter);
30 $VERSION = eval $VERSION if $VERSION =~ /_/;
32 # The scalars in the line below remain as 'our' variables because pulling
33 # them into $self led to build problems. In most cases, strings being
34 # 'eval'-ed contain the variables' names hard-coded.
36 $FH, $Package, $func_name, $Full_func_name, $Packid, $pname, $ALIAS,
43 # Allow for $package->process_file(%hash) in the future
44 my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
46 $self->{ProtoUsed} = exists $options{prototypes};
63 $args{except} = $args{except} ? ' TRY' : '';
67 my ($Is_VMS, $SymSet);
70 # Establish set of global symbols with max length 28, since xsubpp
71 # will later add the 'XS_' prefix.
72 require ExtUtils::XSSymSet;
73 $SymSet = new ExtUtils::XSSymSet 28;
75 @{ $self->{XSStack} } = ({type => 'none'});
76 $self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ];
77 $FH = $ExtUtils::ParseXS::Constants::FH;
78 $self->{Overload} = $ExtUtils::ParseXS::Constants::Overload;
79 $self->{errors} = $ExtUtils::ParseXS::Constants::errors;
80 $self->{Fallback} = $ExtUtils::ParseXS::Constants::Fallback;
82 # Most of the 1500 lines below uses these globals. We'll have to
83 # clean this up sometime, probably. For now, we just pull them out
86 $self->{hiertype} = $args{hiertype};
87 $self->{WantPrototypes} = $args{prototypes};
88 $self->{WantVersionChk} = $args{versioncheck};
89 $self->{WantLineNumbers} = $args{linenumbers};
90 $self->{IncludedFiles} = {};
92 for my $f ($args{filename}) {
93 die "Missing required parameter 'filename'" unless $f;
94 $self->{filepathname} = $f;
95 ($self->{dir}, $self->{filename}) = (dirname($f), basename($f));
96 $self->{filepathname} =~ s/\\/\\\\/g;
97 $self->{IncludedFiles}->{$f}++;
100 # Open the output file if given as a string. If they provide some
101 # other kind of reference, trust them that we can print to it.
102 if (not ref $args{output}) {
103 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
104 $args{outfile} = $args{output};
108 # Really, we shouldn't have to chdir() or select() in the first
109 # place. For now, just save & restore.
110 my $orig_cwd = cwd();
111 my $orig_fh = select();
115 my $csuffix = $args{csuffix};
117 if ($self->{WantLineNumbers}) {
119 if ( $args{outfile} ) {
120 $cfile = $args{outfile};
123 $cfile = $args{filename};
124 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
126 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
127 select PSEUDO_STDOUT;
130 select $args{output};
135 $self->{proto_letter},
137 $self->{output_expr},
138 ) = process_typemaps( $args{typemap}, $pwd );
140 foreach my $value (values %{ $self->{input_expr} }) {
141 $value =~ s/;*\s+\z//;
142 # Move C pre-processor instructions to column 1 to be strictly ANSI
143 # conformant. Some pre-processors are fussy about this.
144 $value =~ s/^\s+#/#/mg;
146 foreach my $value (values %{ $self->{output_expr} }) {
148 $value =~ s/^\s+#/#/mg;
151 my %targetable = make_targetable($self->{output_expr});
153 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
155 # Match an XS keyword
156 $self->{BLOCK_re} = '\s*(' .
157 join('|' => @ExtUtils::ParseXS::Constants::keywords) .
160 our ($C_group_rex, $C_arg);
161 # Group in C (no support for comments or literals)
162 $C_group_rex = qr/ [({\[]
163 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
165 # Chunk in C without comma at toplevel (no comments):
166 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
167 | (??{ $C_group_rex })
168 | " (?: (?> [^\\"]+ )
170 )* " # String literal
171 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
174 # Identify the version of xsubpp used
177 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
178 * contents of $self->{filename}. Do not edit this file, edit $self->{filename} instead.
180 * ANY CHANGES MADE HERE WILL BE LOST!
187 print("#line 1 \"$self->{filepathname}\"\n")
188 if $self->{WantLineNumbers};
190 # Open the input file (using $self->{filename} which
191 # is a basename'd $args{filename} due to chdir above)
192 open($FH, $self->{filename}) or die "cannot open $self->{filename}: $!\n";
197 my $podstartline = $.;
200 # We can't just write out a /* */ comment, as our embedded
201 # POD might itself be in a comment. We can't put a /**/
202 # comment inside #if 0, as the C standard says that the source
203 # file is decomposed into preprocessing characters in the stage
204 # before preprocessing commands are executed.
205 # I don't want to leave the text as barewords, because the spec
206 # isn't clear whether macros are expanded before or after
207 # preprocessing commands are executed, and someone pathological
208 # may just have defined one of the 3 words as a macro that does
209 # something strange. Multiline strings are illegal in C, so
210 # the "" we write must be a string literal. And they aren't
211 # concatenated until 2 steps later, so we are safe.
213 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
214 printf("#line %d \"$self->{filepathname}\"\n", $. + 1)
215 if $self->{WantLineNumbers};
220 # At this point $. is at end of file so die won't state the start
221 # of the problem, and as we haven't yet read any lines &death won't
222 # show the correct line in the message either.
223 die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n")
224 unless $self->{lastline};
226 last if ($Package, $self->{Prefix}) =
227 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
231 unless (defined $_) {
232 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
233 exit 0; # Not a fatal error for the caller process
236 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
239 #ifndef PERL_UNUSED_VAR
240 # define PERL_UNUSED_VAR(var) if (0) var = var
246 #ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
247 #define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)
249 /* prototype to pass -Wmissing-prototypes */
251 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params);
254 S_croak_xs_usage(pTHX_ const CV *const cv, const char *const params)
256 const GV *const gv = CvGV(cv);
258 PERL_ARGS_ASSERT_CROAK_XS_USAGE;
261 const char *const gvname = GvNAME(gv);
262 const HV *const stash = GvSTASH(gv);
263 const char *const hvname = stash ? HvNAME(stash) : NULL;
266 Perl_croak(aTHX_ "Usage: %s::%s(%s)", hvname, gvname, params);
268 Perl_croak(aTHX_ "Usage: %s(%s)", gvname, params);
270 /* Pants. I don't think that it should be possible to get here. */
271 Perl_croak(aTHX_ "Usage: CODE(0x%"UVxf")(%s)", PTR2UV(cv), params);
274 #undef PERL_ARGS_ASSERT_CROAK_XS_USAGE
276 #ifdef PERL_IMPLICIT_CONTEXT
277 #define croak_xs_usage(a,b) S_croak_xs_usage(aTHX_ a,b)
279 #define croak_xs_usage S_croak_xs_usage
284 /* NOTE: the prototype of newXSproto() is different in versions of perls,
285 * so we define a portable version of newXSproto()
288 #define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
290 #define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
291 #endif /* !defined(newXS_flags) */
295 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
297 $self->{lastline} = $_;
298 $self->{lastline_no} = $.;
300 my (@outlist, $prepush_done, $xsreturn, $func_header, $orig_args, );
301 my $BootCode_ref = [];
302 my $XSS_work_idx = 0;
303 my $cpp_next_tmp = 'XSubPPtmpAAAA';
305 while (fetch_para()) {
306 # Print initial preprocessor statements and blank lines
307 while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) {
308 my $ln = shift(@{ $self->{line} });
310 next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
312 if ($statement eq 'if') {
313 $XSS_work_idx = @{ $self->{XSStack} };
314 push(@{ $self->{XSStack} }, {type => 'if'});
317 death ("Error: `$statement' with no matching `if'")
318 if $self->{XSStack}->[-1]{type} ne 'if';
319 if ($self->{XSStack}->[-1]{varname}) {
320 push(@{ $self->{InitFileCode} }, "#endif\n");
321 push(@{ $BootCode_ref }, "#endif");
324 my(@fns) = keys %{$self->{XSStack}->[-1]{functions}};
325 if ($statement ne 'endif') {
326 # Hide the functions defined in other #if branches, and reset.
327 @{$self->{XSStack}->[-1]{other_functions}}{@fns} = (1) x @fns;
328 @{$self->{XSStack}->[-1]}{qw(varname functions)} = ('', {});
331 my($tmp) = pop(@{ $self->{XSStack} });
332 0 while (--$XSS_work_idx
333 && $self->{XSStack}->[$XSS_work_idx]{type} ne 'if');
334 # Keep all new defined functions
335 push(@fns, keys %{$tmp->{other_functions}});
336 @{$self->{XSStack}->[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
341 next PARAGRAPH unless @{ $self->{line} };
343 if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) {
344 # We are inside an #if, but have not yet #defined its xsubpp variable.
345 print "#define $cpp_next_tmp 1\n\n";
346 push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n");
347 push(@{ $BootCode_ref }, "#if $cpp_next_tmp");
348 $self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++;
351 death ("Code is not inside a function"
352 ." (maybe last function was ended by a blank line "
353 ." followed by a statement on column one?)")
354 if $self->{line}->[0] =~ /^\s/;
356 my ($class, $externC, $static, $ellipsis, $wantRETVAL, $RETVAL_no_return);
357 my (@fake_INPUT_pre); # For length(s) generated variables
360 # initialize info arrays
361 undef(%{ $self->{args_match} });
362 undef(%{ $self->{var_types} });
363 undef(%{ $self->{defaults} });
364 undef(%{ $self->{arg_list} });
365 undef(@{ $self->{proto_arg} });
366 undef($self->{processing_arg_with_types});
367 undef(%{ $self->{argtype_seen} });
369 undef(%{ $self->{in_out} });
370 undef(%{ $self->{lengthof} });
371 undef($self->{proto_in_this_xsub});
372 undef($self->{scope_in_this_xsub});
373 undef($self->{interface});
374 undef($prepush_done);
375 $self->{interface_macro} = 'XSINTERFACE_FUNC';
376 $self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET';
377 $self->{ProtoThisXSUB} = $self->{WantPrototypes};
378 $self->{ScopeThisXSUB} = 0;
381 $_ = shift(@{ $self->{line} });
382 while (my $kwd = check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
384 &{"${kwd}_handler"}();
386 next PARAGRAPH unless @{ $self->{line} };
387 $_ = shift(@{ $self->{line} });
390 if (check_keyword("BOOT")) {
392 push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \"$self->{filepathname}\"")
393 if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/;
394 push (@{ $BootCode_ref }, @{ $self->{line} }, "");
398 # extract return type, function name and arguments
399 ($self->{ret_type}) = tidy_type($_);
400 $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//;
402 # Allow one-line ANSI-like declaration
403 unshift @{ $self->{line} }, $2
405 and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
407 # a function definition needs at least 2 lines
408 blurt ("Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH
409 unless @{ $self->{line} };
411 $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
412 $static = 1 if $self->{ret_type} =~ s/^static\s+//;
414 $func_header = shift(@{ $self->{line} });
415 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
416 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
418 ($class, $func_name, $orig_args) = ($1, $2, $3);
419 $class = "$4 $class" if $4;
420 ($pname = $func_name) =~ s/^($self->{Prefix})?/$self->{Packprefix}/;
422 ($clean_func_name = $func_name) =~ s/^$self->{Prefix}//;
423 $Full_func_name = "${Packid}_$clean_func_name";
425 $Full_func_name = $SymSet->addsym($Full_func_name);
428 # Check for duplicate function definition
429 for my $tmp (@{ $self->{XSStack} }) {
430 next unless defined $tmp->{functions}{$Full_func_name};
431 Warn("Warning: duplicate function definition '$clean_func_name' detected");
434 $self->{XSStack}->[$XSS_work_idx]{functions}{$Full_func_name}++;
435 %{ $self->{XsubAliases} } = %{ $self->{XsubAliasValues} } = %{ $self->{Interfaces} } = @{ $self->{Attributes} } = ();
436 $self->{DoSetMagic} = 1;
438 $orig_args =~ s/\\\s*/ /g; # process line continuations
441 my %only_C_inlist; # Not in the signature of Perl function
442 if ($args{argtypes} and $orig_args =~ /\S/) {
443 my $args = "$orig_args ,";
444 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
445 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
449 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
450 my ($pre, $len_name) = ($arg =~ /(.*?) \s*
451 \b ( \w+ | length\( \s*\w+\s* \) )
453 next unless defined($pre) && length($pre);
456 if ($args{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
458 $out_type = $type if $type ne 'IN';
459 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
460 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
463 if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
464 $len_name = "XSauto_length_of_$1";
466 die "Default value on length() argument: `$_'"
469 if (length $pre or $islength) { # Has a type
471 push @fake_INPUT_pre, $arg;
474 push @fake_INPUT, $arg;
476 # warn "pushing '$arg'\n";
477 $self->{argtype_seen}->{$len_name}++;
478 $_ = "$len_name$default"; # Assigns to @args
480 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST" or $islength;
481 push @outlist, $len_name if $out_type =~ /OUTLIST$/;
482 $self->{in_out}->{$len_name} = $out_type if $out_type;
486 @args = split(/\s*,\s*/, $orig_args);
487 Warn("Warning: cannot parse argument list '$orig_args', fallback to split");
491 @args = split(/\s*,\s*/, $orig_args);
493 if ($args{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
495 next if $out_type eq 'IN';
496 $only_C_inlist{$_} = 1 if $out_type eq "OUTLIST";
497 if ($out_type =~ /OUTLIST$/) {
498 push @outlist, undef;
500 $self->{in_out}->{$_} = $out_type;
504 if (defined($class)) {
505 my $arg0 = ((defined($static) or $func_name eq 'new')
507 unshift(@args, $arg0);
512 my $report_args = '';
513 foreach my $i (0 .. $#args) {
514 if ($args[$i] =~ s/\.\.\.//) {
516 if ($args[$i] eq '' && $i == $#args) {
517 $report_args .= ", ...";
522 if ($only_C_inlist{$args[$i]}) {
523 push @args_num, undef;
526 push @args_num, ++$num_args;
527 $report_args .= ", $args[$i]";
529 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
532 $self->{defaults}->{$args[$i]} = $2;
533 $self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
535 $self->{proto_arg}->[$i+1] = '$';
537 my $min_args = $num_args - $extra_args;
538 $report_args =~ s/"/\\"/g;
539 $report_args =~ s/^,\s+//;
540 my @func_args = @args;
541 shift @func_args if defined($class);
544 s/^/&/ if $self->{in_out}->{$_};
546 $self->{func_args} = join(", ", @func_args);
547 @{ $self->{args_match} }{@args} = @args_num;
549 my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} });
550 my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} });
551 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
552 # to set explicit return values.
553 my $EXPLICIT_RETURN = ($CODE &&
554 ("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
556 # The $ALIAS which follows is only explicitly called within the scope of
557 # process_file(). In principle, it ought to be a lexical, i.e., 'my
558 # $ALIAS' like the other nearby variables. However, implementing that
559 # change produced a slight difference in the resulting .c output in at
560 # least two distributions: B/BD/BDFOY/Crypt-Rijndael and
561 # G/GF/GFUJI/Hash-FieldHash. The difference is, arguably, an improvement
562 # in the resulting C code. Example:
564 # < GvNAME(CvGV(cv)),
566 # > "Crypt::Rijndael::encrypt",
567 # But at this point we're committed to generating the *same* C code that
568 # the current version of ParseXS.pm does. So we're declaring it as 'our'.
569 $ALIAS = grep(/^\s*ALIAS\s*:/, @{ $self->{line} });
571 my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @{ $self->{line} });
573 $xsreturn = 1 if $EXPLICIT_RETURN;
575 $externC = $externC ? qq[extern "C"] : "";
577 # print function header
580 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
581 #XS(XS_${Full_func_name})
589 print Q(<<"EOF") if $ALIAS;
592 print Q(<<"EOF") if $INTERFACE;
593 # dXSFUNCTION($self->{ret_type});
596 $self->{cond} = ($min_args ? qq(items < $min_args) : 0);
598 elsif ($min_args == $num_args) {
599 $self->{cond} = qq(items != $min_args);
602 $self->{cond} = qq(items < $min_args || items > $num_args);
605 print Q(<<"EOF") if $args{except};
613 # croak_xs_usage(cv, "$report_args");
617 # cv likely to be unused
619 # PERL_UNUSED_VAR(cv); /* -W */
623 #gcc -Wall: if an xsub has PPCODE is used
624 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
625 #hence `ax' (setup by dXSARGS) is unused
626 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
627 #but such a move could break third-party extensions
628 print Q(<<"EOF") if $PPCODE;
629 # PERL_UNUSED_VAR(ax); /* -Wall */
632 print Q(<<"EOF") if $PPCODE;
636 # Now do a block of some sort.
638 $self->{condnum} = 0;
639 $self->{cond} = ''; # last CASE: condidional
640 push(@{ $self->{line} }, "$END:");
641 push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
644 while (@{ $self->{line} }) {
645 &CASE_handler if check_keyword("CASE");
650 # do initialization of input variables
651 $self->{thisdone} = 0;
652 $self->{retvaldone} = 0;
653 $self->{deferred} = "";
654 %{ $self->{arg_list} } = ();
655 $self->{gotRETVAL} = 0;
658 process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
660 print Q(<<"EOF") if $self->{ScopeThisXSUB};
665 if (!$self->{thisdone} && defined($class)) {
666 if (defined($static) or $func_name eq 'new') {
668 $self->{var_types}->{"CLASS"} = "char *";
673 printed_name => undef,
678 $self->{var_types}->{"THIS"} = "$class *";
683 printed_name => undef,
689 if (/^\s*NOT_IMPLEMENTED_YET/) {
690 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
694 if ($self->{ret_type} ne "void") {
695 print "\t" . &map_type($self->{ret_type}, 'RETVAL', $self->{hiertype}) . ";\n"
696 if !$self->{retvaldone};
697 $self->{args_match}->{"RETVAL"} = 0;
698 $self->{var_types}->{"RETVAL"} = $self->{ret_type};
700 if $args{optimize} and $targetable{$self->{type_kind}->{$self->{ret_type}}};
703 if (@fake_INPUT or @fake_INPUT_pre) {
704 unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
706 $self->{processing_arg_with_types} = 1;
709 print $self->{deferred};
711 process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
713 if (check_keyword("PPCODE")) {
715 death ("PPCODE must be last thing") if @{ $self->{line} };
716 print "\tLEAVE;\n" if $self->{ScopeThisXSUB};
717 print "\tPUTBACK;\n\treturn;\n";
719 elsif (check_keyword("CODE")) {
722 elsif (defined($class) and $func_name eq "DESTROY") {
724 print "delete THIS;\n";
728 if ($self->{ret_type} ne "void") {
732 if (defined($static)) {
733 if ($func_name eq 'new') {
734 $func_name = "$class";
740 elsif (defined($class)) {
741 if ($func_name eq 'new') {
742 $func_name .= " $class";
748 $func_name =~ s/^\Q$args{'s'}//
749 if exists $args{'s'};
750 $func_name = 'XSFUNCTION' if $self->{interface};
751 print "$func_name($self->{func_args});\n";
755 # do output variables
756 $self->{gotRETVAL} = 0; # 1 if RETVAL seen in OUTPUT section;
757 undef $self->{RETVAL_code} ; # code to set RETVAL (from OUTPUT section);
758 # $wantRETVAL set if 'RETVAL =' autogenerated
759 ($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return;
760 undef %{ $self->{outargs} };
761 process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
764 type => $self->{var_types}->{$_},
765 num => $self->{args_match}->{$_},
767 do_setmagic => $self->{DoSetMagic},
769 } ) for grep $self->{in_out}->{$_} =~ /OUT$/, keys %{ $self->{in_out} };
771 # all OUTPUT done, so now push the return value on the stack
772 if ($self->{gotRETVAL} && $self->{RETVAL_code}) {
773 print "\t$self->{RETVAL_code}\n";
775 elsif ($self->{gotRETVAL} || $wantRETVAL) {
776 my $t = $args{optimize} && $targetable{$self->{type_kind}->{$self->{ret_type}}};
777 # Although the '$var' declared in the next line is never explicitly
778 # used within this 'elsif' block, commenting it out leads to
779 # disaster, starting with the first 'eval qq' inside the 'elsif' block
781 # It appears that this is related to the fact that at this point the
782 # value of $t is a reference to an array whose [2] element includes
783 # '$var' as a substring:
786 my $type = $self->{ret_type};
788 # 0: type, 1: with_size, 2: how, 3: how_size
789 if ($t and not $t->[1] and $t->[0] eq 'p') {
790 # PUSHp corresponds to setpvn. Treate setpv directly
791 my $what = eval qq("$t->[2]");
794 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
798 my $what = eval qq("$t->[2]");
802 $tsize = '' unless defined $tsize;
803 $tsize = eval qq("$tsize");
805 print "\tXSprePUSH; PUSH$t->[0]($what$tsize);\n";
809 # RETVAL almost never needs SvSETMAGIC()
811 type => $self->{ret_type},
820 $xsreturn = 1 if $self->{ret_type} ne "void";
823 print "\tXSprePUSH;" if $c and not $prepush_done;
824 print "\tEXTEND(SP,$c);\n" if $c;
827 type => $self->{var_types}->{$_},
835 process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
837 print Q(<<"EOF") if $self->{ScopeThisXSUB};
840 print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
844 # print function trailer
848 print Q(<<"EOF") if $args{except};
851 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
854 if (check_keyword("CASE")) {
855 blurt ("Error: No `CASE:' at top of function")
856 unless $self->{condnum};
857 $_ = "CASE: $_"; # Restore CASE: label
860 last if $_ eq "$END:";
861 death(/^$self->{BLOCK_re}/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
864 print Q(<<"EOF") if $args{except};
866 # Perl_croak(aTHX_ errbuf);
870 print Q(<<"EOF") unless $PPCODE;
871 # XSRETURN($xsreturn);
875 print Q(<<"EOF") unless $PPCODE;
885 $self->{newXS} = "newXS";
888 # Build the prototype string for the xsub
889 if ($self->{ProtoThisXSUB}) {
890 $self->{newXS} = "newXSproto_portable";
892 if ($self->{ProtoThisXSUB} eq 2) {
893 # User has specified empty prototype
895 elsif ($self->{ProtoThisXSUB} eq 1) {
897 if ($min_args < $num_args) {
899 $self->{proto_arg}->[$min_args] .= ";";
901 push @{ $self->{proto_arg} }, "$s\@"
904 $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
907 # User has specified a prototype
908 $self->{proto} = $self->{ProtoThisXSUB};
910 $self->{proto} = qq{, "$self->{proto}"};
913 if (%{ $self->{XsubAliases} }) {
914 $self->{XsubAliases}->{$pname} = 0
915 unless defined $self->{XsubAliases}->{$pname};
916 while ( my ($xname, $value) = each %{ $self->{XsubAliases} }) {
917 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
918 # cv = $self->{newXS}(\"$xname\", XS_$Full_func_name, file$self->{proto});
919 # XSANY.any_i32 = $value;
923 elsif (@{ $self->{Attributes} }) {
924 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
925 # cv = $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});
926 # apply_attrs_string("$Package", cv, "@{ $self->{Attributes} }", 0);
929 elsif ($self->{interface}) {
930 while ( my ($yname, $value) = each %{ $self->{Interfaces} }) {
931 $yname = "$Package\::$yname" unless $yname =~ /::/;
932 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
933 # cv = $self->{newXS}(\"$yname\", XS_$Full_func_name, file$self->{proto});
934 # $self->{interface_macro_set}(cv,$value);
938 elsif($self->{newXS} eq 'newXS'){ # work around P5NCI's empty newXS macro
939 push(@{ $self->{InitFileCode} },
940 " $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
943 push(@{ $self->{InitFileCode} },
944 " (void)$self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
946 } # END 'PARAGRAPH' 'while' loop
948 if ($self->{Overload}) { # make it findable with fetchmethod
950 #XS(XS_${Packid}_nil); /* prototype to pass -Wmissing-prototypes */
951 #XS(XS_${Packid}_nil)
958 unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK");
959 /* Making a sub named "${Package}::()" allows the package */
960 /* to be findable via fetchmethod(), and causes */
961 /* overload::Overloaded("${Package}") to return true. */
962 (void)$self->{newXS}("${Package}::()", XS_${Packid}_nil, file$self->{proto});
963 MAKE_FETCHMETHOD_WORK
966 # print initialization routine
975 #XS(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
976 #XS(boot_$self->{Module_cname})
988 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
989 #file name argument. If the wrong qualifier is used, it causes breakage with
990 #C++ compilers and warnings with recent gcc.
991 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
993 print Q(<<"EOF") if $Full_func_name;
994 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
995 # char* file = __FILE__;
997 # const char* file = __FILE__;
1004 # PERL_UNUSED_VAR(cv); /* -W */
1005 # PERL_UNUSED_VAR(items); /* -W */
1008 print Q(<<"EOF") if $self->{WantVersionChk};
1009 # XS_VERSION_BOOTCHECK;
1013 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
1019 print Q(<<"EOF") if ($self->{Overload});
1020 # /* register the overloading (type 'A') magic */
1021 # PL_amagic_generation++;
1022 # /* The magic for overload gets a GV* via gv_fetchmeth as */
1023 # /* mentioned above, and looks in the SV* slot of it for */
1024 # /* the "fallback" status. */
1026 # get_sv( "${Package}::()", TRUE ),
1031 print @{ $self->{InitFileCode} };
1033 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
1037 if (@{ $BootCode_ref }) {
1038 print "\n /* Initialisation Section */\n\n";
1039 @{ $self->{line} } = @{ $BootCode_ref };
1041 print "\n /* End of Initialisation Section */\n\n";
1045 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
1046 # if (PL_unitcheckav)
1047 # call_list(PL_scopestack_ix, PL_unitcheckav);
1057 warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
1058 unless $self->{ProtoUsed};
1062 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
1068 sub report_error_count { $self->{errors} }
1070 # Input: ($_, @{ $self->{line} }) == unparsed input.
1071 # Output: ($_, @{ $self->{line} }) == (rest of line, following lines).
1072 # Return: the matched keyword if found, otherwise 0
1074 $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} };
1075 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1079 # the "do" is required for right semantics
1080 do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} };
1082 print("#line ", $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1], " \"$self->{filepathname}\"\n")
1083 if $self->{WantLineNumbers} && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1084 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1087 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
1093 while (!/\S/ && @{ $self->{line} }) {
1094 $_ = shift(@{ $self->{line} });
1097 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1104 sub process_keyword($) {
1109 &{"${kwd}_handler"}()
1110 while $kwd = check_keyword($pattern);
1115 blurt ("Error: `CASE:' after unconditional `CASE:'")
1116 if $self->{condnum} && $self->{cond} eq '';
1118 trim_whitespace($self->{cond});
1119 print " ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n");
1124 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1125 last if /^\s*NOT_IMPLEMENTED_YET/;
1126 next unless /\S/; # skip blank lines
1128 trim_whitespace($_);
1131 # remove trailing semicolon if no initialisation
1132 s/\s*;$//g unless /[=;+].*\S/;
1134 # Process the length(foo) declarations
1135 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1136 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1137 $self->{lengthof}->{$2} = undef;
1138 $self->{deferred} .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1141 # check for optional initialisation code
1143 $var_init = $1 if s/\s*([=;+].*)$//s;
1144 $var_init =~ s/"/\\"/g;
1147 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1148 or blurt("Error: invalid argument declaration '$ln'"), next;
1150 # Check for duplicate definitions
1151 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
1152 if $self->{arg_list}->{$var_name}++
1153 or defined $self->{argtype_seen}->{$var_name} and not $self->{processing_arg_with_types};
1155 $self->{thisdone} |= $var_name eq "THIS";
1156 $self->{retvaldone} |= $var_name eq "RETVAL";
1157 $self->{var_types}->{$var_name} = $var_type;
1158 # XXXX This check is a safeguard against the unfinished conversion of
1159 # generate_init(). When generate_init() is fixed,
1160 # one can use 2-args map_type() unconditionally.
1162 if ($var_type =~ / \( \s* \* \s* \) /x) {
1163 # Function pointers are not yet supported with &output_init!
1164 print "\t" . &map_type($var_type, $var_name, $self->{hiertype});
1168 print "\t" . &map_type($var_type, undef, $self->{hiertype});
1171 $self->{var_num} = $self->{args_match}->{$var_name};
1173 if ($self->{var_num}) {
1174 $self->{proto_arg}->[$self->{var_num}] = $self->{proto_letter}->{$var_type} || "\$";
1176 $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr;
1177 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1178 or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/
1179 and $var_init !~ /\S/) {
1180 if ($printed_name) {
1184 print "\t$var_name;\n";
1187 elsif ($var_init =~ /\S/) {
1190 num => $self->{var_num},
1193 printed_name => $printed_name,
1196 elsif ($self->{var_num}) {
1199 num => $self->{var_num},
1201 printed_name => $printed_name,
1210 sub OUTPUT_handler {
1211 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1213 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1214 $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
1217 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1218 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1219 if $self->{outargs}->{$outarg}++;
1220 if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') {
1221 # deal with RETVAL last
1222 $self->{RETVAL_code} = $outcode;
1223 $self->{gotRETVAL} = 1;
1226 blurt ("Error: OUTPUT $outarg not an argument"), next
1227 unless defined($self->{args_match}->{$outarg});
1228 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1229 unless defined $self->{var_types}->{$outarg};
1230 $self->{var_num} = $self->{args_match}->{$outarg};
1232 print "\t$outcode\n";
1233 print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
1237 type => $self->{var_types}->{$outarg},
1238 num => $self->{var_num},
1240 do_setmagic => $self->{DoSetMagic},
1244 delete $self->{in_out}->{$outarg} # No need to auto-OUTPUT
1245 if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
1249 sub C_ARGS_handler() {
1250 my $in = merge_section();
1252 trim_whitespace($in);
1253 $self->{func_args} = $in;
1256 sub INTERFACE_MACRO_handler() {
1257 my $in = merge_section();
1259 trim_whitespace($in);
1260 if ($in =~ /\s/) { # two
1261 ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
1264 $self->{interface_macro} = $in;
1265 $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
1267 $self->{interface} = 1; # local
1268 $self->{interfaces} = 1; # global
1271 sub INTERFACE_handler() {
1272 my $in = merge_section();
1274 trim_whitespace($in);
1276 foreach (split /[\s,]+/, $in) {
1277 my $iface_name = $_;
1278 $iface_name =~ s/^$self->{Prefix}//;
1279 $self->{Interfaces}->{$iface_name} = $_;
1282 # XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
1284 $self->{interface} = 1; # local
1285 $self->{interfaces} = 1; # global
1288 sub CLEANUP_handler() { print_section() }
1289 sub PREINIT_handler() { print_section() }
1290 sub POSTCALL_handler() { print_section() }
1291 sub INIT_handler() { print_section() }
1297 # Parse alias definitions
1299 # alias = value alias = value ...
1301 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1302 my ($alias, $value) = ($1, $2);
1303 my $orig_alias = $alias;
1305 # check for optional package definition in the alias
1306 $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
1308 # check for duplicate alias name & duplicate value
1309 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
1310 if defined $self->{XsubAliases}->{$alias};
1312 Warn("Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
1313 if $self->{XsubAliasValues}->{$value};
1315 $self->{xsubaliases} = 1;
1316 $self->{XsubAliases}->{$alias} = $value;
1317 $self->{XsubAliasValues}->{$value} = $orig_alias;
1320 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
1324 sub ATTRS_handler () {
1325 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1327 trim_whitespace($_);
1328 push @{ $self->{Attributes} }, $_;
1332 sub ALIAS_handler () {
1333 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1335 trim_whitespace($_);
1336 GetAliases($_) if $_;
1340 sub OVERLOAD_handler() {
1341 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1343 trim_whitespace($_);
1344 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1345 $self->{Overload} = 1 unless $self->{Overload};
1346 my $overload = "$Package\::(".$1;
1347 push(@{ $self->{InitFileCode} },
1348 " (void)$self->{newXS}(\"$overload\", XS_$Full_func_name, file$self->{proto});\n");
1353 sub FALLBACK_handler() {
1354 # the rest of the current line should contain either TRUE,
1357 trim_whitespace($_);
1359 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1360 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1361 UNDEF => "&PL_sv_undef",
1364 # check for valid FALLBACK value
1365 death ("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1367 $self->{Fallback} = $map{uc $_};
1371 sub REQUIRE_handler () {
1372 # the rest of the current line should contain a version number
1375 trim_whitespace($Ver);
1377 death ("Error: REQUIRE expects a version number")
1380 # check that the version number is of the form n.n
1381 death ("Error: REQUIRE: expected a number, got '$Ver'")
1382 unless $Ver =~ /^\d+(\.\d*)?/;
1384 death ("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1385 unless $VERSION >= $Ver;
1388 sub VERSIONCHECK_handler () {
1389 # the rest of the current line should contain either ENABLE or
1392 trim_whitespace($_);
1394 # check for ENABLE/DISABLE
1395 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
1396 unless /^(ENABLE|DISABLE)/i;
1398 $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1399 $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
1403 sub PROTOTYPE_handler () {
1406 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1407 if $self->{proto_in_this_xsub}++;
1409 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1412 trim_whitespace($_);
1413 if ($_ eq 'DISABLE') {
1414 $self->{ProtoThisXSUB} = 0;
1416 elsif ($_ eq 'ENABLE') {
1417 $self->{ProtoThisXSUB} = 1;
1420 # remove any whitespace
1422 death("Error: Invalid prototype '$_'")
1423 unless valid_proto_string($_);
1424 $self->{ProtoThisXSUB} = C_string($_);
1428 # If no prototype specified, then assume empty prototype ""
1429 $self->{ProtoThisXSUB} = 2 unless $specified;
1431 $self->{ProtoUsed} = 1;
1434 sub SCOPE_handler () {
1435 death("Error: Only 1 SCOPE declaration allowed per xsub")
1436 if $self->{scope_in_this_xsub}++;
1438 trim_whitespace($_);
1439 death ("Error: SCOPE: ENABLE/DISABLE")
1440 unless /^(ENABLE|DISABLE)\b/i;
1441 $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
1444 sub PROTOTYPES_handler () {
1445 # the rest of the current line should contain either ENABLE or
1448 trim_whitespace($_);
1450 # check for ENABLE/DISABLE
1451 death ("Error: PROTOTYPES: ENABLE/DISABLE")
1452 unless /^(ENABLE|DISABLE)/i;
1454 $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1455 $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
1456 $self->{ProtoUsed} = 1;
1462 # Save the current file context.
1463 push(@{ $self->{XSStack} }, {
1465 LastLine => $self->{lastline},
1466 LastLineNo => $self->{lastline_no},
1467 Line => $self->{line},
1468 LineNo => $self->{line_no},
1469 Filename => $self->{filename},
1470 Filepathname => $self->{filepathname},
1472 IsPipe => scalar($self->{filename} =~ /\|\s*$/),
1478 sub INCLUDE_handler () {
1479 # the rest of the current line should contain a valid filename
1481 trim_whitespace($_);
1483 death("INCLUDE: filename missing")
1486 death("INCLUDE: output pipe is illegal")
1489 # simple minded recursion detector
1490 death("INCLUDE loop detected")
1491 if $self->{IncludedFiles}->{$_};
1493 ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
1495 if (/\|\s*$/ && /^\s*perl\s/) {
1496 Warn("The INCLUDE directive with a command is discouraged." .
1497 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1498 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1499 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1500 " the use of \$^X as the currently running perl, see" .
1501 " 'perldoc perlxs' for details.");
1506 $FH = Symbol::gensym();
1509 open ($FH, "$_") or death("Cannot open '$_': $!");
1513 #/* INCLUDE: Including '$_' from '$self->{filename}' */
1517 $self->{filename} = $_;
1518 $self->{filepathname} = File::Spec->catfile($self->{dir}, $self->{filename});
1520 # Prime the pump by reading the first
1523 # skip leading blank lines
1525 last unless /^\s*$/;
1528 $self->{lastline} = $_;
1529 $self->{lastline_no} = $.;
1534 my @args = split /\s+/, $cmd;
1537 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1539 return join (' ', ($cmd, @args));
1542 sub INCLUDE_COMMAND_handler () {
1543 # the rest of the current line should contain a valid command
1545 trim_whitespace($_);
1547 $_ = QuoteArgs($_) if $^O eq 'VMS';
1549 death("INCLUDE_COMMAND: command missing")
1552 death("INCLUDE_COMMAND: pipes are illegal")
1553 if /^\s*\|/ or /\|\s*$/;
1555 PushXSStack( IsPipe => 1 );
1557 $FH = Symbol::gensym();
1559 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1560 # the same perl interpreter as we're currently running
1564 open ($FH, "-|", "$_")
1565 or death("Cannot run command '$_' to include its output: $!");
1569 #/* INCLUDE_COMMAND: Including output of '$_' from '$self->{filename}' */
1573 $self->{filename} = $_;
1574 $self->{filepathname} = $self->{filename};
1575 $self->{filepathname} =~ s/\"/\\"/g;
1577 # Prime the pump by reading the first
1580 # skip leading blank lines
1582 last unless /^\s*$/;
1585 $self->{lastline} = $_;
1586 $self->{lastline_no} = $.;
1590 return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
1592 my $data = pop @{ $self->{XSStack} };
1593 my $ThisFile = $self->{filename};
1594 my $isPipe = $data->{IsPipe};
1596 --$self->{IncludedFiles}->{$self->{filename}}
1601 $FH = $data->{Handle};
1602 # $filename is the leafname, which for some reason isused for diagnostic
1603 # messages, whereas $filepathname is the full pathname, and is used for
1605 $self->{filename} = $data->{Filename};
1606 $self->{filepathname} = $data->{Filepathname};
1607 $self->{lastline} = $data->{LastLine};
1608 $self->{lastline_no} = $data->{LastLineNo};
1609 @{ $self->{line} } = @{ $data->{Line} };
1610 @{ $self->{line_no} } = @{ $data->{LineNo} };
1612 if ($isPipe and $? ) {
1613 --$self->{lastline_no};
1614 print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
1620 #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
1628 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @{ $self->{line} });
1630 my ($cpp, $cpplevel);
1632 if ($cpp =~ /^\#\s*if/) {
1635 elsif (!$cpplevel) {
1636 Warn("Warning: #else/elif/endif without #if in this function");
1637 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
1638 if $self->{XSStack}->[-1]{type} eq 'if';
1641 elsif ($cpp =~ /^\#\s*endif/) {
1645 Warn("Warning: #if without #endif in this function") if $cpplevel;
1653 $text =~ s/\[\[/{/g;
1654 $text =~ s/\]\]/}/g;
1658 # Read next xsub into @{ $self->{line} } from ($lastline, <$FH>).
1661 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
1662 if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if';
1663 @{ $self->{line} } = ();
1664 @{ $self->{line_no} } = ();
1665 return PopFile() if !defined $self->{lastline};
1667 if ($self->{lastline} =~
1668 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1670 $Package = defined($2) ? $2 : ''; # keep -w happy
1671 $self->{Prefix} = defined($3) ? $3 : ''; # keep -w happy
1672 $self->{Prefix} = quotemeta $self->{Prefix};
1673 ($self->{Module_cname} = $Module) =~ s/\W/_/g;
1674 ($Packid = $Package) =~ tr/:/_/;
1675 $self->{Packprefix} = $Package;
1676 $self->{Packprefix} .= "::" if $self->{Packprefix} ne "";
1677 $self->{lastline} = "";
1681 # Skip embedded PODs
1682 while ($self->{lastline} =~ /^=/) {
1683 while ($self->{lastline} = <$FH>) {
1684 last if ($self->{lastline} =~ /^=cut\s*$/);
1686 death ("Error: Unterminated pod") unless $self->{lastline};
1687 $self->{lastline} = <$FH>;
1688 chomp $self->{lastline};
1689 $self->{lastline} =~ s/^\s+$//;
1691 if ($self->{lastline} !~ /^\s*#/ ||
1693 # ANSI: if ifdef ifndef elif else endif define undef
1695 # gcc: warning include_next
1697 # others: ident (gcc notes that some cpps have this one)
1698 $self->{lastline} =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1699 last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq "";
1700 push(@{ $self->{line} }, $self->{lastline});
1701 push(@{ $self->{line_no} }, $self->{lastline_no});
1704 # Read next line and continuation lines
1705 last unless defined($self->{lastline} = <$FH>);
1706 $self->{lastline_no} = $.;
1708 $self->{lastline} .= $tmp_line
1709 while ($self->{lastline} =~ /\\$/ && defined($tmp_line = <$FH>));
1711 chomp $self->{lastline};
1712 $self->{lastline} =~ s/^\s+$//;
1714 pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq "";
1719 my $argsref = shift;
1720 my ($type, $num, $var, $init, $printed_name) = (
1725 $argsref->{printed_name}
1727 my $arg = "ST(" . ($num - 1) . ")";
1729 if ( $init =~ /^=/ ) {
1730 if ($printed_name) {
1731 eval qq/print " $init\\n"/;
1734 eval qq/print "\\t$var $init\\n"/;
1739 if ( $init =~ s/^\+// && $num ) {
1744 printed_name => $printed_name,
1747 elsif ($printed_name) {
1752 eval qq/print "\\t$var;\\n"/;
1756 $self->{deferred} .= eval qq/"\\n\\t$init\\n"/;
1762 my $argsref = shift;
1763 my ($type, $num, $var, $printed_name) = (
1767 $argsref->{printed_name},
1769 my $arg = "ST(" . ($num - 1) . ")";
1770 my ($argoff, $ntype, $tk);
1773 $type = tidy_type($type);
1774 blurt("Error: '$type' not in typemap"), return
1775 unless defined($self->{type_kind}->{$type});
1777 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1779 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1780 $tk = $self->{type_kind}->{$type};
1781 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1782 if ($tk eq 'T_PV' and exists $self->{lengthof}->{$var}) {
1783 print "\t$var" unless $printed_name;
1784 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1785 die "default value not supported with length(NAME) supplied"
1786 if defined $self->{defaults}->{$var};
1789 $type =~ tr/:/_/ unless $self->{hiertype};
1790 blurt("Error: No INPUT definition for type '$type', typekind '$self->{type_kind}->{$type}' found"), return
1791 unless defined $self->{input_expr}->{$tk};
1792 my $expr = $self->{input_expr}->{$tk};
1793 if ($expr =~ /DO_ARRAY_ELEM/) {
1794 blurt("Error: '$subtype' not in typemap"), return
1795 unless defined($self->{type_kind}->{$subtype});
1796 blurt("Error: No INPUT definition for type '$subtype', typekind '$self->{type_kind}->{$subtype}' found"), return
1797 unless defined $self->{input_expr}->{$self->{type_kind}->{$subtype}};
1798 my $subexpr = $self->{input_expr}->{$self->{type_kind}->{$subtype}};
1799 $subexpr =~ s/\$type/\$subtype/g;
1800 $subexpr =~ s/ntype/subtype/g;
1801 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1802 $subexpr =~ s/\n\t/\n\t\t/g;
1803 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1804 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1805 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1807 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1808 $self->{ScopeThisXSUB} = 1;
1810 if (defined($self->{defaults}->{$var})) {
1811 $expr =~ s/(\t+)/$1 /g;
1813 if ($printed_name) {
1817 eval qq/print "\\t$var;\\n"/;
1820 if ($self->{defaults}->{$var} eq 'NO_INIT') {
1821 $self->{deferred} .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1824 $self->{deferred} .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1828 elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
1829 if ($printed_name) {
1833 eval qq/print "\\t$var;\\n"/;
1836 $self->{deferred} .= eval qq/"\\n$expr;\\n"/;
1840 die "panic: do not know how to handle this branch for function pointers"
1842 eval qq/print "$expr;\\n"/;
1847 sub generate_output {
1848 my $argsref = shift;
1849 my ($type, $num, $var, $do_setmagic, $do_push) = (
1853 $argsref->{do_setmagic},
1856 my $arg = "ST(" . ($num - ($num != 0)) . ")";
1859 $type = tidy_type($type);
1860 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1861 print "\t$arg = sv_newmortal();\n";
1862 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1863 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1866 blurt("Error: '$type' not in typemap"), return
1867 unless defined($self->{type_kind}->{$type});
1868 blurt("Error: No OUTPUT definition for type '$type', typekind '$self->{type_kind}->{$type}' found"), return
1869 unless defined $self->{output_expr}->{$self->{type_kind}->{$type}};
1870 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1871 $ntype =~ s/\(\)//g;
1873 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1874 my $expr = $self->{output_expr}->{$self->{type_kind}->{$type}};
1875 if ($expr =~ /DO_ARRAY_ELEM/) {
1876 blurt("Error: '$subtype' not in typemap"), return
1877 unless defined($self->{type_kind}->{$subtype});
1878 blurt("Error: No OUTPUT definition for type '$subtype', typekind '$self->{type_kind}->{$subtype}' found"), return
1879 unless defined $self->{output_expr}->{$self->{type_kind}->{$subtype}};
1880 my $subexpr = $self->{output_expr}->{$self->{type_kind}->{$subtype}};
1881 $subexpr =~ s/ntype/subtype/g;
1882 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1883 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1884 $subexpr =~ s/\n\t/\n\t\t/g;
1885 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1886 eval "print qq\a$expr\a";
1888 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1890 elsif ($var eq 'RETVAL') {
1891 if ($expr =~ /^\t\$arg = new/) {
1892 # We expect that $arg has refcnt 1, so we need to
1894 eval "print qq\a$expr\a";
1896 print "\tsv_2mortal(ST($num));\n";
1897 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1899 elsif ($expr =~ /^\s*\$arg\s*=/) {
1900 # We expect that $arg has refcnt >=1, so we need
1902 eval "print qq\a$expr\a";
1904 print "\tsv_2mortal(ST(0));\n";
1905 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1908 # Just hope that the entry would safely write it
1909 # over an already mortalized value. By
1910 # coincidence, something like $arg = &sv_undef
1912 print "\tST(0) = sv_newmortal();\n";
1913 eval "print qq\a$expr\a";
1915 # new mortals don't have set magic
1919 print "\tPUSHs(sv_newmortal());\n";
1921 eval "print qq\a$expr\a";
1923 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1925 elsif ($arg =~ /^ST\(\d+\)$/) {
1926 eval "print qq\a$expr\a";
1928 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1934 # work out the line number
1935 my $warn_line_number = $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1];
1937 print STDERR "@_ in $self->{filename}, line $warn_line_number\n";