1 package ExtUtils::ParseXS;
15 require ExtUtils::ParseXS::Constants; ExtUtils::ParseXS::Constants->VERSION($VERSION);
16 require ExtUtils::ParseXS::CountLines; ExtUtils::ParseXS::CountLines->VERSION($VERSION);
17 require ExtUtils::ParseXS::Utilities; ExtUtils::ParseXS::Utilities->VERSION($VERSION);
18 require ExtUtils::ParseXS::Eval; ExtUtils::ParseXS::Eval->VERSION($VERSION);
20 $VERSION = eval $VERSION if $VERSION =~ /_/;
22 use ExtUtils::ParseXS::Utilities qw(
23 standard_typemap_locations
31 analyze_preprocessor_statements
37 check_conditional_preprocessor_statements
38 escape_file_for_line_directive
39 report_typemap_failure
48 ##############################
49 # A number of "constants"
51 our ($C_group_rex, $C_arg);
52 # Group in C (no support for comments or literals)
53 $C_group_rex = qr/ [({\[]
54 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
56 # Chunk in C without comma at toplevel (no comments):
57 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
58 | (??{ $C_group_rex })
62 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
65 # "impossible" keyword (multiple newline)
66 my $END = "!End!\n\n";
68 my $BLOCK_regexp = '\s*(' . $ExtUtils::ParseXS::Constants::XSKeywordsAlternation . "|$END)\\s*:";
73 return bless {} => shift;
76 our $Singleton = __PACKAGE__->new;
80 # Allow for $package->process_file(%hash), $obj->process_file, and process_file()
83 $self = ref($invocant) ? $invocant : $invocant->new;
90 $self->{ProtoUsed} = exists $options{prototypes};
105 FH => Symbol::gensym(),
108 $args{except} = $args{except} ? ' TRY' : '';
112 my ($Is_VMS, $SymSet);
115 # Establish set of global symbols with max length 28, since xsubpp
116 # will later add the 'XS_' prefix.
117 require ExtUtils::XSSymSet;
118 $SymSet = ExtUtils::XSSymSet->new(28);
120 @{ $self->{XSStack} } = ({type => 'none'});
121 $self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ];
122 $self->{Overload} = 0; # bool
123 $self->{errors} = 0; # count
124 $self->{Fallback} = '&PL_sv_undef';
126 # Most of the 1500 lines below uses these globals. We'll have to
127 # clean this up sometime, probably. For now, we just pull them out
130 $self->{RetainCplusplusHierarchicalTypes} = $args{hiertype};
131 $self->{WantPrototypes} = $args{prototypes};
132 $self->{WantVersionChk} = $args{versioncheck};
133 $self->{WantLineNumbers} = $args{linenumbers};
134 $self->{IncludedFiles} = {};
136 die "Missing required parameter 'filename'" unless $args{filename};
137 $self->{filepathname} = $args{filename};
138 ($self->{dir}, $self->{filename}) =
139 (dirname($args{filename}), basename($args{filename}));
140 $self->{filepathname} =~ s/\\/\\\\/g;
141 $self->{IncludedFiles}->{$args{filename}}++;
143 # Open the output file if given as a string. If they provide some
144 # other kind of reference, trust them that we can print to it.
145 if (not ref $args{output}) {
146 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
147 $args{outfile} = $args{output};
151 # Really, we shouldn't have to chdir() or select() in the first
152 # place. For now, just save and restore.
153 my $orig_cwd = cwd();
154 my $orig_fh = select();
158 my $csuffix = $args{csuffix};
160 if ($self->{WantLineNumbers}) {
162 if ( $args{outfile} ) {
163 $cfile = $args{outfile};
166 $cfile = $args{filename};
167 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
169 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
170 select PSEUDO_STDOUT;
173 select $args{output};
176 $self->{typemap} = process_typemaps( $args{typemap}, $pwd );
178 # Move more settings from parameters to object
179 foreach my $datum ( qw| argtypes except inout optimize | ) {
180 $self->{$datum} = $args{$datum};
182 $self->{strip_c_func_prefix} = $args{s};
184 # Identify the version of xsubpp used
187 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
188 * contents of $self->{filename}. Do not edit this file, edit $self->{filename} instead.
190 * ANY CHANGES MADE HERE WILL BE LOST!
197 print("#line 1 \"" . escape_file_for_line_directive($self->{filepathname}) . "\"\n")
198 if $self->{WantLineNumbers};
200 # Open the input file (using $self->{filename} which
201 # is a basename'd $args{filename} due to chdir above)
202 open($self->{FH}, '<', $self->{filename}) or die "cannot open $self->{filename}: $!\n";
205 while (readline($self->{FH})) {
207 my $podstartline = $.;
210 # We can't just write out a /* */ comment, as our embedded
211 # POD might itself be in a comment. We can't put a /**/
212 # comment inside #if 0, as the C standard says that the source
213 # file is decomposed into preprocessing characters in the stage
214 # before preprocessing commands are executed.
215 # I don't want to leave the text as barewords, because the spec
216 # isn't clear whether macros are expanded before or after
217 # preprocessing commands are executed, and someone pathological
218 # may just have defined one of the 3 words as a macro that does
219 # something strange. Multiline strings are illegal in C, so
220 # the "" we write must be a string literal. And they aren't
221 # concatenated until 2 steps later, so we are safe.
223 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
224 printf("#line %d \"%s\"\n", $. + 1, escape_file_for_line_directive($self->{filepathname}))
225 if $self->{WantLineNumbers};
229 } while (readline($self->{FH}));
230 # At this point $. is at end of file so die won't state the start
231 # of the problem, and as we haven't yet read any lines &death won't
232 # show the correct line in the message either.
233 die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n")
234 unless $self->{lastline};
236 last if ($self->{Package}, $self->{Prefix}) =
237 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
241 unless (defined $_) {
242 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
243 exit 0; # Not a fatal error for the caller process
246 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
250 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
252 $self->{lastline} = $_;
253 $self->{lastline_no} = $.;
255 my $BootCode_ref = [];
256 my $XSS_work_idx = 0;
257 my $cpp_next_tmp = 'XSubPPtmpAAAA';
259 while ($self->fetch_para()) {
260 my $outlist_ref = [];
261 # Print initial preprocessor statements and blank lines
262 while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) {
263 my $ln = shift(@{ $self->{line} });
265 next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
267 ( $self, $XSS_work_idx, $BootCode_ref ) =
268 analyze_preprocessor_statements(
269 $self, $statement, $XSS_work_idx, $BootCode_ref
273 next PARAGRAPH unless @{ $self->{line} };
275 if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) {
276 # We are inside an #if, but have not yet #defined its xsubpp variable.
277 print "#define $cpp_next_tmp 1\n\n";
278 push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n");
279 push(@{ $BootCode_ref }, "#if $cpp_next_tmp");
280 $self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++;
284 "Code is not inside a function"
285 ." (maybe last function was ended by a blank line "
286 ." followed by a statement on column one?)")
287 if $self->{line}->[0] =~ /^\s/;
289 # initialize info arrays
290 foreach my $member (qw(args_match var_types defaults arg_list
291 argtype_seen in_out lengthof))
293 $self->{$member} = {};
295 $self->{proto_arg} = [];
296 $self->{processing_arg_with_types} = 0; # bool
297 $self->{proto_in_this_xsub} = 0; # counter & bool
298 $self->{scope_in_this_xsub} = 0; # counter & bool
299 $self->{interface} = 0; # bool
300 $self->{interface_macro} = 'XSINTERFACE_FUNC';
301 $self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET';
302 $self->{ProtoThisXSUB} = $self->{WantPrototypes}; # states 0 (none), 1 (yes), 2 (empty prototype)
303 $self->{ScopeThisXSUB} = 0; # bool
307 $_ = shift(@{ $self->{line} });
308 while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|EXPORT_XSUB_SYMBOLS|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
309 my $method = $kwd . "_handler";
311 next PARAGRAPH unless @{ $self->{line} };
312 $_ = shift(@{ $self->{line} });
315 if ($self->check_keyword("BOOT")) {
316 check_conditional_preprocessor_statements($self);
317 push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \""
318 . escape_file_for_line_directive($self->{filepathname}) . "\"")
319 if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/;
320 push (@{ $BootCode_ref }, @{ $self->{line} }, "");
324 # extract return type, function name and arguments
325 ($self->{ret_type}) = ExtUtils::Typemaps::tidy_type($_);
326 my $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//;
328 # Allow one-line ANSI-like declaration
329 unshift @{ $self->{line} }, $2
331 and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
333 # a function definition needs at least 2 lines
334 $self->blurt("Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH
335 unless @{ $self->{line} };
337 my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
338 my $static = 1 if $self->{ret_type} =~ s/^static\s+//;
340 my $func_header = shift(@{ $self->{line} });
341 $self->blurt("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
342 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
344 my ($class, $orig_args);
345 ($class, $self->{func_name}, $orig_args) = ($1, $2, $3);
346 $class = "$4 $class" if $4;
347 ($self->{pname} = $self->{func_name}) =~ s/^($self->{Prefix})?/$self->{Packprefix}/;
349 ($clean_func_name = $self->{func_name}) =~ s/^$self->{Prefix}//;
350 $self->{Full_func_name} = "$self->{Packid}_$clean_func_name";
352 $self->{Full_func_name} = $SymSet->addsym( $self->{Full_func_name} );
355 # Check for duplicate function definition
356 for my $tmp (@{ $self->{XSStack} }) {
357 next unless defined $tmp->{functions}{ $self->{Full_func_name} };
358 Warn( $self, "Warning: duplicate function definition '$clean_func_name' detected");
361 $self->{XSStack}->[$XSS_work_idx]{functions}{ $self->{Full_func_name} }++;
362 delete $self->{XsubAliases};
363 delete $self->{XsubAliasValues};
364 %{ $self->{Interfaces} } = ();
365 @{ $self->{Attributes} } = ();
366 $self->{DoSetMagic} = 1;
368 $orig_args =~ s/\\\s*/ /g; # process line continuations
371 my (@fake_INPUT_pre); # For length(s) generated variables
373 my $only_C_inlist_ref = {}; # Not in the signature of Perl function
374 if ($self->{argtypes} and $orig_args =~ /\S/) {
375 my $args = "$orig_args ,";
377 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
378 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
383 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
384 my ($pre, $len_name) = ($arg =~ /(.*?) \s*
385 \b ( \w+ | length\( \s*\w+\s* \) )
387 next unless defined($pre) && length($pre);
390 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
392 $out_type = $type if $type ne 'IN';
393 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
394 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
397 if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
398 $len_name = "XSauto_length_of_$1";
400 die "Default value on length() argument: '$_'"
403 if (length $pre or $islength) { # Has a type
405 push @fake_INPUT_pre, $arg;
408 push @fake_INPUT, $arg;
410 # warn "pushing '$arg'\n";
411 $self->{argtype_seen}->{$len_name}++;
412 $_ = "$len_name$default"; # Assigns to @args
414 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST" or $islength;
415 push @{ $outlist_ref }, $len_name if $out_type =~ /OUTLIST$/;
416 $self->{in_out}->{$len_name} = $out_type if $out_type;
421 @args = split(/\s*,\s*/, $orig_args);
422 Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split");
426 @args = split(/\s*,\s*/, $orig_args);
428 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
430 next if $out_type eq 'IN';
431 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST";
432 if ($out_type =~ /OUTLIST$/) {
433 push @{ $outlist_ref }, undef;
435 $self->{in_out}->{$_} = $out_type;
439 if (defined($class)) {
440 my $arg0 = ((defined($static) or $self->{func_name} eq 'new')
442 unshift(@args, $arg0);
447 my $report_args = '';
449 foreach my $i (0 .. $#args) {
450 if ($args[$i] =~ s/\.\.\.//) {
452 if ($args[$i] eq '' && $i == $#args) {
453 $report_args .= ", ...";
458 if ($only_C_inlist_ref->{$args[$i]}) {
459 push @args_num, undef;
462 push @args_num, ++$num_args;
463 $report_args .= ", $args[$i]";
465 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
468 $self->{defaults}->{$args[$i]} = $2;
469 $self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
471 $self->{proto_arg}->[$i+1] = '$' unless $only_C_inlist_ref->{$args[$i]};
473 my $min_args = $num_args - $extra_args;
474 $report_args =~ s/"/\\"/g;
475 $report_args =~ s/^,\s+//;
476 $self->{func_args} = assign_func_args($self, \@args, $class);
477 @{ $self->{args_match} }{@args} = @args_num;
479 my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} });
480 my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} });
481 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
482 # to set explicit return values.
483 my $EXPLICIT_RETURN = ($CODE &&
484 ("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
486 $self->{ALIAS} = grep(/^\s*ALIAS\s*:/, @{ $self->{line} });
488 my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @{ $self->{line} });
490 $xsreturn = 1 if $EXPLICIT_RETURN;
492 $externC = $externC ? qq[extern "C"] : "";
494 # print function header
497 #XS_EUPXS(XS_$self->{Full_func_name}); /* prototype to pass -Wmissing-prototypes */
498 #XS_EUPXS(XS_$self->{Full_func_name})
502 print Q(<<"EOF") if $self->{ALIAS};
505 print Q(<<"EOF") if $INTERFACE;
506 # dXSFUNCTION($self->{ret_type});
509 $self->{cond} = set_cond($ellipsis, $min_args, $num_args);
511 print Q(<<"EOF") if $self->{except};
519 # croak_xs_usage(cv, "$report_args");
523 # cv and items likely to be unused
525 # PERL_UNUSED_VAR(cv); /* -W */
526 # PERL_UNUSED_VAR(items); /* -W */
530 #gcc -Wall: if an xsub has PPCODE is used
531 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
532 #hence 'ax' (setup by dXSARGS) is unused
533 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
534 #but such a move could break third-party extensions
535 print Q(<<"EOF") if $PPCODE;
536 # PERL_UNUSED_VAR(ax); /* -Wall */
539 print Q(<<"EOF") if $PPCODE;
543 # Now do a block of some sort.
545 $self->{condnum} = 0;
546 $self->{cond} = ''; # last CASE: conditional
547 push(@{ $self->{line} }, "$END:");
548 push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
550 check_conditional_preprocessor_statements();
551 while (@{ $self->{line} }) {
553 $self->CASE_handler($_) if $self->check_keyword("CASE");
558 # do initialization of input variables
559 $self->{thisdone} = 0;
560 $self->{retvaldone} = 0;
561 $self->{deferred} = "";
562 %{ $self->{arg_list} } = ();
563 $self->{gotRETVAL} = 0;
564 $self->INPUT_handler($_);
565 $self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
567 print Q(<<"EOF") if $self->{ScopeThisXSUB};
572 if (!$self->{thisdone} && defined($class)) {
573 if (defined($static) or $self->{func_name} eq 'new') {
575 $self->{var_types}->{"CLASS"} = "char *";
576 $self->generate_init( {
580 printed_name => undef,
584 print "\t" . map_type($self, "$class *");
585 $self->{var_types}->{"THIS"} = "$class *";
586 $self->generate_init( {
590 printed_name => undef,
595 # These are set if OUTPUT is found and/or CODE using RETVAL
596 $self->{have_OUTPUT} = $self->{have_CODE_with_RETVAL} = 0;
600 if (/^\s*NOT_IMPLEMENTED_YET/) {
601 print "\n\tPerl_croak(aTHX_ \"$self->{pname}: not implemented yet\");\n";
605 if ($self->{ret_type} ne "void") {
606 print "\t" . map_type($self, $self->{ret_type}, 'RETVAL') . ";\n"
607 if !$self->{retvaldone};
608 $self->{args_match}->{"RETVAL"} = 0;
609 $self->{var_types}->{"RETVAL"} = $self->{ret_type};
610 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
612 if $self->{optimize} and $outputmap and $outputmap->targetable;
615 if (@fake_INPUT or @fake_INPUT_pre) {
616 unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
618 $self->{processing_arg_with_types} = 1;
619 $self->INPUT_handler($_);
621 print $self->{deferred};
623 $self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
625 if ($self->check_keyword("PPCODE")) {
626 $self->print_section();
627 $self->death("PPCODE must be last thing") if @{ $self->{line} };
628 print "\tLEAVE;\n" if $self->{ScopeThisXSUB};
629 print "\tPUTBACK;\n\treturn;\n";
631 elsif ($self->check_keyword("CODE")) {
632 my $consumed_code = $self->print_section();
633 if ($consumed_code =~ /\bRETVAL\b/) {
634 $self->{have_CODE_with_RETVAL} = 1;
637 elsif (defined($class) and $self->{func_name} eq "DESTROY") {
639 print "delete THIS;\n";
643 if ($self->{ret_type} ne "void") {
647 if (defined($static)) {
648 if ($self->{func_name} eq 'new') {
649 $self->{func_name} = "$class";
655 elsif (defined($class)) {
656 if ($self->{func_name} eq 'new') {
657 $self->{func_name} .= " $class";
663 my $strip = $self->{strip_c_func_prefix};
664 $self->{func_name} =~ s/^\Q$strip//
666 $self->{func_name} = 'XSFUNCTION' if $self->{interface};
667 print "$self->{func_name}($self->{func_args});\n";
671 # do output variables
672 $self->{gotRETVAL} = 0; # 1 if RETVAL seen in OUTPUT section;
673 undef $self->{RETVAL_code} ; # code to set RETVAL (from OUTPUT section);
674 # $wantRETVAL set if 'RETVAL =' autogenerated
675 ($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return;
676 undef %{ $self->{outargs} };
678 $self->process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
680 # A CODE section with RETVAL, but no OUTPUT? FAIL!
681 if ($self->{have_CODE_with_RETVAL} and not $self->{have_OUTPUT} and $self->{ret_type} ne 'void') {
682 $self->Warn("Warning: Found a 'CODE' section which seems to be using 'RETVAL' but no 'OUTPUT' section.");
685 $self->generate_output( {
686 type => $self->{var_types}->{$_},
687 num => $self->{args_match}->{$_},
689 do_setmagic => $self->{DoSetMagic},
691 } ) for grep $self->{in_out}->{$_} =~ /OUT$/, sort keys %{ $self->{in_out} };
694 # all OUTPUT done, so now push the return value on the stack
695 if ($self->{gotRETVAL} && $self->{RETVAL_code}) {
696 print "\t$self->{RETVAL_code}\n";
698 elsif ($self->{gotRETVAL} || $wantRETVAL) {
699 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
700 my $trgt = $self->{optimize} && $outputmap && $outputmap->targetable;
702 my $type = $self->{ret_type};
705 my $what = $self->eval_output_typemap_code(
707 {var => $var, type => $self->{ret_type}}
709 if (not $trgt->{with_size} and $trgt->{type} eq 'p') { # sv_setpv
710 # PUSHp corresponds to sv_setpvn. Treat sv_setpv directly
711 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
715 my $tsize = $trgt->{what_size};
716 $tsize = '' unless defined $tsize;
717 $tsize = $self->eval_output_typemap_code(
719 {var => $var, type => $self->{ret_type}}
721 print "\tXSprePUSH; PUSH$trgt->{type}($what$tsize);\n";
726 # RETVAL almost never needs SvSETMAGIC()
727 $self->generate_output( {
728 type => $self->{ret_type},
737 $xsreturn = 1 if $self->{ret_type} ne "void";
739 my $c = @{ $outlist_ref };
740 print "\tXSprePUSH;" if $c and not $prepush_done;
741 print "\tEXTEND(SP,$c);\n" if $c;
743 $self->generate_output( {
744 type => $self->{var_types}->{$_},
749 } ) for @{ $outlist_ref };
752 $self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
754 print Q(<<"EOF") if $self->{ScopeThisXSUB};
757 print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
761 # print function trailer
765 print Q(<<"EOF") if $self->{except};
768 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
771 if ($self->check_keyword("CASE")) {
772 $self->blurt("Error: No 'CASE:' at top of function")
773 unless $self->{condnum};
774 $_ = "CASE: $_"; # Restore CASE: label
777 last if $_ eq "$END:";
778 $self->death(/^$BLOCK_regexp/o ? "Misplaced '$1:'" : "Junk at end of function ($_)");
781 print Q(<<"EOF") if $self->{except};
783 # Perl_croak(aTHX_ errbuf);
787 print Q(<<"EOF") unless $PPCODE;
788 # XSRETURN($xsreturn);
792 print Q(<<"EOF") unless $PPCODE;
803 unless($self->{ProtoThisXSUB}) {
804 $self->{newXS} = "newXS_deffile";
808 # Build the prototype string for the xsub
809 $self->{newXS} = "newXSproto_portable";
810 $self->{file} = ", file";
812 if ($self->{ProtoThisXSUB} eq 2) {
813 # User has specified empty prototype
815 elsif ($self->{ProtoThisXSUB} eq 1) {
817 if ($min_args < $num_args) {
819 $self->{proto_arg}->[$min_args] .= ";";
821 push @{ $self->{proto_arg} }, "$s\@"
824 $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
827 # User has specified a prototype
828 $self->{proto} = $self->{ProtoThisXSUB};
830 $self->{proto} = qq{, "$self->{proto}"};
833 if ($self->{XsubAliases} and keys %{ $self->{XsubAliases} }) {
834 $self->{XsubAliases}->{ $self->{pname} } = 0
835 unless defined $self->{XsubAliases}->{ $self->{pname} };
836 foreach my $xname (sort keys %{ $self->{XsubAliases} }) {
837 my $value = $self->{XsubAliases}{$xname};
838 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
839 # cv = $self->{newXS}(\"$xname\", XS_$self->{Full_func_name}$self->{file}$self->{proto});
840 # XSANY.any_i32 = $value;
844 elsif (@{ $self->{Attributes} }) {
845 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
846 # cv = $self->{newXS}(\"$self->{pname}\", XS_$self->{Full_func_name}$self->{file}$self->{proto});
847 # apply_attrs_string("$self->{Package}", cv, "@{ $self->{Attributes} }", 0);
850 elsif ($self->{interface}) {
851 foreach my $yname (sort keys %{ $self->{Interfaces} }) {
852 my $value = $self->{Interfaces}{$yname};
853 $yname = "$self->{Package}\::$yname" unless $yname =~ /::/;
854 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
855 # cv = $self->{newXS}(\"$yname\", XS_$self->{Full_func_name}$self->{file}$self->{proto});
856 # $self->{interface_macro_set}(cv,$value);
860 elsif($self->{newXS} eq 'newXS_deffile'){ # work around P5NCI's empty newXS macro
861 push(@{ $self->{InitFileCode} },
862 " $self->{newXS}(\"$self->{pname}\", XS_$self->{Full_func_name}$self->{file}$self->{proto});\n");
865 push(@{ $self->{InitFileCode} },
866 " (void)$self->{newXS}(\"$self->{pname}\", XS_$self->{Full_func_name}$self->{file}$self->{proto});\n");
868 } # END 'PARAGRAPH' 'while' loop
870 if ($self->{Overload}) { # make it findable with fetchmethod
872 #XS_EUPXS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */
873 #XS_EUPXS(XS_$self->{Packid}_nil)
876 # PERL_UNUSED_VAR(items);
881 unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK");
882 /* Making a sub named "$self->{Package}::()" allows the package */
883 /* to be findable via fetchmethod(), and causes */
884 /* overload::Overloaded("$self->{Package}") to return true. */
885 (void)$self->{newXS}("$self->{Package}::()", XS_$self->{Packid}_nil$self->{file}$self->{proto});
886 MAKE_FETCHMETHOD_WORK
889 # print initialization routine
898 #XS_EXTERNAL(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
899 #XS_EXTERNAL(boot_$self->{Module_cname})
901 ##if PERL_VERSION_LE(5, 21, 5)
904 # dVAR; ${\($self->{WantVersionChk} ?
905 'dXSBOOTARGSXSAPIVERCHK;' : 'dXSBOOTARGSAPIVERCHK;')}
909 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
910 #file name argument. If the wrong qualifier is used, it causes breakage with
911 #C++ compilers and warnings with recent gcc.
912 #-Wall: if there is no $self->{Full_func_name} there are no xsubs in this .xs
914 print Q(<<"EOF") if $self->{Full_func_name};
915 ##if PERL_VERSION_LT(5, 9, 0)
916 # char* file = __FILE__;
918 # const char* file = __FILE__;
921 # PERL_UNUSED_VAR(file);
927 # PERL_UNUSED_VAR(cv); /* -W */
928 # PERL_UNUSED_VAR(items); /* -W */
931 if( $self->{WantVersionChk}){
933 ##if PERL_VERSION_LE(5, 21, 5)
934 # XS_VERSION_BOOTCHECK;
935 ## ifdef XS_APIVERSION_BOOTCHECK
936 # XS_APIVERSION_BOOTCHECK;
943 ##if PERL_VERSION_LE(5, 21, 5) && defined(XS_APIVERSION_BOOTCHECK)
944 # XS_APIVERSION_BOOTCHECK;
950 print Q(<<"EOF") if defined $self->{XsubAliases} or defined $self->{interfaces};
956 print Q(<<"EOF") if ($self->{Overload});
957 # /* register the overloading (type 'A') magic */
958 ##if PERL_VERSION_LT(5, 9, 0)
959 # PL_amagic_generation++;
961 # /* The magic for overload gets a GV* via gv_fetchmeth as */
962 # /* mentioned above, and looks in the SV* slot of it for */
963 # /* the "fallback" status. */
965 # get_sv( "$self->{Package}::()", TRUE ),
970 print @{ $self->{InitFileCode} };
972 print Q(<<"EOF") if defined $self->{XsubAliases} or defined $self->{interfaces};
976 if (@{ $BootCode_ref }) {
977 print "\n /* Initialisation Section */\n\n";
978 @{ $self->{line} } = @{ $BootCode_ref };
979 $self->print_section();
980 print "\n /* End of Initialisation Section */\n\n";
984 ##if PERL_VERSION_LE(5, 21, 5)
985 ## if PERL_VERSION_GE(5, 9, 0)
986 # if (PL_unitcheckav)
987 # call_list(PL_scopestack_ix, PL_unitcheckav);
991 # Perl_xs_boot_epilog(aTHX_ ax);
997 warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
998 unless $self->{ProtoUsed};
1002 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
1008 sub report_error_count {
1010 return $_[0]->{errors}||0;
1013 return $Singleton->{errors}||0;
1016 *errors = \&report_error_count;
1018 # Input: ($self, $_, @{ $self->{line} }) == unparsed input.
1019 # Output: ($_, @{ $self->{line} }) == (rest of line, following lines).
1020 # Return: the matched keyword if found, otherwise 0
1023 $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} };
1024 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1030 # the "do" is required for right semantics
1031 do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} };
1033 my $consumed_code = '';
1035 print("#line ", $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1], " \"",
1036 escape_file_for_line_directive($self->{filepathname}), "\"\n")
1037 if $self->{WantLineNumbers} && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1038 for (; defined($_) && !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1040 $consumed_code .= "$_\n";
1042 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
1044 return $consumed_code;
1051 while (!/\S/ && @{ $self->{line} }) {
1052 $_ = shift(@{ $self->{line} });
1055 for (; defined($_) && !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1062 sub process_keyword {
1063 my($self, $pattern) = @_;
1065 while (my $kwd = $self->check_keyword($pattern)) {
1066 my $method = $kwd . "_handler";
1074 $self->blurt("Error: 'CASE:' after unconditional 'CASE:'")
1075 if $self->{condnum} && $self->{cond} eq '';
1077 trim_whitespace($self->{cond});
1078 print " ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n");
1085 for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1086 last if /^\s*NOT_IMPLEMENTED_YET/;
1087 next unless /\S/; # skip blank lines
1089 trim_whitespace($_);
1092 # remove trailing semicolon if no initialisation
1093 s/\s*;$//g unless /[=;+].*\S/;
1095 # Process the length(foo) declarations
1096 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1097 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1098 $self->{lengthof}->{$2} = undef;
1099 $self->{deferred} .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1102 # check for optional initialisation code
1104 $var_init = $1 if s/\s*([=;+].*)$//s;
1105 $var_init =~ s/"/\\"/g;
1106 # *sigh* It's valid to supply explicit input typemaps in the argument list...
1107 my $is_overridden_typemap = $var_init =~ /ST\s*\(|\$arg\b/;
1110 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1111 or $self->blurt("Error: invalid argument declaration '$ln'"), next;
1113 # Check for duplicate definitions
1114 $self->blurt("Error: duplicate definition of argument '$var_name' ignored"), next
1115 if $self->{arg_list}->{$var_name}++
1116 or defined $self->{argtype_seen}->{$var_name} and not $self->{processing_arg_with_types};
1118 $self->{thisdone} |= $var_name eq "THIS";
1119 $self->{retvaldone} |= $var_name eq "RETVAL";
1120 $self->{var_types}->{$var_name} = $var_type;
1121 # XXXX This check is a safeguard against the unfinished conversion of
1122 # generate_init(). When generate_init() is fixed,
1123 # one can use 2-args map_type() unconditionally.
1125 if ($var_type =~ / \( \s* \* \s* \) /x) {
1126 # Function pointers are not yet supported with output_init()!
1127 print "\t" . map_type($self, $var_type, $var_name);
1131 print "\t" . map_type($self, $var_type, undef);
1134 $self->{var_num} = $self->{args_match}->{$var_name};
1136 if ($self->{var_num}) {
1137 my $typemap = $self->{typemap}->get_typemap(ctype => $var_type);
1138 $self->report_typemap_failure($self->{typemap}, $var_type, "death")
1139 if not $typemap and not $is_overridden_typemap;
1140 $self->{proto_arg}->[$self->{var_num}] = ($typemap && $typemap->proto) || "\$";
1142 $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr;
1143 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1144 or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/
1145 and $var_init !~ /\S/) {
1146 if ($printed_name) {
1150 print "\t$var_name;\n";
1153 elsif ($var_init =~ /\S/) {
1154 $self->output_init( {
1156 num => $self->{var_num},
1159 printed_name => $printed_name,
1162 elsif ($self->{var_num}) {
1163 $self->generate_init( {
1165 num => $self->{var_num},
1167 printed_name => $printed_name,
1176 sub OUTPUT_handler {
1178 $self->{have_OUTPUT} = 1;
1181 for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1183 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1184 $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
1187 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1188 $self->blurt("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1189 if $self->{outargs}->{$outarg}++;
1190 if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') {
1191 # deal with RETVAL last
1192 $self->{RETVAL_code} = $outcode;
1193 $self->{gotRETVAL} = 1;
1196 $self->blurt("Error: OUTPUT $outarg not an argument"), next
1197 unless defined($self->{args_match}->{$outarg});
1198 $self->blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1199 unless defined $self->{var_types}->{$outarg};
1200 $self->{var_num} = $self->{args_match}->{$outarg};
1202 print "\t$outcode\n";
1203 print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
1206 $self->generate_output( {
1207 type => $self->{var_types}->{$outarg},
1208 num => $self->{var_num},
1210 do_setmagic => $self->{DoSetMagic},
1214 delete $self->{in_out}->{$outarg} # No need to auto-OUTPUT
1215 if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
1219 sub C_ARGS_handler {
1222 my $in = $self->merge_section();
1224 trim_whitespace($in);
1225 $self->{func_args} = $in;
1228 sub INTERFACE_MACRO_handler {
1231 my $in = $self->merge_section();
1233 trim_whitespace($in);
1234 if ($in =~ /\s/) { # two
1235 ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
1238 $self->{interface_macro} = $in;
1239 $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
1241 $self->{interface} = 1; # local
1242 $self->{interfaces} = 1; # global
1245 sub INTERFACE_handler {
1248 my $in = $self->merge_section();
1250 trim_whitespace($in);
1252 foreach (split /[\s,]+/, $in) {
1253 my $iface_name = $_;
1254 $iface_name =~ s/^$self->{Prefix}//;
1255 $self->{Interfaces}->{$iface_name} = $_;
1258 # XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
1260 $self->{interface} = 1; # local
1261 $self->{interfaces} = 1; # global
1264 sub CLEANUP_handler {
1266 $self->print_section();
1269 sub PREINIT_handler {
1271 $self->print_section();
1274 sub POSTCALL_handler {
1276 $self->print_section();
1281 $self->print_section();
1289 # Parse alias definitions
1291 # alias = value alias = value ...
1293 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1294 my ($alias, $value) = ($1, $2);
1295 my $orig_alias = $alias;
1297 # check for optional package definition in the alias
1298 $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
1300 # check for duplicate alias name & duplicate value
1301 Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'")
1302 if defined $self->{XsubAliases}->{$alias};
1304 Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
1305 if $self->{XsubAliasValues}->{$value};
1307 $self->{XsubAliases}->{$alias} = $value;
1308 $self->{XsubAliasValues}->{$value} = $orig_alias;
1311 blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'")
1319 for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1321 trim_whitespace($_);
1322 push @{ $self->{Attributes} }, $_;
1330 for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1332 trim_whitespace($_);
1333 $self->get_aliases($_) if $_;
1337 sub OVERLOAD_handler {
1341 for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1343 trim_whitespace($_);
1344 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1345 $self->{Overload} = 1 unless $self->{Overload};
1346 my $overload = "$self->{Package}\::(".$1;
1347 push(@{ $self->{InitFileCode} },
1348 " (void)$self->{newXS}(\"$overload\", XS_$self->{Full_func_name}$self->{file}$self->{proto});\n");
1353 sub FALLBACK_handler {
1354 my ($self, $setting) = @_;
1356 # the rest of the current line should contain either TRUE,
1359 trim_whitespace($setting);
1360 $setting = uc($setting);
1363 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1364 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1365 UNDEF => "&PL_sv_undef",
1368 # check for valid FALLBACK value
1369 $self->death("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{$setting};
1371 $self->{Fallback} = $map{$setting};
1375 sub REQUIRE_handler {
1376 # the rest of the current line should contain a version number
1377 my ($self, $ver) = @_;
1379 trim_whitespace($ver);
1381 $self->death("Error: REQUIRE expects a version number")
1384 # check that the version number is of the form n.n
1385 $self->death("Error: REQUIRE: expected a number, got '$ver'")
1386 unless $ver =~ /^\d+(\.\d*)?/;
1388 $self->death("Error: xsubpp $ver (or better) required--this is only $VERSION.")
1389 unless $VERSION >= $ver;
1392 sub VERSIONCHECK_handler {
1393 # the rest of the current line should contain either ENABLE or
1395 my ($self, $setting) = @_;
1397 trim_whitespace($setting);
1399 # check for ENABLE/DISABLE
1400 $self->death("Error: VERSIONCHECK: ENABLE/DISABLE")
1401 unless $setting =~ /^(ENABLE|DISABLE)/i;
1403 $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1404 $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
1408 sub PROTOTYPE_handler {
1414 $self->death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1415 if $self->{proto_in_this_xsub}++;
1417 for (; !/^$BLOCK_regexp/o; $_ = shift(@{ $self->{line} })) {
1420 trim_whitespace($_);
1421 if ($_ eq 'DISABLE') {
1422 $self->{ProtoThisXSUB} = 0;
1424 elsif ($_ eq 'ENABLE') {
1425 $self->{ProtoThisXSUB} = 1;
1428 # remove any whitespace
1430 $self->death("Error: Invalid prototype '$_'")
1431 unless valid_proto_string($_);
1432 $self->{ProtoThisXSUB} = C_string($_);
1436 # If no prototype specified, then assume empty prototype ""
1437 $self->{ProtoThisXSUB} = 2 unless $specified;
1439 $self->{ProtoUsed} = 1;
1443 # Rest of line should be either ENABLE or DISABLE
1444 my ($self, $setting) = @_;
1446 $self->death("Error: Only 1 SCOPE declaration allowed per xsub")
1447 if $self->{scope_in_this_xsub}++;
1449 trim_whitespace($setting);
1450 $self->death("Error: SCOPE: ENABLE/DISABLE")
1451 unless $setting =~ /^(ENABLE|DISABLE)\b/i;
1452 $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
1455 sub PROTOTYPES_handler {
1456 # the rest of the current line should contain either ENABLE or
1458 my ($self, $setting) = @_;
1460 trim_whitespace($setting);
1462 # check for ENABLE/DISABLE
1463 $self->death("Error: PROTOTYPES: ENABLE/DISABLE")
1464 unless $setting =~ /^(ENABLE|DISABLE)/i;
1466 $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1467 $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
1468 $self->{ProtoUsed} = 1;
1471 sub EXPORT_XSUB_SYMBOLS_handler {
1472 # the rest of the current line should contain either ENABLE or
1474 my ($self, $setting) = @_;
1476 trim_whitespace($setting);
1478 # check for ENABLE/DISABLE
1479 $self->death("Error: EXPORT_XSUB_SYMBOLS: ENABLE/DISABLE")
1480 unless $setting =~ /^(ENABLE|DISABLE)/i;
1482 my $xs_impl = $1 eq 'ENABLE' ? 'XS_EXTERNAL' : 'XS_INTERNAL';
1486 ##if defined(PERL_EUPXS_ALWAYS_EXPORT)
1487 ## define XS_EUPXS(name) XS_EXTERNAL(name)
1488 ##elif defined(PERL_EUPXS_NEVER_EXPORT)
1489 ## define XS_EUPXS(name) XS_INTERNAL(name)
1491 ## define XS_EUPXS(name) $xs_impl(name)
1500 # Save the current file context.
1501 push(@{ $self->{XSStack} }, {
1503 LastLine => $self->{lastline},
1504 LastLineNo => $self->{lastline_no},
1505 Line => $self->{line},
1506 LineNo => $self->{line_no},
1507 Filename => $self->{filename},
1508 Filepathname => $self->{filepathname},
1509 Handle => $self->{FH},
1510 IsPipe => scalar($self->{filename} =~ /\|\s*$/),
1516 sub INCLUDE_handler {
1519 # the rest of the current line should contain a valid filename
1521 trim_whitespace($_);
1523 $self->death("INCLUDE: filename missing")
1526 $self->death("INCLUDE: output pipe is illegal")
1529 # simple minded recursion detector
1530 $self->death("INCLUDE loop detected")
1531 if $self->{IncludedFiles}->{$_};
1533 ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
1535 if (/\|\s*$/ && /^\s*perl\s/) {
1536 Warn( $self, "The INCLUDE directive with a command is discouraged." .
1537 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1538 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1539 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1540 " the use of \$^X as the currently running perl, see" .
1541 " 'perldoc perlxs' for details.");
1544 $self->PushXSStack();
1546 $self->{FH} = Symbol::gensym();
1549 open($self->{FH}, $_) or $self->death("Cannot open '$_': $!");
1553 #/* INCLUDE: Including '$_' from '$self->{filename}' */
1557 $self->{filename} = $_;
1558 $self->{filepathname} = ( $^O =~ /^mswin/i )
1559 ? qq($self->{dir}/$self->{filename}) # See CPAN RT #61908: gcc doesn't like backslashes on win32?
1560 : File::Spec->catfile($self->{dir}, $self->{filename});
1562 # Prime the pump by reading the first
1565 # skip leading blank lines
1566 while (readline($self->{FH})) {
1567 last unless /^\s*$/;
1570 $self->{lastline} = $_;
1571 $self->{lastline_no} = $.;
1576 my @args = split /\s+/, $cmd;
1579 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1581 return join (' ', ($cmd, @args));
1584 # code copied from CPAN::HandleConfig::safe_quote
1585 # - that has doc saying leave if start/finish with same quote, but no code
1586 # given text, will conditionally quote it to protect from shell
1588 my ($quote, $use_quote) = $^O eq 'MSWin32'
1592 my ($self, $command) = @_;
1593 # Set up quote/default quote
1594 if (defined($command)
1595 and $command =~ /\s/
1596 and $command !~ /[$quote]/) {
1597 return qq{$use_quote$command$use_quote}
1603 sub INCLUDE_COMMAND_handler {
1606 # the rest of the current line should contain a valid command
1608 trim_whitespace($_);
1610 $_ = QuoteArgs($_) if $^O eq 'VMS';
1612 $self->death("INCLUDE_COMMAND: command missing")
1615 $self->death("INCLUDE_COMMAND: pipes are illegal")
1616 if /^\s*\|/ or /\|\s*$/;
1618 $self->PushXSStack( IsPipe => 1 );
1620 $self->{FH} = Symbol::gensym();
1622 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1623 # the same perl interpreter as we're currently running
1624 my $X = $self->_safe_quote($^X); # quotes if has spaces
1628 open ($self->{FH}, "-|", $_)
1629 or $self->death( $self, "Cannot run command '$_' to include its output: $!");
1633 #/* INCLUDE_COMMAND: Including output of '$_' from '$self->{filename}' */
1637 $self->{filename} = $_;
1638 $self->{filepathname} = $self->{filename};
1639 #$self->{filepathname} =~ s/\"/\\"/g; # Fails? See CPAN RT #53938: MinGW Broken after 2.21
1640 $self->{filepathname} =~ s/\\/\\\\/g; # Works according to reporter of #53938
1642 # Prime the pump by reading the first
1645 # skip leading blank lines
1646 while (readline($self->{FH})) {
1647 last unless /^\s*$/;
1650 $self->{lastline} = $_;
1651 $self->{lastline_no} = $.;
1657 return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
1659 my $data = pop @{ $self->{XSStack} };
1660 my $ThisFile = $self->{filename};
1661 my $isPipe = $data->{IsPipe};
1663 --$self->{IncludedFiles}->{$self->{filename}}
1668 $self->{FH} = $data->{Handle};
1669 # $filename is the leafname, which for some reason is used for diagnostic
1670 # messages, whereas $filepathname is the full pathname, and is used for
1672 $self->{filename} = $data->{Filename};
1673 $self->{filepathname} = $data->{Filepathname};
1674 $self->{lastline} = $data->{LastLine};
1675 $self->{lastline_no} = $data->{LastLineNo};
1676 @{ $self->{line} } = @{ $data->{Line} };
1677 @{ $self->{line_no} } = @{ $data->{LineNo} };
1679 if ($isPipe and $? ) {
1680 --$self->{lastline_no};
1681 print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
1687 #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
1697 $text =~ s/\[\[/{/g;
1698 $text =~ s/\]\]/}/g;
1702 # Process "MODULE = Foo ..." lines and update global state accordingly
1703 sub _process_module_xs_line {
1704 my ($self, $module, $pkg, $prefix) = @_;
1706 ($self->{Module_cname} = $module) =~ s/\W/_/g;
1708 $self->{Package} = defined($pkg) ? $pkg : '';
1709 $self->{Prefix} = quotemeta( defined($prefix) ? $prefix : '' );
1711 ($self->{Packid} = $self->{Package}) =~ tr/:/_/;
1713 $self->{Packprefix} = $self->{Package};
1714 $self->{Packprefix} .= "::" if $self->{Packprefix} ne "";
1716 $self->{lastline} = "";
1719 # Skip any embedded POD sections
1720 sub _maybe_skip_pod {
1723 while ($self->{lastline} =~ /^=/) {
1724 while ($self->{lastline} = readline($self->{FH})) {
1725 last if ($self->{lastline} =~ /^=cut\s*$/);
1727 $self->death("Error: Unterminated pod") unless defined $self->{lastline};
1728 $self->{lastline} = readline($self->{FH});
1729 chomp $self->{lastline};
1730 $self->{lastline} =~ s/^\s+$//;
1734 # This chunk of code strips out (and parses) embedded TYPEMAP blocks
1735 # which support a HEREdoc-alike block syntax.
1736 sub _maybe_parse_typemap_block {
1739 # This is special cased from the usual paragraph-handler logic
1740 # due to the HEREdoc-ish syntax.
1741 if ($self->{lastline} =~ /^TYPEMAP\s*:\s*<<\s*(?:(["'])(.+?)\1|([^\s'"]+?))\s*;?\s*$/)
1743 my $end_marker = quotemeta(defined($1) ? $2 : $3);
1745 # Scan until we find $end_marker alone on a line.
1748 $self->{lastline} = readline($self->{FH});
1749 $self->death("Error: Unterminated TYPEMAP section") if not defined $self->{lastline};
1750 last if $self->{lastline} =~ /^$end_marker\s*$/;
1751 push @tmaplines, $self->{lastline};
1754 my $tmap = ExtUtils::Typemaps->new(
1755 string => join("", @tmaplines),
1756 lineno_offset => 1 + ($self->current_line_number() || 0),
1757 fake_filename => $self->{filename},
1759 $self->{typemap}->merge(typemap => $tmap, replace => 1);
1761 $self->{lastline} = "";
1765 # Read next xsub into @{ $self->{line} } from ($lastline, readline($self->{FH})).
1770 $self->death("Error: Unterminated '#if/#ifdef/#ifndef'")
1771 if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if';
1772 @{ $self->{line} } = ();
1773 @{ $self->{line_no} } = ();
1774 return $self->PopFile() if not defined $self->{lastline}; # EOF
1776 if ($self->{lastline} =~
1777 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/)
1779 $self->_process_module_xs_line($1, $2, $3);
1783 $self->_maybe_skip_pod;
1785 $self->_maybe_parse_typemap_block;
1787 if ($self->{lastline} !~ /^\s*#/ # not a CPP directive
1789 # ANSI: if ifdef ifndef elif else endif define undef
1791 # gcc: warning include_next
1793 # others: ident (gcc notes that some cpps have this one)
1794 || $self->{lastline} =~ /^\#[ \t]*
1796 (?:if|ifn?def|elif|else|endif|
1797 define|undef|pragma|error|
1798 warning|line\s+\d+|ident)
1800 | (?:include(?:_next)?|import)
1806 last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq "";
1807 push(@{ $self->{line} }, $self->{lastline});
1808 push(@{ $self->{line_no} }, $self->{lastline_no});
1811 # Read next line and continuation lines
1812 last unless defined($self->{lastline} = readline($self->{FH}));
1813 $self->{lastline_no} = $.;
1815 $self->{lastline} .= $tmp_line
1816 while ($self->{lastline} =~ /\\$/ && defined($tmp_line = readline($self->{FH})));
1818 chomp $self->{lastline};
1819 $self->{lastline} =~ s/^\s+$//;
1822 # Nuke trailing "line" entries until there's one that's not empty
1823 pop(@{ $self->{line} }), pop(@{ $self->{line_no} })
1824 while @{ $self->{line} } && $self->{line}->[-1] eq "";
1831 my $argsref = shift;
1833 my ($type, $num, $var, $init, $printed_name)
1834 = @{$argsref}{qw(type num var init printed_name)};
1836 # local assign for efficiently passing in to eval_input_typemap_code
1837 local $argsref->{arg} = $num
1838 ? "ST(" . ($num-1) . ")"
1839 : "/* not a parameter */";
1841 if ( $init =~ /^=/ ) {
1842 if ($printed_name) {
1843 $self->eval_input_typemap_code(qq/print " $init\\n"/, $argsref);
1846 $self->eval_input_typemap_code(qq/print "\\t$var $init\\n"/, $argsref);
1850 if ( $init =~ s/^\+// && $num ) {
1851 $self->generate_init( {
1855 printed_name => $printed_name,
1858 elsif ($printed_name) {
1863 $self->eval_input_typemap_code(qq/print "\\t$var;\\n"/, $argsref);
1867 .= $self->eval_input_typemap_code(qq/"\\n\\t$init\\n"/, $argsref);
1873 my $argsref = shift;
1875 my ($type, $num, $var, $printed_name)
1876 = @{$argsref}{qw(type num var printed_name)};
1878 my $argoff = $num - 1;
1879 my $arg = "ST($argoff)";
1881 my $typemaps = $self->{typemap};
1883 $type = ExtUtils::Typemaps::tidy_type($type);
1884 if (not $typemaps->get_typemap(ctype => $type)) {
1885 $self->report_typemap_failure($typemaps, $type);
1889 (my $ntype = $type) =~ s/\s*\*/Ptr/g;
1890 (my $subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1892 my $typem = $typemaps->get_typemap(ctype => $type);
1893 my $xstype = $typem->xstype;
1894 #this is an optimization from perl 5.0 alpha 6, class check is skipped
1895 #T_REF_IV_REF is missing since it has no untyped analog at the moment
1896 $xstype =~ s/OBJ$/REF/ || $xstype =~ s/^T_REF_IV_PTR$/T_PTRREF/
1897 if $self->{func_name} =~ /DESTROY$/;
1898 if ($xstype eq 'T_PV' and exists $self->{lengthof}->{$var}) {
1899 print "\t$var" unless $printed_name;
1900 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1901 die "default value not supported with length(NAME) supplied"
1902 if defined $self->{defaults}->{$var};
1905 $type =~ tr/:/_/ unless $self->{RetainCplusplusHierarchicalTypes};
1907 my $inputmap = $typemaps->get_inputmap(xstype => $xstype);
1908 if (not defined $inputmap) {
1909 $self->blurt("Error: No INPUT definition for type '$type', typekind '" . $type->xstype . "' found");
1913 my $expr = $inputmap->cleaned_code;
1914 # Note: This gruesome bit either needs heavy rethinking or documentation. I vote for the former. --Steffen
1915 if ($expr =~ /DO_ARRAY_ELEM/) {
1916 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1917 if (not $subtypemap) {
1918 $self->report_typemap_failure($typemaps, $subtype);
1922 my $subinputmap = $typemaps->get_inputmap(xstype => $subtypemap->xstype);
1923 if (not $subinputmap) {
1924 $self->blurt("Error: No INPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found");
1928 my $subexpr = $subinputmap->cleaned_code;
1929 $subexpr =~ s/\$type/\$subtype/g;
1930 $subexpr =~ s/ntype/subtype/g;
1931 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1932 $subexpr =~ s/\n\t/\n\t\t/g;
1933 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1934 $subexpr =~ s/\$var/${var}\[ix_$var - $argoff]/;
1935 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1937 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1938 $self->{ScopeThisXSUB} = 1;
1943 printed_name => $printed_name,
1946 subtype => $subtype,
1952 if (defined($self->{defaults}->{$var})) {
1953 $expr =~ s/(\t+)/$1 /g;
1955 if ($printed_name) {
1959 $self->eval_input_typemap_code(qq/print "\\t$var;\\n"/, $eval_vars);
1961 if ($self->{defaults}->{$var} eq 'NO_INIT') {
1962 $self->{deferred} .= $self->eval_input_typemap_code(
1963 qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/,
1968 $self->{deferred} .= $self->eval_input_typemap_code(
1969 qq/"\\n\\tif (items < $num)\\n\\t $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/,
1974 elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
1975 if ($printed_name) {
1979 $self->eval_input_typemap_code(qq/print "\\t$var;\\n"/, $eval_vars);
1982 .= $self->eval_input_typemap_code(qq/"\\n$expr;\\n"/, $eval_vars);
1985 die "panic: do not know how to handle this branch for function pointers"
1987 $self->eval_input_typemap_code(qq/print "$expr;\\n"/, $eval_vars);
1991 sub generate_output {
1993 my $argsref = shift;
1994 my ($type, $num, $var, $do_setmagic, $do_push)
1995 = @{$argsref}{qw(type num var do_setmagic do_push)};
1997 my $arg = "ST(" . ($num - ($num != 0)) . ")";
1999 my $typemaps = $self->{typemap};
2001 $type = ExtUtils::Typemaps::tidy_type($type);
2002 local $argsref->{type} = $type;
2004 if ($type =~ /^array\(([^,]*),(.*)\)/) {
2005 print "\t$arg = sv_newmortal();\n";
2006 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
2007 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
2010 my $typemap = $typemaps->get_typemap(ctype => $type);
2012 $self->report_typemap_failure($typemaps, $type);
2016 my $outputmap = $typemaps->get_outputmap(xstype => $typemap->xstype);
2017 if (not $outputmap) {
2018 $self->blurt("Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found");
2022 (my $ntype = $type) =~ s/\s*\*/Ptr/g;
2023 $ntype =~ s/\(\)//g;
2024 (my $subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
2026 my $eval_vars = {%$argsref, subtype => $subtype, ntype => $ntype, arg => $arg};
2027 my $expr = $outputmap->cleaned_code;
2028 if ($expr =~ /DO_ARRAY_ELEM/) {
2029 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
2030 if (not $subtypemap) {
2031 $self->report_typemap_failure($typemaps, $subtype);
2035 my $suboutputmap = $typemaps->get_outputmap(xstype => $subtypemap->xstype);
2036 if (not $suboutputmap) {
2037 $self->blurt("Error: No OUTPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found");
2041 my $subexpr = $suboutputmap->cleaned_code;
2042 $subexpr =~ s/ntype/subtype/g;
2043 $subexpr =~ s/\$arg/ST(ix_$var)/g;
2044 $subexpr =~ s/\$var/${var}\[ix_$var]/g;
2045 $subexpr =~ s/\n\t/\n\t\t/g;
2046 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
2047 $self->eval_output_typemap_code("print qq\a$expr\a", $eval_vars);
2048 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
2050 elsif ($var eq 'RETVAL') {
2051 my $orig_arg = $arg;
2053 my $use_RETVALSV = 1;
2055 my $do_copy_tmp = 1;
2057 local $eval_vars->{arg} = $arg = 'RETVALSV';
2058 my $evalexpr = $self->eval_output_typemap_code("qq\a$expr\a", $eval_vars);
2060 if ($expr =~ /^\t\Q$arg\E = new/) {
2061 # We expect that $arg has refcnt 1, so we need to
2065 # If RETVAL is immortal, don't mortalize it. This code is not perfect:
2066 # It won't detect a func or expression that only returns immortals, for
2067 # example, this RE must be tried before next elsif.
2068 elsif ($evalexpr =~ /^\t\Q$arg\E\s*=\s*(boolSV\(|(&PL_sv_yes|&PL_sv_no|&PL_sv_undef)\s*;)/) {
2069 $do_copy_tmp = 0; #$arg will be a ST(X), no SV* RETVAL, no RETVALSV
2072 elsif ($evalexpr =~ /^\s*\Q$arg\E\s*=/) {
2073 # We expect that $arg has refcnt >=1, so we need
2075 $use_RETVALSV = 0 if $ntype eq "SVPtr";#reuse SV* RETVAL vs open new block
2079 # Just hope that the entry would safely write it
2080 # over an already mortalized value. By
2081 # coincidence, something like $arg = &PL_sv_undef
2082 # works too, but should be caught above.
2083 $pre_expr = "RETVALSV = sv_newmortal();\n";
2084 # new mortals don't have set magic
2088 print "\t{\n\t SV * RETVALSV;\n";
2093 print $indent.$pre_expr if $pre_expr;
2096 #take control of 1 layer of indent, may or may not indent more
2097 $evalexpr =~ s/^(\t| )/$indent/gm;
2098 #"\t \t" doesn't draw right in some IDEs
2099 #break down all \t into spaces
2100 $evalexpr =~ s/\t/ /g;
2101 #rebuild back into \t'es, \t==8 spaces, indent==4 spaces
2102 $evalexpr =~ s/ /\t/g;
2105 if($do_mortal || $do_setmagic) {
2106 #typemap entry evaled with RETVALSV, if we aren't using RETVALSV replace
2107 $evalexpr =~ s/RETVALSV/RETVAL/g; #all uses with RETVAL for prettier code
2109 else { #if no extra boilerplate (no mortal, no set magic) is needed
2110 #after $evalexport, get rid of RETVALSV's visual cluter and change
2111 $evalexpr =~ s/RETVALSV/$orig_arg/g;#the lvalue to ST(X)
2114 #stop " RETVAL = RETVAL;" for SVPtr type
2115 print $evalexpr if $evalexpr !~ /^\s*RETVAL = RETVAL;$/;
2116 print $indent.'RETVAL'.($use_RETVALSV ? 'SV':'')
2117 .' = sv_2mortal(RETVAL'.($use_RETVALSV ? 'SV':'').");\n" if $do_mortal;
2118 print $indent.'SvSETMAGIC(RETVAL'.($use_RETVALSV ? 'SV':'').");\n" if $do_setmagic;
2119 #dont do "RETVALSV = boolSV(RETVAL); ST(0) = RETVALSV;", it is visual clutter
2120 print $indent."$orig_arg = RETVAL".($use_RETVALSV ? 'SV':'').";\n"
2121 if $do_mortal || $do_setmagic || $do_copy_tmp;
2122 print "\t}\n" if $use_RETVALSV;
2125 print "\tPUSHs(sv_newmortal());\n";
2126 local $eval_vars->{arg} = "ST($num)";
2127 $self->eval_output_typemap_code("print qq\a$expr\a", $eval_vars);
2128 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
2130 elsif ($arg =~ /^ST\(\d+\)$/) {
2131 $self->eval_output_typemap_code("print qq\a$expr\a", $eval_vars);
2132 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
2138 # Just delegates to a clean package.
2139 # Shim to evaluate Perl code in the right variable context
2140 # for typemap code (having things such as $ALIAS set up).
2141 sub eval_output_typemap_code {
2142 my ($self, $code, $other) = @_;
2143 return ExtUtils::ParseXS::Eval::eval_output_typemap_code($self, $code, $other);
2146 sub eval_input_typemap_code {
2147 my ($self, $code, $other) = @_;
2148 return ExtUtils::ParseXS::Eval::eval_input_typemap_code($self, $code, $other);
2153 # vim: ts=2 sw=2 et: