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 analyze_preprocessor_statements
29 check_conditional_preprocessor_statements
32 our @ISA = qw(Exporter);
38 $VERSION = eval $VERSION if $VERSION =~ /_/;
40 # The scalars in the line below remain as 'our' variables because pulling
41 # them into $self led to build problems. In most cases, strings being
42 # 'eval'-ed contain the variables' names hard-coded.
44 $FH, $Package, $func_name, $Full_func_name, $pname, $ALIAS,
47 our $self = bless {} => __PACKAGE__;
51 # Allow for $package->process_file(%hash) in the future
52 my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
54 $self->{ProtoUsed} = exists $options{prototypes};
71 $args{except} = $args{except} ? ' TRY' : '';
75 my ($Is_VMS, $SymSet);
78 # Establish set of global symbols with max length 28, since xsubpp
79 # will later add the 'XS_' prefix.
80 require ExtUtils::XSSymSet;
81 $SymSet = ExtUtils::XSSymSet->new(28);
83 @{ $self->{XSStack} } = ({type => 'none'});
84 $self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ];
85 $FH = $ExtUtils::ParseXS::Constants::FH;
86 $self->{Overload} = $ExtUtils::ParseXS::Constants::Overload;
87 $self->{errors} = $ExtUtils::ParseXS::Constants::errors;
88 $self->{Fallback} = $ExtUtils::ParseXS::Constants::Fallback;
90 # Most of the 1500 lines below uses these globals. We'll have to
91 # clean this up sometime, probably. For now, we just pull them out
94 $self->{hiertype} = $args{hiertype};
95 $self->{WantPrototypes} = $args{prototypes};
96 $self->{WantVersionChk} = $args{versioncheck};
97 $self->{WantLineNumbers} = $args{linenumbers};
98 $self->{IncludedFiles} = {};
100 die "Missing required parameter 'filename'" unless $args{filename};
101 $self->{filepathname} = $args{filename};
102 ($self->{dir}, $self->{filename}) =
103 (dirname($args{filename}), basename($args{filename}));
104 $self->{filepathname} =~ s/\\/\\\\/g;
105 $self->{IncludedFiles}->{$args{filename}}++;
107 # Open the output file if given as a string. If they provide some
108 # other kind of reference, trust them that we can print to it.
109 if (not ref $args{output}) {
110 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
111 $args{outfile} = $args{output};
115 # Really, we shouldn't have to chdir() or select() in the first
116 # place. For now, just save and restore.
117 my $orig_cwd = cwd();
118 my $orig_fh = select();
122 my $csuffix = $args{csuffix};
124 if ($self->{WantLineNumbers}) {
126 if ( $args{outfile} ) {
127 $cfile = $args{outfile};
130 $cfile = $args{filename};
131 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
133 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
134 select PSEUDO_STDOUT;
137 select $args{output};
140 $self->{typemap} = process_typemaps( $args{typemap}, $pwd );
142 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
144 # Match an XS keyword
145 $self->{BLOCK_re} = '\s*(' .
146 join('|' => @ExtUtils::ParseXS::Constants::XSKeywords) .
149 our ($C_group_rex, $C_arg);
150 # Group in C (no support for comments or literals)
151 $C_group_rex = qr/ [({\[]
152 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
154 # Chunk in C without comma at toplevel (no comments):
155 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
156 | (??{ $C_group_rex })
157 | " (?: (?> [^\\"]+ )
159 )* " # String literal
160 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
163 # Since at this point we're ready to begin printing to the output file and
164 # reading from the input file, I want to get as much data as possible into
165 # the proto-object $self. That means assigning to $self and elements of
166 # %args referenced below this point.
167 # HOWEVER: This resulted in an error when I tried:
168 # $args{'s'} ---> $self->{s}.
169 # Use of uninitialized value in quotemeta at
170 # .../blib/lib/ExtUtils/ParseXS.pm line 733
172 foreach my $datum ( qw| argtypes except inout optimize | ) {
173 $self->{$datum} = $args{$datum};
176 # Identify the version of xsubpp used
179 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
180 * contents of $self->{filename}. Do not edit this file, edit $self->{filename} instead.
182 * ANY CHANGES MADE HERE WILL BE LOST!
189 print("#line 1 \"$self->{filepathname}\"\n")
190 if $self->{WantLineNumbers};
192 # Open the input file (using $self->{filename} which
193 # is a basename'd $args{filename} due to chdir above)
194 open($FH, $self->{filename}) or die "cannot open $self->{filename}: $!\n";
199 my $podstartline = $.;
202 # We can't just write out a /* */ comment, as our embedded
203 # POD might itself be in a comment. We can't put a /**/
204 # comment inside #if 0, as the C standard says that the source
205 # file is decomposed into preprocessing characters in the stage
206 # before preprocessing commands are executed.
207 # I don't want to leave the text as barewords, because the spec
208 # isn't clear whether macros are expanded before or after
209 # preprocessing commands are executed, and someone pathological
210 # may just have defined one of the 3 words as a macro that does
211 # something strange. Multiline strings are illegal in C, so
212 # the "" we write must be a string literal. And they aren't
213 # concatenated until 2 steps later, so we are safe.
215 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
216 printf("#line %d \"$self->{filepathname}\"\n", $. + 1)
217 if $self->{WantLineNumbers};
222 # At this point $. is at end of file so die won't state the start
223 # of the problem, and as we haven't yet read any lines &death won't
224 # show the correct line in the message either.
225 die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n")
226 unless $self->{lastline};
228 last if ($Package, $self->{Prefix}) =
229 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
233 unless (defined $_) {
234 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
235 exit 0; # Not a fatal error for the caller process
238 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
242 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
244 $self->{lastline} = $_;
245 $self->{lastline_no} = $.;
247 my $BootCode_ref = [];
248 my $XSS_work_idx = 0;
249 my $cpp_next_tmp = 'XSubPPtmpAAAA';
251 while ($self->fetch_para()) {
252 my $outlist_ref = [];
253 # Print initial preprocessor statements and blank lines
254 while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) {
255 my $ln = shift(@{ $self->{line} });
257 next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
259 ( $self, $XSS_work_idx, $BootCode_ref ) =
260 analyze_preprocessor_statements(
261 $self, $statement, $XSS_work_idx, $BootCode_ref
265 next PARAGRAPH unless @{ $self->{line} };
267 if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) {
268 # We are inside an #if, but have not yet #defined its xsubpp variable.
269 print "#define $cpp_next_tmp 1\n\n";
270 push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n");
271 push(@{ $BootCode_ref }, "#if $cpp_next_tmp");
272 $self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++;
276 "Code is not inside a function"
277 ." (maybe last function was ended by a blank line "
278 ." followed by a statement on column one?)")
279 if $self->{line}->[0] =~ /^\s/;
281 # initialize info arrays
282 undef(%{ $self->{args_match} });
283 undef(%{ $self->{var_types} });
284 undef(%{ $self->{defaults} });
285 undef(%{ $self->{arg_list} });
286 undef(@{ $self->{proto_arg} });
287 undef($self->{processing_arg_with_types});
288 undef(%{ $self->{argtype_seen} });
289 undef(%{ $self->{in_out} });
290 undef(%{ $self->{lengthof} });
291 undef($self->{proto_in_this_xsub});
292 undef($self->{scope_in_this_xsub});
293 undef($self->{interface});
294 $self->{interface_macro} = 'XSINTERFACE_FUNC';
295 $self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET';
296 $self->{ProtoThisXSUB} = $self->{WantPrototypes};
297 $self->{ScopeThisXSUB} = 0;
300 $_ = shift(@{ $self->{line} });
301 while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
302 my $method = $kwd . "_handler";
304 next PARAGRAPH unless @{ $self->{line} };
305 $_ = shift(@{ $self->{line} });
308 if ($self->check_keyword("BOOT")) {
309 check_conditional_preprocessor_statements($self);
310 push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \"$self->{filepathname}\"")
311 if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/;
312 push (@{ $BootCode_ref }, @{ $self->{line} }, "");
316 # extract return type, function name and arguments
317 ($self->{ret_type}) = tidy_type($_);
318 my $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//;
320 # Allow one-line ANSI-like declaration
321 unshift @{ $self->{line} }, $2
323 and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
325 # a function definition needs at least 2 lines
326 blurt( $self, "Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH
327 unless @{ $self->{line} };
329 my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
330 my $static = 1 if $self->{ret_type} =~ s/^static\s+//;
332 my $func_header = shift(@{ $self->{line} });
333 blurt( $self, "Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
334 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
336 my ($class, $orig_args);
337 ($class, $func_name, $orig_args) = ($1, $2, $3);
338 $class = "$4 $class" if $4;
339 ($pname = $func_name) =~ s/^($self->{Prefix})?/$self->{Packprefix}/;
341 ($clean_func_name = $func_name) =~ s/^$self->{Prefix}//;
342 $Full_func_name = "$self->{Packid}_$clean_func_name";
344 $Full_func_name = $SymSet->addsym($Full_func_name);
347 # Check for duplicate function definition
348 for my $tmp (@{ $self->{XSStack} }) {
349 next unless defined $tmp->{functions}{$Full_func_name};
350 Warn( $self, "Warning: duplicate function definition '$clean_func_name' detected");
353 $self->{XSStack}->[$XSS_work_idx]{functions}{$Full_func_name}++;
354 %{ $self->{XsubAliases} } = ();
355 %{ $self->{XsubAliasValues} } = ();
356 %{ $self->{Interfaces} } = ();
357 @{ $self->{Attributes} } = ();
358 $self->{DoSetMagic} = 1;
360 $orig_args =~ s/\\\s*/ /g; # process line continuations
363 my (@fake_INPUT_pre); # For length(s) generated variables
365 my $only_C_inlist_ref = {}; # Not in the signature of Perl function
366 if ($self->{argtypes} and $orig_args =~ /\S/) {
367 my $args = "$orig_args ,";
368 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
369 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
373 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
374 my ($pre, $len_name) = ($arg =~ /(.*?) \s*
375 \b ( \w+ | length\( \s*\w+\s* \) )
377 next unless defined($pre) && length($pre);
380 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
382 $out_type = $type if $type ne 'IN';
383 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
384 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
387 if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
388 $len_name = "XSauto_length_of_$1";
390 die "Default value on length() argument: `$_'"
393 if (length $pre or $islength) { # Has a type
395 push @fake_INPUT_pre, $arg;
398 push @fake_INPUT, $arg;
400 # warn "pushing '$arg'\n";
401 $self->{argtype_seen}->{$len_name}++;
402 $_ = "$len_name$default"; # Assigns to @args
404 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST" or $islength;
405 push @{ $outlist_ref }, $len_name if $out_type =~ /OUTLIST$/;
406 $self->{in_out}->{$len_name} = $out_type if $out_type;
410 @args = split(/\s*,\s*/, $orig_args);
411 Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split");
415 @args = split(/\s*,\s*/, $orig_args);
417 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
419 next if $out_type eq 'IN';
420 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST";
421 if ($out_type =~ /OUTLIST$/) {
422 push @{ $outlist_ref }, undef;
424 $self->{in_out}->{$_} = $out_type;
428 if (defined($class)) {
429 my $arg0 = ((defined($static) or $func_name eq 'new')
431 unshift(@args, $arg0);
436 my $report_args = '';
438 foreach my $i (0 .. $#args) {
439 if ($args[$i] =~ s/\.\.\.//) {
441 if ($args[$i] eq '' && $i == $#args) {
442 $report_args .= ", ...";
447 if ($only_C_inlist_ref->{$args[$i]}) {
448 push @args_num, undef;
451 push @args_num, ++$num_args;
452 $report_args .= ", $args[$i]";
454 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
457 $self->{defaults}->{$args[$i]} = $2;
458 $self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
460 $self->{proto_arg}->[$i+1] = '$';
462 my $min_args = $num_args - $extra_args;
463 $report_args =~ s/"/\\"/g;
464 $report_args =~ s/^,\s+//;
465 $self->{func_args} = assign_func_args($self, \@args, $class);
466 @{ $self->{args_match} }{@args} = @args_num;
468 my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} });
469 my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} });
470 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
471 # to set explicit return values.
472 my $EXPLICIT_RETURN = ($CODE &&
473 ("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
475 # The $ALIAS which follows is only explicitly called within the scope of
476 # process_file(). In principle, it ought to be a lexical, i.e., 'my
477 # $ALIAS' like the other nearby variables. However, implementing that
478 # change produced a slight difference in the resulting .c output in at
479 # least two distributions: B/BD/BDFOY/Crypt-Rijndael and
480 # G/GF/GFUJI/Hash-FieldHash. The difference is, arguably, an improvement
481 # in the resulting C code. Example:
483 # < GvNAME(CvGV(cv)),
485 # > "Crypt::Rijndael::encrypt",
486 # But at this point we're committed to generating the *same* C code that
487 # the current version of ParseXS.pm does. So we're declaring it as 'our'.
488 $ALIAS = grep(/^\s*ALIAS\s*:/, @{ $self->{line} });
490 my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @{ $self->{line} });
492 $xsreturn = 1 if $EXPLICIT_RETURN;
494 $externC = $externC ? qq[extern "C"] : "";
496 # print function header
499 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
500 #XS(XS_${Full_func_name})
508 print Q(<<"EOF") if $ALIAS;
511 print Q(<<"EOF") if $INTERFACE;
512 # dXSFUNCTION($self->{ret_type});
515 $self->{cond} = set_cond($ellipsis, $min_args, $num_args);
517 print Q(<<"EOF") if $self->{except};
525 # croak_xs_usage(cv, "$report_args");
529 # cv likely to be unused
531 # PERL_UNUSED_VAR(cv); /* -W */
535 #gcc -Wall: if an xsub has PPCODE is used
536 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
537 #hence `ax' (setup by dXSARGS) is unused
538 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
539 #but such a move could break third-party extensions
540 print Q(<<"EOF") if $PPCODE;
541 # PERL_UNUSED_VAR(ax); /* -Wall */
544 print Q(<<"EOF") if $PPCODE;
548 # Now do a block of some sort.
550 $self->{condnum} = 0;
551 $self->{cond} = ''; # last CASE: conditional
552 push(@{ $self->{line} }, "$END:");
553 push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
555 $self->check_conditional_preprocessor_statements();
556 while (@{ $self->{line} }) {
557 $self->CASE_handler($_) if $self->check_keyword("CASE");
562 # do initialization of input variables
563 $self->{thisdone} = 0;
564 $self->{retvaldone} = 0;
565 $self->{deferred} = "";
566 %{ $self->{arg_list} } = ();
567 $self->{gotRETVAL} = 0;
569 $self->INPUT_handler($_);
570 $self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
572 print Q(<<"EOF") if $self->{ScopeThisXSUB};
577 if (!$self->{thisdone} && defined($class)) {
578 if (defined($static) or $func_name eq 'new') {
580 $self->{var_types}->{"CLASS"} = "char *";
585 printed_name => undef,
590 $self->{var_types}->{"THIS"} = "$class *";
595 printed_name => undef,
602 if (/^\s*NOT_IMPLEMENTED_YET/) {
603 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
607 if ($self->{ret_type} ne "void") {
608 print "\t" . map_type($self, $self->{ret_type}, 'RETVAL') . ";\n"
609 if !$self->{retvaldone};
610 $self->{args_match}->{"RETVAL"} = 0;
611 $self->{var_types}->{"RETVAL"} = $self->{ret_type};
612 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
614 if $self->{optimize} and $outputmap and $outputmap->targetable;
617 if (@fake_INPUT or @fake_INPUT_pre) {
618 unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
620 $self->{processing_arg_with_types} = 1;
621 $self->INPUT_handler($_);
623 print $self->{deferred};
625 $self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
627 if ($self->check_keyword("PPCODE")) {
628 $self->print_section();
629 death( $self, "PPCODE must be last thing") if @{ $self->{line} };
630 print "\tLEAVE;\n" if $self->{ScopeThisXSUB};
631 print "\tPUTBACK;\n\treturn;\n";
633 elsif ($self->check_keyword("CODE")) {
634 $self->print_section();
636 elsif (defined($class) and $func_name eq "DESTROY") {
638 print "delete THIS;\n";
642 if ($self->{ret_type} ne "void") {
646 if (defined($static)) {
647 if ($func_name eq 'new') {
648 $func_name = "$class";
654 elsif (defined($class)) {
655 if ($func_name eq 'new') {
656 $func_name .= " $class";
662 $func_name =~ s/^\Q$args{'s'}//
663 if exists $args{'s'};
664 $func_name = 'XSFUNCTION' if $self->{interface};
665 print "$func_name($self->{func_args});\n";
669 # do output variables
670 $self->{gotRETVAL} = 0; # 1 if RETVAL seen in OUTPUT section;
671 undef $self->{RETVAL_code} ; # code to set RETVAL (from OUTPUT section);
672 # $wantRETVAL set if 'RETVAL =' autogenerated
673 ($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return;
674 undef %{ $self->{outargs} };
675 $self->process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
678 type => $self->{var_types}->{$_},
679 num => $self->{args_match}->{$_},
681 do_setmagic => $self->{DoSetMagic},
683 } ) for grep $self->{in_out}->{$_} =~ /OUT$/, keys %{ $self->{in_out} };
686 # all OUTPUT done, so now push the return value on the stack
687 if ($self->{gotRETVAL} && $self->{RETVAL_code}) {
688 print "\t$self->{RETVAL_code}\n";
690 elsif ($self->{gotRETVAL} || $wantRETVAL) {
691 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
692 my $t = $self->{optimize} && $outputmap && $outputmap->targetable;
693 # Although the '$var' declared in the next line is never explicitly
694 # used within this 'elsif' block, commenting it out leads to
695 # disaster, starting with the first 'eval qq' inside the 'elsif' block
697 # It appears that this is related to the fact that at this point the
698 # value of $t is a reference to an array whose [2] element includes
699 # '$var' as a substring:
702 my $type = $self->{ret_type};
704 if ($t and not $t->{with_size} and $t->{type} eq 'p') {
705 # PUSHp corresponds to setpvn. Treat setpv directly
706 my $what = eval qq("$t->{what}");
709 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
713 my $what = eval qq("$t->{what}");
716 my $tsize = $t->{what_size};
717 $tsize = '' unless defined $tsize;
718 $tsize = eval qq("$tsize");
720 print "\tXSprePUSH; PUSH$t->{type}($what$tsize);\n";
724 # RETVAL almost never needs SvSETMAGIC()
726 type => $self->{ret_type},
735 $xsreturn = 1 if $self->{ret_type} ne "void";
737 my $c = @{ $outlist_ref };
738 print "\tXSprePUSH;" if $c and not $prepush_done;
739 print "\tEXTEND(SP,$c);\n" if $c;
742 type => $self->{var_types}->{$_},
747 } ) for @{ $outlist_ref };
750 $self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
752 print Q(<<"EOF") if $self->{ScopeThisXSUB};
755 print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
759 # print function trailer
763 print Q(<<"EOF") if $self->{except};
766 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
769 if ($self->check_keyword("CASE")) {
770 blurt( $self, "Error: No `CASE:' at top of function")
771 unless $self->{condnum};
772 $_ = "CASE: $_"; # Restore CASE: label
775 last if $_ eq "$END:";
777 /^$self->{BLOCK_re}/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
780 print Q(<<"EOF") if $self->{except};
782 # Perl_croak(aTHX_ errbuf);
786 print Q(<<"EOF") unless $PPCODE;
787 # XSRETURN($xsreturn);
791 print Q(<<"EOF") unless $PPCODE;
801 $self->{newXS} = "newXS";
804 # Build the prototype string for the xsub
805 if ($self->{ProtoThisXSUB}) {
806 $self->{newXS} = "newXSproto_portable";
808 if ($self->{ProtoThisXSUB} eq 2) {
809 # User has specified empty prototype
811 elsif ($self->{ProtoThisXSUB} eq 1) {
813 if ($min_args < $num_args) {
815 $self->{proto_arg}->[$min_args] .= ";";
817 push @{ $self->{proto_arg} }, "$s\@"
820 $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
823 # User has specified a prototype
824 $self->{proto} = $self->{ProtoThisXSUB};
826 $self->{proto} = qq{, "$self->{proto}"};
829 if (%{ $self->{XsubAliases} }) {
830 $self->{XsubAliases}->{$pname} = 0
831 unless defined $self->{XsubAliases}->{$pname};
832 while ( my ($xname, $value) = each %{ $self->{XsubAliases} }) {
833 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
834 # cv = $self->{newXS}(\"$xname\", XS_$Full_func_name, file$self->{proto});
835 # XSANY.any_i32 = $value;
839 elsif (@{ $self->{Attributes} }) {
840 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
841 # cv = $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});
842 # apply_attrs_string("$Package", cv, "@{ $self->{Attributes} }", 0);
845 elsif ($self->{interface}) {
846 while ( my ($yname, $value) = each %{ $self->{Interfaces} }) {
847 $yname = "$Package\::$yname" unless $yname =~ /::/;
848 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
849 # cv = $self->{newXS}(\"$yname\", XS_$Full_func_name, file$self->{proto});
850 # $self->{interface_macro_set}(cv,$value);
854 elsif($self->{newXS} eq 'newXS'){ # work around P5NCI's empty newXS macro
855 push(@{ $self->{InitFileCode} },
856 " $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
859 push(@{ $self->{InitFileCode} },
860 " (void)$self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
862 } # END 'PARAGRAPH' 'while' loop
864 if ($self->{Overload}) { # make it findable with fetchmethod
866 #XS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */
867 #XS(XS_$self->{Packid}_nil)
874 unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK");
875 /* Making a sub named "${Package}::()" allows the package */
876 /* to be findable via fetchmethod(), and causes */
877 /* overload::Overloaded("${Package}") to return true. */
878 (void)$self->{newXS}("${Package}::()", XS_$self->{Packid}_nil, file$self->{proto});
879 MAKE_FETCHMETHOD_WORK
882 # print initialization routine
891 #XS(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
892 #XS(boot_$self->{Module_cname})
904 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
905 #file name argument. If the wrong qualifier is used, it causes breakage with
906 #C++ compilers and warnings with recent gcc.
907 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
909 print Q(<<"EOF") if $Full_func_name;
910 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
911 # char* file = __FILE__;
913 # const char* file = __FILE__;
920 # PERL_UNUSED_VAR(cv); /* -W */
921 # PERL_UNUSED_VAR(items); /* -W */
922 ##ifdef XS_APIVERSION_BOOTCHECK
923 # XS_APIVERSION_BOOTCHECK;
927 print Q(<<"EOF") if $self->{WantVersionChk};
928 # XS_VERSION_BOOTCHECK;
932 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
938 print Q(<<"EOF") if ($self->{Overload});
939 # /* register the overloading (type 'A') magic */
940 # PL_amagic_generation++;
941 # /* The magic for overload gets a GV* via gv_fetchmeth as */
942 # /* mentioned above, and looks in the SV* slot of it for */
943 # /* the "fallback" status. */
945 # get_sv( "${Package}::()", TRUE ),
950 print @{ $self->{InitFileCode} };
952 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
956 if (@{ $BootCode_ref }) {
957 print "\n /* Initialisation Section */\n\n";
958 @{ $self->{line} } = @{ $BootCode_ref };
959 $self->print_section();
960 print "\n /* End of Initialisation Section */\n\n";
964 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
965 # if (PL_unitcheckav)
966 # call_list(PL_scopestack_ix, PL_unitcheckav);
976 warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
977 unless $self->{ProtoUsed};
981 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
987 sub report_error_count { $self->{errors} }
989 # Input: ($self, $_, @{ $self->{line} }) == unparsed input.
990 # Output: ($_, @{ $self->{line} }) == (rest of line, following lines).
991 # Return: the matched keyword if found, otherwise 0
994 $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} };
995 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1001 # the "do" is required for right semantics
1002 do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} };
1004 print("#line ", $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1], " \"$self->{filepathname}\"\n")
1005 if $self->{WantLineNumbers} && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1006 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1009 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
1016 while (!/\S/ && @{ $self->{line} }) {
1017 $_ = shift(@{ $self->{line} });
1020 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1027 sub process_keyword {
1028 my($self, $pattern) = @_;
1030 while (my $kwd = $self->check_keyword($pattern)) {
1031 my $method = $kwd . "_handler";
1039 blurt( $self, "Error: `CASE:' after unconditional `CASE:'")
1040 if $self->{condnum} && $self->{cond} eq '';
1042 trim_whitespace($self->{cond});
1043 print " ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n");
1050 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1051 last if /^\s*NOT_IMPLEMENTED_YET/;
1052 next unless /\S/; # skip blank lines
1054 trim_whitespace($_);
1057 # remove trailing semicolon if no initialisation
1058 s/\s*;$//g unless /[=;+].*\S/;
1060 # Process the length(foo) declarations
1061 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1062 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1063 $self->{lengthof}->{$2} = undef;
1064 $self->{deferred} .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1067 # check for optional initialisation code
1069 $var_init = $1 if s/\s*([=;+].*)$//s;
1070 $var_init =~ s/"/\\"/g;
1073 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1074 or blurt( $self, "Error: invalid argument declaration '$ln'"), next;
1076 # Check for duplicate definitions
1077 blurt( $self, "Error: duplicate definition of argument '$var_name' ignored"), next
1078 if $self->{arg_list}->{$var_name}++
1079 or defined $self->{argtype_seen}->{$var_name} and not $self->{processing_arg_with_types};
1081 $self->{thisdone} |= $var_name eq "THIS";
1082 $self->{retvaldone} |= $var_name eq "RETVAL";
1083 $self->{var_types}->{$var_name} = $var_type;
1084 # XXXX This check is a safeguard against the unfinished conversion of
1085 # generate_init(). When generate_init() is fixed,
1086 # one can use 2-args map_type() unconditionally.
1088 if ($var_type =~ / \( \s* \* \s* \) /x) {
1089 # Function pointers are not yet supported with output_init()!
1090 print "\t" . map_type($self, $var_type, $var_name);
1094 print "\t" . map_type($self, $var_type, undef);
1097 $self->{var_num} = $self->{args_match}->{$var_name};
1099 if ($self->{var_num}) {
1100 my $typemap = $self->{typemap}->get_typemap(ctype => $var_type);
1101 $self->{proto_arg}->[$self->{var_num}] = ($typemap && $typemap->proto) || "\$";
1103 $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr;
1104 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1105 or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/
1106 and $var_init !~ /\S/) {
1107 if ($printed_name) {
1111 print "\t$var_name;\n";
1114 elsif ($var_init =~ /\S/) {
1117 num => $self->{var_num},
1120 printed_name => $printed_name,
1123 elsif ($self->{var_num}) {
1126 num => $self->{var_num},
1128 printed_name => $printed_name,
1137 sub OUTPUT_handler {
1140 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1142 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1143 $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
1146 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1147 blurt( $self, "Error: duplicate OUTPUT argument '$outarg' ignored"), next
1148 if $self->{outargs}->{$outarg}++;
1149 if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') {
1150 # deal with RETVAL last
1151 $self->{RETVAL_code} = $outcode;
1152 $self->{gotRETVAL} = 1;
1155 blurt( $self, "Error: OUTPUT $outarg not an argument"), next
1156 unless defined($self->{args_match}->{$outarg});
1157 blurt( $self, "Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1158 unless defined $self->{var_types}->{$outarg};
1159 $self->{var_num} = $self->{args_match}->{$outarg};
1161 print "\t$outcode\n";
1162 print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
1166 type => $self->{var_types}->{$outarg},
1167 num => $self->{var_num},
1169 do_setmagic => $self->{DoSetMagic},
1173 delete $self->{in_out}->{$outarg} # No need to auto-OUTPUT
1174 if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
1178 sub C_ARGS_handler {
1181 my $in = $self->merge_section();
1183 trim_whitespace($in);
1184 $self->{func_args} = $in;
1187 sub INTERFACE_MACRO_handler {
1190 my $in = $self->merge_section();
1192 trim_whitespace($in);
1193 if ($in =~ /\s/) { # two
1194 ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
1197 $self->{interface_macro} = $in;
1198 $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
1200 $self->{interface} = 1; # local
1201 $self->{interfaces} = 1; # global
1204 sub INTERFACE_handler {
1207 my $in = $self->merge_section();
1209 trim_whitespace($in);
1211 foreach (split /[\s,]+/, $in) {
1212 my $iface_name = $_;
1213 $iface_name =~ s/^$self->{Prefix}//;
1214 $self->{Interfaces}->{$iface_name} = $_;
1217 # XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
1219 $self->{interface} = 1; # local
1220 $self->{interfaces} = 1; # global
1223 sub CLEANUP_handler {
1225 $self->print_section();
1228 sub PREINIT_handler {
1230 $self->print_section();
1233 sub POSTCALL_handler {
1235 $self->print_section();
1240 $self->print_section();
1248 # Parse alias definitions
1250 # alias = value alias = value ...
1252 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1253 my ($alias, $value) = ($1, $2);
1254 my $orig_alias = $alias;
1256 # check for optional package definition in the alias
1257 $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
1259 # check for duplicate alias name & duplicate value
1260 Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'")
1261 if defined $self->{XsubAliases}->{$alias};
1263 Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
1264 if $self->{XsubAliasValues}->{$value};
1266 $self->{xsubaliases} = 1;
1267 $self->{XsubAliases}->{$alias} = $value;
1268 $self->{XsubAliasValues}->{$value} = $orig_alias;
1271 blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'")
1279 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1281 trim_whitespace($_);
1282 push @{ $self->{Attributes} }, $_;
1290 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1292 trim_whitespace($_);
1293 $self->get_aliases($_) if $_;
1297 sub OVERLOAD_handler {
1301 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1303 trim_whitespace($_);
1304 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1305 $self->{Overload} = 1 unless $self->{Overload};
1306 my $overload = "$Package\::(".$1;
1307 push(@{ $self->{InitFileCode} },
1308 " (void)$self->{newXS}(\"$overload\", XS_$Full_func_name, file$self->{proto});\n");
1313 sub FALLBACK_handler {
1317 # the rest of the current line should contain either TRUE,
1320 trim_whitespace($_);
1322 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1323 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1324 UNDEF => "&PL_sv_undef",
1327 # check for valid FALLBACK value
1328 death( $self, "Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1330 $self->{Fallback} = $map{uc $_};
1334 sub REQUIRE_handler {
1336 # the rest of the current line should contain a version number
1339 trim_whitespace($Ver);
1341 death( $self, "Error: REQUIRE expects a version number")
1344 # check that the version number is of the form n.n
1345 death( $self, "Error: REQUIRE: expected a number, got '$Ver'")
1346 unless $Ver =~ /^\d+(\.\d*)?/;
1348 death( $self, "Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1349 unless $VERSION >= $Ver;
1352 sub VERSIONCHECK_handler {
1356 # the rest of the current line should contain either ENABLE or
1359 trim_whitespace($_);
1361 # check for ENABLE/DISABLE
1362 death( $self, "Error: VERSIONCHECK: ENABLE/DISABLE")
1363 unless /^(ENABLE|DISABLE)/i;
1365 $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1366 $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
1370 sub PROTOTYPE_handler {
1376 death( $self, "Error: Only 1 PROTOTYPE definition allowed per xsub")
1377 if $self->{proto_in_this_xsub}++;
1379 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1382 trim_whitespace($_);
1383 if ($_ eq 'DISABLE') {
1384 $self->{ProtoThisXSUB} = 0;
1386 elsif ($_ eq 'ENABLE') {
1387 $self->{ProtoThisXSUB} = 1;
1390 # remove any whitespace
1392 death( $self, "Error: Invalid prototype '$_'")
1393 unless valid_proto_string($_);
1394 $self->{ProtoThisXSUB} = C_string($_);
1398 # If no prototype specified, then assume empty prototype ""
1399 $self->{ProtoThisXSUB} = 2 unless $specified;
1401 $self->{ProtoUsed} = 1;
1408 death( $self, "Error: Only 1 SCOPE declaration allowed per xsub")
1409 if $self->{scope_in_this_xsub}++;
1411 trim_whitespace($_);
1412 death("Error: SCOPE: ENABLE/DISABLE")
1413 unless /^(ENABLE|DISABLE)\b/i;
1414 $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
1417 sub PROTOTYPES_handler {
1421 # the rest of the current line should contain either ENABLE or
1424 trim_whitespace($_);
1426 # check for ENABLE/DISABLE
1427 death("Error: PROTOTYPES: ENABLE/DISABLE")
1428 unless /^(ENABLE|DISABLE)/i;
1430 $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1431 $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
1432 $self->{ProtoUsed} = 1;
1438 # Save the current file context.
1439 push(@{ $self->{XSStack} }, {
1441 LastLine => $self->{lastline},
1442 LastLineNo => $self->{lastline_no},
1443 Line => $self->{line},
1444 LineNo => $self->{line_no},
1445 Filename => $self->{filename},
1446 Filepathname => $self->{filepathname},
1448 IsPipe => scalar($self->{filename} =~ /\|\s*$/),
1454 sub INCLUDE_handler {
1457 # the rest of the current line should contain a valid filename
1459 trim_whitespace($_);
1461 death( $self, "INCLUDE: filename missing")
1464 death( $self, "INCLUDE: output pipe is illegal")
1467 # simple minded recursion detector
1468 death( $self, "INCLUDE loop detected")
1469 if $self->{IncludedFiles}->{$_};
1471 ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
1473 if (/\|\s*$/ && /^\s*perl\s/) {
1474 Warn( $self, "The INCLUDE directive with a command is discouraged." .
1475 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1476 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1477 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1478 " the use of \$^X as the currently running perl, see" .
1479 " 'perldoc perlxs' for details.");
1482 $self->PushXSStack();
1484 $FH = Symbol::gensym();
1487 open ($FH, "$_") or death( $self, "Cannot open '$_': $!");
1491 #/* INCLUDE: Including '$_' from '$self->{filename}' */
1495 $self->{filename} = $_;
1496 $self->{filepathname} = File::Spec->catfile($self->{dir}, $self->{filename});
1498 # Prime the pump by reading the first
1501 # skip leading blank lines
1503 last unless /^\s*$/;
1506 $self->{lastline} = $_;
1507 $self->{lastline_no} = $.;
1512 my @args = split /\s+/, $cmd;
1515 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1517 return join (' ', ($cmd, @args));
1520 sub INCLUDE_COMMAND_handler {
1523 # the rest of the current line should contain a valid command
1525 trim_whitespace($_);
1527 $_ = QuoteArgs($_) if $^O eq 'VMS';
1529 death( $self, "INCLUDE_COMMAND: command missing")
1532 death( $self, "INCLUDE_COMMAND: pipes are illegal")
1533 if /^\s*\|/ or /\|\s*$/;
1535 $self->PushXSStack( IsPipe => 1 );
1537 $FH = Symbol::gensym();
1539 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1540 # the same perl interpreter as we're currently running
1544 open ($FH, "-|", "$_")
1545 or death( $self, "Cannot run command '$_' to include its output: $!");
1549 #/* INCLUDE_COMMAND: Including output of '$_' from '$self->{filename}' */
1553 $self->{filename} = $_;
1554 $self->{filepathname} = $self->{filename};
1555 $self->{filepathname} =~ s/\"/\\"/g;
1557 # Prime the pump by reading the first
1560 # skip leading blank lines
1562 last unless /^\s*$/;
1565 $self->{lastline} = $_;
1566 $self->{lastline_no} = $.;
1572 return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
1574 my $data = pop @{ $self->{XSStack} };
1575 my $ThisFile = $self->{filename};
1576 my $isPipe = $data->{IsPipe};
1578 --$self->{IncludedFiles}->{$self->{filename}}
1583 $FH = $data->{Handle};
1584 # $filename is the leafname, which for some reason isused for diagnostic
1585 # messages, whereas $filepathname is the full pathname, and is used for
1587 $self->{filename} = $data->{Filename};
1588 $self->{filepathname} = $data->{Filepathname};
1589 $self->{lastline} = $data->{LastLine};
1590 $self->{lastline_no} = $data->{LastLineNo};
1591 @{ $self->{line} } = @{ $data->{Line} };
1592 @{ $self->{line_no} } = @{ $data->{LineNo} };
1594 if ($isPipe and $? ) {
1595 --$self->{lastline_no};
1596 print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
1602 #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
1612 $text =~ s/\[\[/{/g;
1613 $text =~ s/\]\]/}/g;
1617 # Read next xsub into @{ $self->{line} } from ($lastline, <$FH>).
1622 death("Error: Unterminated `#if/#ifdef/#ifndef'")
1623 if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if';
1624 @{ $self->{line} } = ();
1625 @{ $self->{line_no} } = ();
1626 return $self->PopFile() if !defined $self->{lastline};
1628 if ($self->{lastline} =~
1629 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1631 $Package = defined($2) ? $2 : ''; # keep -w happy
1632 $self->{Prefix} = defined($3) ? $3 : ''; # keep -w happy
1633 $self->{Prefix} = quotemeta $self->{Prefix};
1634 ($self->{Module_cname} = $Module) =~ s/\W/_/g;
1635 ($self->{Packid} = $Package) =~ tr/:/_/;
1636 $self->{Packprefix} = $Package;
1637 $self->{Packprefix} .= "::" if $self->{Packprefix} ne "";
1638 $self->{lastline} = "";
1642 # Skip embedded PODs
1643 while ($self->{lastline} =~ /^=/) {
1644 while ($self->{lastline} = <$FH>) {
1645 last if ($self->{lastline} =~ /^=cut\s*$/);
1647 death("Error: Unterminated pod") unless $self->{lastline};
1648 $self->{lastline} = <$FH>;
1649 chomp $self->{lastline};
1650 $self->{lastline} =~ s/^\s+$//;
1652 if ($self->{lastline} !~ /^\s*#/ ||
1654 # ANSI: if ifdef ifndef elif else endif define undef
1656 # gcc: warning include_next
1658 # others: ident (gcc notes that some cpps have this one)
1659 $self->{lastline} =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1660 last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq "";
1661 push(@{ $self->{line} }, $self->{lastline});
1662 push(@{ $self->{line_no} }, $self->{lastline_no});
1665 # Read next line and continuation lines
1666 last unless defined($self->{lastline} = <$FH>);
1667 $self->{lastline_no} = $.;
1669 $self->{lastline} .= $tmp_line
1670 while ($self->{lastline} =~ /\\$/ && defined($tmp_line = <$FH>));
1672 chomp $self->{lastline};
1673 $self->{lastline} =~ s/^\s+$//;
1675 pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq "";
1680 my $argsref = shift;
1681 my ($type, $num, $var, $init, $printed_name) = (
1686 $argsref->{printed_name}
1688 my $arg = "ST(" . ($num - 1) . ")";
1690 if ( $init =~ /^=/ ) {
1691 if ($printed_name) {
1692 eval qq/print " $init\\n"/;
1695 eval qq/print "\\t$var $init\\n"/;
1700 if ( $init =~ s/^\+// && $num ) {
1705 printed_name => $printed_name,
1708 elsif ($printed_name) {
1713 eval qq/print "\\t$var;\\n"/;
1717 $self->{deferred} .= eval qq/"\\n\\t$init\\n"/;
1723 my $argsref = shift;
1724 my ($type, $num, $var, $printed_name) = (
1728 $argsref->{printed_name},
1730 my $arg = "ST(" . ($num - 1) . ")";
1731 my ($argoff, $ntype);
1734 my $typemaps = $self->{typemap};
1736 $type = tidy_type($type);
1737 blurt( $self, "Error: '$type' not in typemap"), return
1738 unless $typemaps->get_typemap(ctype => $type);
1740 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1742 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1743 my $typem = $typemaps->get_typemap(ctype => $type);
1744 my $xstype = $typem->xstype;
1745 $xstype =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1746 if ($xstype eq 'T_PV' and exists $self->{lengthof}->{$var}) {
1747 print "\t$var" unless $printed_name;
1748 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1749 die "default value not supported with length(NAME) supplied"
1750 if defined $self->{defaults}->{$var};
1753 $type =~ tr/:/_/ unless $self->{hiertype};
1755 my $inputmap = $typemaps->get_inputmap(xstype => $xstype);
1756 blurt( $self, "Error: No INPUT definition for type '$type', typekind '" . $type->xstype . "' found"), return
1757 unless defined $inputmap;
1759 my $expr = $inputmap->cleaned_code;
1760 # Note: This gruesome bit either needs heavy rethinking or documentation. I vote for the former. --Steffen
1761 if ($expr =~ /DO_ARRAY_ELEM/) {
1762 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1763 my $subinputmap = $typemaps->get_inputmap(xstype => $subtypemap->xstype);
1764 blurt( $self, "Error: '$subtype' not in typemap"), return
1766 blurt( $self, "Error: No INPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1767 unless $subinputmap;
1768 my $subexpr = $subinputmap->cleaned_code;
1769 $subexpr =~ s/\$type/\$subtype/g;
1770 $subexpr =~ s/ntype/subtype/g;
1771 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1772 $subexpr =~ s/\n\t/\n\t\t/g;
1773 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1774 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1775 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1777 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1778 $self->{ScopeThisXSUB} = 1;
1780 if (defined($self->{defaults}->{$var})) {
1781 $expr =~ s/(\t+)/$1 /g;
1783 if ($printed_name) {
1787 eval qq/print "\\t$var;\\n"/;
1790 if ($self->{defaults}->{$var} eq 'NO_INIT') {
1791 $self->{deferred} .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1794 $self->{deferred} .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1798 elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
1799 if ($printed_name) {
1803 eval qq/print "\\t$var;\\n"/;
1806 $self->{deferred} .= eval qq/"\\n$expr;\\n"/;
1810 die "panic: do not know how to handle this branch for function pointers"
1812 eval qq/print "$expr;\\n"/;
1817 sub generate_output {
1818 my $argsref = shift;
1819 my ($type, $num, $var, $do_setmagic, $do_push) = (
1823 $argsref->{do_setmagic},
1826 my $arg = "ST(" . ($num - ($num != 0)) . ")";
1829 my $typemaps = $self->{typemap};
1831 $type = tidy_type($type);
1832 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1833 print "\t$arg = sv_newmortal();\n";
1834 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1835 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1838 my $typemap = $typemaps->get_typemap(ctype => $type);
1839 my $outputmap = $typemaps->get_outputmap(xstype => $typemap->xstype);
1840 blurt( $self, "Error: '$type' not in typemap"), return
1842 blurt( $self, "Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found"), return
1844 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1845 $ntype =~ s/\(\)//g;
1847 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1849 my $expr = $outputmap->cleaned_code;
1850 if ($expr =~ /DO_ARRAY_ELEM/) {
1851 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1852 my $suboutputmap = $typemaps->get_outputmap(xstype => $subtypemap->xstype);
1853 blurt( $self, "Error: '$subtype' not in typemap"), return
1855 blurt( $self, "Error: No OUTPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1856 unless $suboutputmap;
1857 my $subexpr = $suboutputmap->cleaned_code;
1858 $subexpr =~ s/ntype/subtype/g;
1859 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1860 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1861 $subexpr =~ s/\n\t/\n\t\t/g;
1862 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1863 eval "print qq\a$expr\a";
1865 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1867 elsif ($var eq 'RETVAL') {
1868 if ($expr =~ /^\t\$arg = new/) {
1869 # We expect that $arg has refcnt 1, so we need to
1871 eval "print qq\a$expr\a";
1873 print "\tsv_2mortal(ST($num));\n";
1874 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1876 elsif ($expr =~ /^\s*\$arg\s*=/) {
1877 # We expect that $arg has refcnt >=1, so we need
1879 eval "print qq\a$expr\a";
1881 print "\tsv_2mortal(ST(0));\n";
1882 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1885 # Just hope that the entry would safely write it
1886 # over an already mortalized value. By
1887 # coincidence, something like $arg = &sv_undef
1889 print "\tST(0) = sv_newmortal();\n";
1890 eval "print qq\a$expr\a";
1892 # new mortals don't have set magic
1896 print "\tPUSHs(sv_newmortal());\n";
1898 eval "print qq\a$expr\a";
1900 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1902 elsif ($arg =~ /^ST\(\d+\)$/) {
1903 eval "print qq\a$expr\a";
1905 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1912 # vim: ts=2 sw=2 et: