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
30 check_conditional_preprocessor_statements
33 our @ISA = qw(Exporter);
39 $VERSION = eval $VERSION if $VERSION =~ /_/;
41 # The scalars in the line below remain as 'our' variables because pulling
42 # them into $self led to build problems. In most cases, strings being
43 # 'eval'-ed contain the variables' names hard-coded.
45 $Package, $func_name, $Full_func_name, $pname, $ALIAS,
48 our $self = bless {} => __PACKAGE__;
52 # Allow for $package->process_file(%hash) in the future
53 my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
55 $self->{ProtoUsed} = exists $options{prototypes};
70 FH => Symbol::gensym(),
73 $args{except} = $args{except} ? ' TRY' : '';
77 my ($Is_VMS, $SymSet);
80 # Establish set of global symbols with max length 28, since xsubpp
81 # will later add the 'XS_' prefix.
82 require ExtUtils::XSSymSet;
83 $SymSet = ExtUtils::XSSymSet->new(28);
85 @{ $self->{XSStack} } = ({type => 'none'});
86 $self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ];
87 $self->{Overload} = 0;
89 $self->{Fallback} = '&PL_sv_undef';
91 # Most of the 1500 lines below uses these globals. We'll have to
92 # clean this up sometime, probably. For now, we just pull them out
95 $self->{hiertype} = $args{hiertype};
96 $self->{WantPrototypes} = $args{prototypes};
97 $self->{WantVersionChk} = $args{versioncheck};
98 $self->{WantLineNumbers} = $args{linenumbers};
99 $self->{IncludedFiles} = {};
101 die "Missing required parameter 'filename'" unless $args{filename};
102 $self->{filepathname} = $args{filename};
103 ($self->{dir}, $self->{filename}) =
104 (dirname($args{filename}), basename($args{filename}));
105 $self->{filepathname} =~ s/\\/\\\\/g;
106 $self->{IncludedFiles}->{$args{filename}}++;
108 # Open the output file if given as a string. If they provide some
109 # other kind of reference, trust them that we can print to it.
110 if (not ref $args{output}) {
111 open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
112 $args{outfile} = $args{output};
116 # Really, we shouldn't have to chdir() or select() in the first
117 # place. For now, just save and restore.
118 my $orig_cwd = cwd();
119 my $orig_fh = select();
123 my $csuffix = $args{csuffix};
125 if ($self->{WantLineNumbers}) {
127 if ( $args{outfile} ) {
128 $cfile = $args{outfile};
131 $cfile = $args{filename};
132 $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
134 tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
135 select PSEUDO_STDOUT;
138 select $args{output};
141 $self->{typemap} = process_typemaps( $args{typemap}, $pwd );
143 my $END = "!End!\n\n"; # "impossible" keyword (multiple newline)
145 # Match an XS keyword
146 $self->{BLOCK_re} = '\s*(' .
147 join('|' => @ExtUtils::ParseXS::Constants::XSKeywords) .
150 our ($C_group_rex, $C_arg);
151 # Group in C (no support for comments or literals)
152 $C_group_rex = qr/ [({\[]
153 (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
155 # Chunk in C without comma at toplevel (no comments):
156 $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
157 | (??{ $C_group_rex })
158 | " (?: (?> [^\\"]+ )
160 )* " # String literal
161 | ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
164 # Since at this point we're ready to begin printing to the output file and
165 # reading from the input file, I want to get as much data as possible into
166 # the proto-object $self. That means assigning to $self and elements of
167 # %args referenced below this point.
168 # HOWEVER: This resulted in an error when I tried:
169 # $args{'s'} ---> $self->{s}.
170 # Use of uninitialized value in quotemeta at
171 # .../blib/lib/ExtUtils/ParseXS.pm line 733
173 foreach my $datum ( qw| argtypes except inout optimize | ) {
174 $self->{$datum} = $args{$datum};
177 # Identify the version of xsubpp used
180 * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
181 * contents of $self->{filename}. Do not edit this file, edit $self->{filename} instead.
183 * ANY CHANGES MADE HERE WILL BE LOST!
190 print("#line 1 \"$self->{filepathname}\"\n")
191 if $self->{WantLineNumbers};
193 # Open the input file (using $self->{filename} which
194 # is a basename'd $args{filename} due to chdir above)
195 open($self->{FH}, '<', $self->{filename}) or die "cannot open $self->{filename}: $!\n";
198 while (readline($self->{FH})) {
200 my $podstartline = $.;
203 # We can't just write out a /* */ comment, as our embedded
204 # POD might itself be in a comment. We can't put a /**/
205 # comment inside #if 0, as the C standard says that the source
206 # file is decomposed into preprocessing characters in the stage
207 # before preprocessing commands are executed.
208 # I don't want to leave the text as barewords, because the spec
209 # isn't clear whether macros are expanded before or after
210 # preprocessing commands are executed, and someone pathological
211 # may just have defined one of the 3 words as a macro that does
212 # something strange. Multiline strings are illegal in C, so
213 # the "" we write must be a string literal. And they aren't
214 # concatenated until 2 steps later, so we are safe.
216 print("#if 0\n \"Skipped embedded POD.\"\n#endif\n");
217 printf("#line %d \"$self->{filepathname}\"\n", $. + 1)
218 if $self->{WantLineNumbers};
222 } while (readline($self->{FH}));
223 # At this point $. is at end of file so die won't state the start
224 # of the problem, and as we haven't yet read any lines &death won't
225 # show the correct line in the message either.
226 die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n")
227 unless $self->{lastline};
229 last if ($Package, $self->{Prefix}) =
230 /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
234 unless (defined $_) {
235 warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
236 exit 0; # Not a fatal error for the caller process
239 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
243 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
245 $self->{lastline} = $_;
246 $self->{lastline_no} = $.;
248 my $BootCode_ref = [];
249 my $XSS_work_idx = 0;
250 my $cpp_next_tmp = 'XSubPPtmpAAAA';
252 while ($self->fetch_para()) {
253 my $outlist_ref = [];
254 # Print initial preprocessor statements and blank lines
255 while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) {
256 my $ln = shift(@{ $self->{line} });
258 next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
260 ( $self, $XSS_work_idx, $BootCode_ref ) =
261 analyze_preprocessor_statements(
262 $self, $statement, $XSS_work_idx, $BootCode_ref
266 next PARAGRAPH unless @{ $self->{line} };
268 if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) {
269 # We are inside an #if, but have not yet #defined its xsubpp variable.
270 print "#define $cpp_next_tmp 1\n\n";
271 push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n");
272 push(@{ $BootCode_ref }, "#if $cpp_next_tmp");
273 $self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++;
277 "Code is not inside a function"
278 ." (maybe last function was ended by a blank line "
279 ." followed by a statement on column one?)")
280 if $self->{line}->[0] =~ /^\s/;
282 # initialize info arrays
283 foreach my $member (qw(args_match var_types defaults arg_list
284 argtype_seen in_out lengthof))
286 $self->{$member} = {};
288 $self->{proto_arg} = [];
289 $self->{processing_arg_with_types} = undef;
290 $self->{proto_in_this_xsub} = undef;
291 $self->{scope_in_this_xsub} = undef;
292 $self->{interface} = undef;
293 $self->{interface_macro} = 'XSINTERFACE_FUNC';
294 $self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET';
295 $self->{ProtoThisXSUB} = $self->{WantPrototypes};
296 $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 $self->blurt("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 $self->blurt("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 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 $self->death("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 $self->blurt("Error: No `CASE:' at top of function")
771 unless $self->{condnum};
772 $_ = "CASE: $_"; # Restore CASE: label
775 last if $_ eq "$END:";
776 $self->death(/^$self->{BLOCK_re}/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
779 print Q(<<"EOF") if $self->{except};
781 # Perl_croak(aTHX_ errbuf);
785 print Q(<<"EOF") unless $PPCODE;
786 # XSRETURN($xsreturn);
790 print Q(<<"EOF") unless $PPCODE;
800 $self->{newXS} = "newXS";
803 # Build the prototype string for the xsub
804 if ($self->{ProtoThisXSUB}) {
805 $self->{newXS} = "newXSproto_portable";
807 if ($self->{ProtoThisXSUB} eq 2) {
808 # User has specified empty prototype
810 elsif ($self->{ProtoThisXSUB} eq 1) {
812 if ($min_args < $num_args) {
814 $self->{proto_arg}->[$min_args] .= ";";
816 push @{ $self->{proto_arg} }, "$s\@"
819 $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
822 # User has specified a prototype
823 $self->{proto} = $self->{ProtoThisXSUB};
825 $self->{proto} = qq{, "$self->{proto}"};
828 if (%{ $self->{XsubAliases} }) {
829 $self->{XsubAliases}->{$pname} = 0
830 unless defined $self->{XsubAliases}->{$pname};
831 while ( my ($xname, $value) = each %{ $self->{XsubAliases} }) {
832 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
833 # cv = $self->{newXS}(\"$xname\", XS_$Full_func_name, file$self->{proto});
834 # XSANY.any_i32 = $value;
838 elsif (@{ $self->{Attributes} }) {
839 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
840 # cv = $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});
841 # apply_attrs_string("$Package", cv, "@{ $self->{Attributes} }", 0);
844 elsif ($self->{interface}) {
845 while ( my ($yname, $value) = each %{ $self->{Interfaces} }) {
846 $yname = "$Package\::$yname" unless $yname =~ /::/;
847 push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
848 # cv = $self->{newXS}(\"$yname\", XS_$Full_func_name, file$self->{proto});
849 # $self->{interface_macro_set}(cv,$value);
853 elsif($self->{newXS} eq 'newXS'){ # work around P5NCI's empty newXS macro
854 push(@{ $self->{InitFileCode} },
855 " $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
858 push(@{ $self->{InitFileCode} },
859 " (void)$self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
861 } # END 'PARAGRAPH' 'while' loop
863 if ($self->{Overload}) { # make it findable with fetchmethod
865 #XS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */
866 #XS(XS_$self->{Packid}_nil)
873 unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK");
874 /* Making a sub named "${Package}::()" allows the package */
875 /* to be findable via fetchmethod(), and causes */
876 /* overload::Overloaded("${Package}") to return true. */
877 (void)$self->{newXS}("${Package}::()", XS_$self->{Packid}_nil, file$self->{proto});
878 MAKE_FETCHMETHOD_WORK
881 # print initialization routine
890 #XS(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
891 #XS(boot_$self->{Module_cname})
903 #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
904 #file name argument. If the wrong qualifier is used, it causes breakage with
905 #C++ compilers and warnings with recent gcc.
906 #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
908 print Q(<<"EOF") if $Full_func_name;
909 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
910 # char* file = __FILE__;
912 # const char* file = __FILE__;
919 # PERL_UNUSED_VAR(cv); /* -W */
920 # PERL_UNUSED_VAR(items); /* -W */
921 ##ifdef XS_APIVERSION_BOOTCHECK
922 # XS_APIVERSION_BOOTCHECK;
926 print Q(<<"EOF") if $self->{WantVersionChk};
927 # XS_VERSION_BOOTCHECK;
931 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
937 print Q(<<"EOF") if ($self->{Overload});
938 # /* register the overloading (type 'A') magic */
939 # PL_amagic_generation++;
940 # /* The magic for overload gets a GV* via gv_fetchmeth as */
941 # /* mentioned above, and looks in the SV* slot of it for */
942 # /* the "fallback" status. */
944 # get_sv( "${Package}::()", TRUE ),
949 print @{ $self->{InitFileCode} };
951 print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
955 if (@{ $BootCode_ref }) {
956 print "\n /* Initialisation Section */\n\n";
957 @{ $self->{line} } = @{ $BootCode_ref };
958 $self->print_section();
959 print "\n /* End of Initialisation Section */\n\n";
963 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
964 # if (PL_unitcheckav)
965 # call_list(PL_scopestack_ix, PL_unitcheckav);
975 warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
976 unless $self->{ProtoUsed};
980 untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
986 sub report_error_count { $self->{errors} }
988 # Input: ($self, $_, @{ $self->{line} }) == unparsed input.
989 # Output: ($_, @{ $self->{line} }) == (rest of line, following lines).
990 # Return: the matched keyword if found, otherwise 0
993 $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} };
994 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1000 # the "do" is required for right semantics
1001 do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} };
1003 print("#line ", $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1], " \"$self->{filepathname}\"\n")
1004 if $self->{WantLineNumbers} && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1005 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1008 print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
1015 while (!/\S/ && @{ $self->{line} }) {
1016 $_ = shift(@{ $self->{line} });
1019 for (; defined($_) && !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1026 sub process_keyword {
1027 my($self, $pattern) = @_;
1029 while (my $kwd = $self->check_keyword($pattern)) {
1030 my $method = $kwd . "_handler";
1038 $self->blurt("Error: `CASE:' after unconditional `CASE:'")
1039 if $self->{condnum} && $self->{cond} eq '';
1041 trim_whitespace($self->{cond});
1042 print " ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n");
1049 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1050 last if /^\s*NOT_IMPLEMENTED_YET/;
1051 next unless /\S/; # skip blank lines
1053 trim_whitespace($_);
1056 # remove trailing semicolon if no initialisation
1057 s/\s*;$//g unless /[=;+].*\S/;
1059 # Process the length(foo) declarations
1060 if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1061 print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1062 $self->{lengthof}->{$2} = undef;
1063 $self->{deferred} .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1066 # check for optional initialisation code
1068 $var_init = $1 if s/\s*([=;+].*)$//s;
1069 $var_init =~ s/"/\\"/g;
1072 my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1073 or $self->blurt("Error: invalid argument declaration '$ln'"), next;
1075 # Check for duplicate definitions
1076 $self->blurt("Error: duplicate definition of argument '$var_name' ignored"), next
1077 if $self->{arg_list}->{$var_name}++
1078 or defined $self->{argtype_seen}->{$var_name} and not $self->{processing_arg_with_types};
1080 $self->{thisdone} |= $var_name eq "THIS";
1081 $self->{retvaldone} |= $var_name eq "RETVAL";
1082 $self->{var_types}->{$var_name} = $var_type;
1083 # XXXX This check is a safeguard against the unfinished conversion of
1084 # generate_init(). When generate_init() is fixed,
1085 # one can use 2-args map_type() unconditionally.
1087 if ($var_type =~ / \( \s* \* \s* \) /x) {
1088 # Function pointers are not yet supported with output_init()!
1089 print "\t" . map_type($self, $var_type, $var_name);
1093 print "\t" . map_type($self, $var_type, undef);
1096 $self->{var_num} = $self->{args_match}->{$var_name};
1098 if ($self->{var_num}) {
1099 my $typemap = $self->{typemap}->get_typemap(ctype => $var_type);
1100 $self->death("Could not find a typemap for C type '$var_type'")
1102 $self->{proto_arg}->[$self->{var_num}] = ($typemap && $typemap->proto) || "\$";
1104 $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr;
1105 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1106 or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/
1107 and $var_init !~ /\S/) {
1108 if ($printed_name) {
1112 print "\t$var_name;\n";
1115 elsif ($var_init =~ /\S/) {
1118 num => $self->{var_num},
1121 printed_name => $printed_name,
1124 elsif ($self->{var_num}) {
1127 num => $self->{var_num},
1129 printed_name => $printed_name,
1138 sub OUTPUT_handler {
1141 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1143 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1144 $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
1147 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1148 $self->blurt("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1149 if $self->{outargs}->{$outarg}++;
1150 if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') {
1151 # deal with RETVAL last
1152 $self->{RETVAL_code} = $outcode;
1153 $self->{gotRETVAL} = 1;
1156 $self->blurt("Error: OUTPUT $outarg not an argument"), next
1157 unless defined($self->{args_match}->{$outarg});
1158 $self->blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1159 unless defined $self->{var_types}->{$outarg};
1160 $self->{var_num} = $self->{args_match}->{$outarg};
1162 print "\t$outcode\n";
1163 print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
1167 type => $self->{var_types}->{$outarg},
1168 num => $self->{var_num},
1170 do_setmagic => $self->{DoSetMagic},
1174 delete $self->{in_out}->{$outarg} # No need to auto-OUTPUT
1175 if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
1179 sub C_ARGS_handler {
1182 my $in = $self->merge_section();
1184 trim_whitespace($in);
1185 $self->{func_args} = $in;
1188 sub INTERFACE_MACRO_handler {
1191 my $in = $self->merge_section();
1193 trim_whitespace($in);
1194 if ($in =~ /\s/) { # two
1195 ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
1198 $self->{interface_macro} = $in;
1199 $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
1201 $self->{interface} = 1; # local
1202 $self->{interfaces} = 1; # global
1205 sub INTERFACE_handler {
1208 my $in = $self->merge_section();
1210 trim_whitespace($in);
1212 foreach (split /[\s,]+/, $in) {
1213 my $iface_name = $_;
1214 $iface_name =~ s/^$self->{Prefix}//;
1215 $self->{Interfaces}->{$iface_name} = $_;
1218 # XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
1220 $self->{interface} = 1; # local
1221 $self->{interfaces} = 1; # global
1224 sub CLEANUP_handler {
1226 $self->print_section();
1229 sub PREINIT_handler {
1231 $self->print_section();
1234 sub POSTCALL_handler {
1236 $self->print_section();
1241 $self->print_section();
1249 # Parse alias definitions
1251 # alias = value alias = value ...
1253 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1254 my ($alias, $value) = ($1, $2);
1255 my $orig_alias = $alias;
1257 # check for optional package definition in the alias
1258 $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
1260 # check for duplicate alias name & duplicate value
1261 Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'")
1262 if defined $self->{XsubAliases}->{$alias};
1264 Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
1265 if $self->{XsubAliasValues}->{$value};
1267 $self->{xsubaliases} = 1;
1268 $self->{XsubAliases}->{$alias} = $value;
1269 $self->{XsubAliasValues}->{$value} = $orig_alias;
1272 blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'")
1280 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1282 trim_whitespace($_);
1283 push @{ $self->{Attributes} }, $_;
1291 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1293 trim_whitespace($_);
1294 $self->get_aliases($_) if $_;
1298 sub OVERLOAD_handler {
1302 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1304 trim_whitespace($_);
1305 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1306 $self->{Overload} = 1 unless $self->{Overload};
1307 my $overload = "$Package\::(".$1;
1308 push(@{ $self->{InitFileCode} },
1309 " (void)$self->{newXS}(\"$overload\", XS_$Full_func_name, file$self->{proto});\n");
1314 sub FALLBACK_handler {
1318 # the rest of the current line should contain either TRUE,
1321 trim_whitespace($_);
1323 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1324 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1325 UNDEF => "&PL_sv_undef",
1328 # check for valid FALLBACK value
1329 $self->death("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1331 $self->{Fallback} = $map{uc $_};
1335 sub REQUIRE_handler {
1337 # the rest of the current line should contain a version number
1340 trim_whitespace($Ver);
1342 $self->death("Error: REQUIRE expects a version number")
1345 # check that the version number is of the form n.n
1346 $self->death("Error: REQUIRE: expected a number, got '$Ver'")
1347 unless $Ver =~ /^\d+(\.\d*)?/;
1349 $self->death("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1350 unless $VERSION >= $Ver;
1353 sub VERSIONCHECK_handler {
1357 # the rest of the current line should contain either ENABLE or
1360 trim_whitespace($_);
1362 # check for ENABLE/DISABLE
1363 $self->death("Error: VERSIONCHECK: ENABLE/DISABLE")
1364 unless /^(ENABLE|DISABLE)/i;
1366 $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1367 $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
1371 sub PROTOTYPE_handler {
1377 $self->death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1378 if $self->{proto_in_this_xsub}++;
1380 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1383 trim_whitespace($_);
1384 if ($_ eq 'DISABLE') {
1385 $self->{ProtoThisXSUB} = 0;
1387 elsif ($_ eq 'ENABLE') {
1388 $self->{ProtoThisXSUB} = 1;
1391 # remove any whitespace
1393 $self->death("Error: Invalid prototype '$_'")
1394 unless valid_proto_string($_);
1395 $self->{ProtoThisXSUB} = C_string($_);
1399 # If no prototype specified, then assume empty prototype ""
1400 $self->{ProtoThisXSUB} = 2 unless $specified;
1402 $self->{ProtoUsed} = 1;
1409 $self->death("Error: Only 1 SCOPE declaration allowed per xsub")
1410 if $self->{scope_in_this_xsub}++;
1412 trim_whitespace($_);
1413 $self->death("Error: SCOPE: ENABLE/DISABLE")
1414 unless /^(ENABLE|DISABLE)\b/i;
1415 $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
1418 sub PROTOTYPES_handler {
1422 # the rest of the current line should contain either ENABLE or
1425 trim_whitespace($_);
1427 # check for ENABLE/DISABLE
1428 $self->death("Error: PROTOTYPES: ENABLE/DISABLE")
1429 unless /^(ENABLE|DISABLE)/i;
1431 $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1432 $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
1433 $self->{ProtoUsed} = 1;
1439 # Save the current file context.
1440 push(@{ $self->{XSStack} }, {
1442 LastLine => $self->{lastline},
1443 LastLineNo => $self->{lastline_no},
1444 Line => $self->{line},
1445 LineNo => $self->{line_no},
1446 Filename => $self->{filename},
1447 Filepathname => $self->{filepathname},
1448 Handle => $self->{FH},
1449 IsPipe => scalar($self->{filename} =~ /\|\s*$/),
1455 sub INCLUDE_handler {
1458 # the rest of the current line should contain a valid filename
1460 trim_whitespace($_);
1462 $self->death("INCLUDE: filename missing")
1465 $self->death("INCLUDE: output pipe is illegal")
1468 # simple minded recursion detector
1469 $self->death("INCLUDE loop detected")
1470 if $self->{IncludedFiles}->{$_};
1472 ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
1474 if (/\|\s*$/ && /^\s*perl\s/) {
1475 Warn( $self, "The INCLUDE directive with a command is discouraged." .
1476 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1477 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1478 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1479 " the use of \$^X as the currently running perl, see" .
1480 " 'perldoc perlxs' for details.");
1483 $self->PushXSStack();
1485 $self->{FH} = Symbol::gensym();
1488 open ($self->{FH}, '<', $_) or $self->death("Cannot open '$_': $!");
1492 #/* INCLUDE: Including '$_' from '$self->{filename}' */
1496 $self->{filename} = $_;
1497 $self->{filepathname} = File::Spec->catfile($self->{dir}, $self->{filename});
1499 # Prime the pump by reading the first
1502 # skip leading blank lines
1503 while (readline($self->{FH})) {
1504 last unless /^\s*$/;
1507 $self->{lastline} = $_;
1508 $self->{lastline_no} = $.;
1513 my @args = split /\s+/, $cmd;
1516 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1518 return join (' ', ($cmd, @args));
1521 sub INCLUDE_COMMAND_handler {
1524 # the rest of the current line should contain a valid command
1526 trim_whitespace($_);
1528 $_ = QuoteArgs($_) if $^O eq 'VMS';
1530 $self->death("INCLUDE_COMMAND: command missing")
1533 $self->death("INCLUDE_COMMAND: pipes are illegal")
1534 if /^\s*\|/ or /\|\s*$/;
1536 $self->PushXSStack( IsPipe => 1 );
1538 $self->{FH} = Symbol::gensym();
1540 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1541 # the same perl interpreter as we're currently running
1545 open ($self->{FH}, "-|", $_)
1546 or $self->death( $self, "Cannot run command '$_' to include its output: $!");
1550 #/* INCLUDE_COMMAND: Including output of '$_' from '$self->{filename}' */
1554 $self->{filename} = $_;
1555 $self->{filepathname} = $self->{filename};
1556 $self->{filepathname} =~ s/\"/\\"/g;
1558 # Prime the pump by reading the first
1561 # skip leading blank lines
1562 while (readline($self->{FH})) {
1563 last unless /^\s*$/;
1566 $self->{lastline} = $_;
1567 $self->{lastline_no} = $.;
1573 return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
1575 my $data = pop @{ $self->{XSStack} };
1576 my $ThisFile = $self->{filename};
1577 my $isPipe = $data->{IsPipe};
1579 --$self->{IncludedFiles}->{$self->{filename}}
1584 $self->{FH} = $data->{Handle};
1585 # $filename is the leafname, which for some reason isused for diagnostic
1586 # messages, whereas $filepathname is the full pathname, and is used for
1588 $self->{filename} = $data->{Filename};
1589 $self->{filepathname} = $data->{Filepathname};
1590 $self->{lastline} = $data->{LastLine};
1591 $self->{lastline_no} = $data->{LastLineNo};
1592 @{ $self->{line} } = @{ $data->{Line} };
1593 @{ $self->{line_no} } = @{ $data->{LineNo} };
1595 if ($isPipe and $? ) {
1596 --$self->{lastline_no};
1597 print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
1603 #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
1613 $text =~ s/\[\[/{/g;
1614 $text =~ s/\]\]/}/g;
1618 # Read next xsub into @{ $self->{line} } from ($lastline, readline($self->{FH})).
1623 $self->death("Error: Unterminated `#if/#ifdef/#ifndef'")
1624 if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if';
1625 @{ $self->{line} } = ();
1626 @{ $self->{line_no} } = ();
1627 return $self->PopFile() if !defined $self->{lastline};
1629 if ($self->{lastline} =~
1630 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1632 $Package = defined($2) ? $2 : ''; # keep -w happy
1633 $self->{Prefix} = defined($3) ? $3 : ''; # keep -w happy
1634 $self->{Prefix} = quotemeta $self->{Prefix};
1635 ($self->{Module_cname} = $Module) =~ s/\W/_/g;
1636 ($self->{Packid} = $Package) =~ tr/:/_/;
1637 $self->{Packprefix} = $Package;
1638 $self->{Packprefix} .= "::" if $self->{Packprefix} ne "";
1639 $self->{lastline} = "";
1643 # Skip embedded PODs
1644 while ($self->{lastline} =~ /^=/) {
1645 while ($self->{lastline} = readline($self->{FH})) {
1646 last if ($self->{lastline} =~ /^=cut\s*$/);
1648 $self->death("Error: Unterminated pod") unless $self->{lastline};
1649 $self->{lastline} = readline($self->{FH});
1650 chomp $self->{lastline};
1651 $self->{lastline} =~ s/^\s+$//;
1654 # This chunk of code strips out (and parses) embedded TYPEMAP blocks
1655 # which support a HEREdoc-alike block syntax.
1656 # This is special cased from the usual paragraph-handler logic
1657 # due to the HEREdoc-ish syntax.
1658 if ($self->{lastline} =~ /^TYPEMAP\s*:\s*<<\s*(?:(["'])(.+?)\1|([^\s'"]+))\s*;?\s*$/) {
1659 my $end_marker = quotemeta(defined($1) ? $2 : $3);
1662 $self->{lastline} = readline($self->{FH});
1663 $self->death("Error: Unterminated typemap") if not defined $self->{lastline};
1664 last if $self->{lastline} =~ /^$end_marker\s*$/;
1665 push @tmaplines, $self->{lastline};
1668 my $tmapcode = join "", @tmaplines;
1669 my $tmap = ExtUtils::Typemaps->new(
1670 string => $tmapcode,
1671 lineno_offset => $self->current_line_number()+1,
1672 fake_filename => $self->{filename},
1674 $self->{typemap}->merge(typemap => $tmap, replace => 1);
1676 last unless defined($self->{lastline} = readline($self->{FH}));
1680 if ($self->{lastline} !~ /^\s*#/ ||
1682 # ANSI: if ifdef ifndef elif else endif define undef
1684 # gcc: warning include_next
1686 # others: ident (gcc notes that some cpps have this one)
1687 $self->{lastline} =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1688 last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq "";
1689 push(@{ $self->{line} }, $self->{lastline});
1690 push(@{ $self->{line_no} }, $self->{lastline_no});
1693 # Read next line and continuation lines
1694 last unless defined($self->{lastline} = readline($self->{FH}));
1695 $self->{lastline_no} = $.;
1697 $self->{lastline} .= $tmp_line
1698 while ($self->{lastline} =~ /\\$/ && defined($tmp_line = readline($self->{FH})));
1700 chomp $self->{lastline};
1701 $self->{lastline} =~ s/^\s+$//;
1703 pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq "";
1708 my $argsref = shift;
1709 my ($type, $num, $var, $init, $printed_name) = (
1714 $argsref->{printed_name}
1716 my $arg = "ST(" . ($num - 1) . ")";
1718 if ( $init =~ /^=/ ) {
1719 if ($printed_name) {
1720 eval qq/print " $init\\n"/;
1723 eval qq/print "\\t$var $init\\n"/;
1728 if ( $init =~ s/^\+// && $num ) {
1733 printed_name => $printed_name,
1736 elsif ($printed_name) {
1741 eval qq/print "\\t$var;\\n"/;
1745 $self->{deferred} .= eval qq/"\\n\\t$init\\n"/;
1751 my $argsref = shift;
1752 my ($type, $num, $var, $printed_name) = (
1756 $argsref->{printed_name},
1758 my $arg = "ST(" . ($num - 1) . ")";
1759 my ($argoff, $ntype);
1762 my $typemaps = $self->{typemap};
1764 $type = tidy_type($type);
1765 $self->blurt("Error: '$type' not in typemap"), return
1766 unless $typemaps->get_typemap(ctype => $type);
1768 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1770 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1771 my $typem = $typemaps->get_typemap(ctype => $type);
1772 my $xstype = $typem->xstype;
1773 $xstype =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1774 if ($xstype eq 'T_PV' and exists $self->{lengthof}->{$var}) {
1775 print "\t$var" unless $printed_name;
1776 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1777 die "default value not supported with length(NAME) supplied"
1778 if defined $self->{defaults}->{$var};
1781 $type =~ tr/:/_/ unless $self->{hiertype};
1783 my $inputmap = $typemaps->get_inputmap(xstype => $xstype);
1784 $self->blurt("Error: No INPUT definition for type '$type', typekind '" . $type->xstype . "' found"), return
1785 unless defined $inputmap;
1787 my $expr = $inputmap->cleaned_code;
1788 # Note: This gruesome bit either needs heavy rethinking or documentation. I vote for the former. --Steffen
1789 if ($expr =~ /DO_ARRAY_ELEM/) {
1790 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1791 $self->blurt("Error: C type '$subtype' not in typemap"), return
1793 my $subinputmap = $typemaps->get_inputmap(xstype => $subtypemap->xstype);
1794 $self->blurt("Error: No INPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1795 unless $subinputmap;
1796 my $subexpr = $subinputmap->cleaned_code;
1797 $subexpr =~ s/\$type/\$subtype/g;
1798 $subexpr =~ s/ntype/subtype/g;
1799 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1800 $subexpr =~ s/\n\t/\n\t\t/g;
1801 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1802 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1803 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1805 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1806 $self->{ScopeThisXSUB} = 1;
1808 if (defined($self->{defaults}->{$var})) {
1809 $expr =~ s/(\t+)/$1 /g;
1811 if ($printed_name) {
1815 eval qq/print "\\t$var;\\n"/;
1818 if ($self->{defaults}->{$var} eq 'NO_INIT') {
1819 $self->{deferred} .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1822 $self->{deferred} .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1826 elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
1827 if ($printed_name) {
1831 eval qq/print "\\t$var;\\n"/;
1834 $self->{deferred} .= eval qq/"\\n$expr;\\n"/;
1838 die "panic: do not know how to handle this branch for function pointers"
1840 eval qq/print "$expr;\\n"/;
1845 sub generate_output {
1846 my $argsref = shift;
1847 my ($type, $num, $var, $do_setmagic, $do_push) = (
1851 $argsref->{do_setmagic},
1854 my $arg = "ST(" . ($num - ($num != 0)) . ")";
1857 my $typemaps = $self->{typemap};
1859 $type = tidy_type($type);
1860 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1861 print "\t$arg = sv_newmortal();\n";
1862 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1863 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1866 my $typemap = $typemaps->get_typemap(ctype => $type);
1867 $self->blurt("Could not find a typemap for C type '$type'"), return
1869 my $outputmap = $typemaps->get_outputmap(xstype => $typemap->xstype);
1870 $self->blurt("Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found"), return
1872 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1873 $ntype =~ s/\(\)//g;
1875 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1877 my $expr = $outputmap->cleaned_code;
1878 if ($expr =~ /DO_ARRAY_ELEM/) {
1879 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1880 $self->blurt("Could not find a typemap for C type '$subtype'"), return
1882 my $suboutputmap = $typemaps->get_outputmap(xstype => $subtypemap->xstype);
1883 $self->blurt("Error: No OUTPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1884 unless $suboutputmap;
1885 my $subexpr = $suboutputmap->cleaned_code;
1886 $subexpr =~ s/ntype/subtype/g;
1887 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1888 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1889 $subexpr =~ s/\n\t/\n\t\t/g;
1890 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1891 eval "print qq\a$expr\a";
1893 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1895 elsif ($var eq 'RETVAL') {
1896 if ($expr =~ /^\t\$arg = new/) {
1897 # We expect that $arg has refcnt 1, so we need to
1899 eval "print qq\a$expr\a";
1901 print "\tsv_2mortal(ST($num));\n";
1902 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1904 elsif ($expr =~ /^\s*\$arg\s*=/) {
1905 # We expect that $arg has refcnt >=1, so we need
1907 eval "print qq\a$expr\a";
1909 print "\tsv_2mortal(ST(0));\n";
1910 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1913 # Just hope that the entry would safely write it
1914 # over an already mortalized value. By
1915 # coincidence, something like $arg = &sv_undef
1917 print "\tST(0) = sv_newmortal();\n";
1918 eval "print qq\a$expr\a";
1920 # new mortals don't have set magic
1924 print "\tPUSHs(sv_newmortal());\n";
1926 eval "print qq\a$expr\a";
1928 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1930 elsif ($arg =~ /^ST\(\d+\)$/) {
1931 eval "print qq\a$expr\a";
1933 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1940 # vim: ts=2 sw=2 et: