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 foreach my $member (qw(args_match var_types defaults arg_list
283 argtype_seen in_out lengthof))
285 $self->{$member} = {};
287 $self->{proto_arg} = [];
288 $self->{processing_arg_with_types} = undef;
289 $self->{proto_in_this_xsub} = undef;
290 $self->{scope_in_this_xsub} = undef;
291 $self->{interface} = undef;
292 $self->{interface_macro} = 'XSINTERFACE_FUNC';
293 $self->{interface_macro_set} = 'XSINTERFACE_FUNC_SET';
294 $self->{ProtoThisXSUB} = $self->{WantPrototypes};
295 $self->{ScopeThisXSUB} = 0;
299 $_ = shift(@{ $self->{line} });
300 while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
301 my $method = $kwd . "_handler";
303 next PARAGRAPH unless @{ $self->{line} };
304 $_ = shift(@{ $self->{line} });
307 if ($self->check_keyword("BOOT")) {
308 check_conditional_preprocessor_statements($self);
309 push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \"$self->{filepathname}\"")
310 if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/;
311 push (@{ $BootCode_ref }, @{ $self->{line} }, "");
315 # extract return type, function name and arguments
316 ($self->{ret_type}) = tidy_type($_);
317 my $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//;
319 # Allow one-line ANSI-like declaration
320 unshift @{ $self->{line} }, $2
322 and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
324 # a function definition needs at least 2 lines
325 blurt( $self, "Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH
326 unless @{ $self->{line} };
328 my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
329 my $static = 1 if $self->{ret_type} =~ s/^static\s+//;
331 my $func_header = shift(@{ $self->{line} });
332 blurt( $self, "Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
333 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
335 my ($class, $orig_args);
336 ($class, $func_name, $orig_args) = ($1, $2, $3);
337 $class = "$4 $class" if $4;
338 ($pname = $func_name) =~ s/^($self->{Prefix})?/$self->{Packprefix}/;
340 ($clean_func_name = $func_name) =~ s/^$self->{Prefix}//;
341 $Full_func_name = "$self->{Packid}_$clean_func_name";
343 $Full_func_name = $SymSet->addsym($Full_func_name);
346 # Check for duplicate function definition
347 for my $tmp (@{ $self->{XSStack} }) {
348 next unless defined $tmp->{functions}{$Full_func_name};
349 Warn( $self, "Warning: duplicate function definition '$clean_func_name' detected");
352 $self->{XSStack}->[$XSS_work_idx]{functions}{$Full_func_name}++;
353 %{ $self->{XsubAliases} } = ();
354 %{ $self->{XsubAliasValues} } = ();
355 %{ $self->{Interfaces} } = ();
356 @{ $self->{Attributes} } = ();
357 $self->{DoSetMagic} = 1;
359 $orig_args =~ s/\\\s*/ /g; # process line continuations
362 my (@fake_INPUT_pre); # For length(s) generated variables
364 my $only_C_inlist_ref = {}; # Not in the signature of Perl function
365 if ($self->{argtypes} and $orig_args =~ /\S/) {
366 my $args = "$orig_args ,";
367 if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
368 @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
372 my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
373 my ($pre, $len_name) = ($arg =~ /(.*?) \s*
374 \b ( \w+ | length\( \s*\w+\s* \) )
376 next unless defined($pre) && length($pre);
379 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
381 $out_type = $type if $type ne 'IN';
382 $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
383 $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
386 if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
387 $len_name = "XSauto_length_of_$1";
389 die "Default value on length() argument: `$_'"
392 if (length $pre or $islength) { # Has a type
394 push @fake_INPUT_pre, $arg;
397 push @fake_INPUT, $arg;
399 # warn "pushing '$arg'\n";
400 $self->{argtype_seen}->{$len_name}++;
401 $_ = "$len_name$default"; # Assigns to @args
403 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST" or $islength;
404 push @{ $outlist_ref }, $len_name if $out_type =~ /OUTLIST$/;
405 $self->{in_out}->{$len_name} = $out_type if $out_type;
409 @args = split(/\s*,\s*/, $orig_args);
410 Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split");
414 @args = split(/\s*,\s*/, $orig_args);
416 if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
418 next if $out_type eq 'IN';
419 $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST";
420 if ($out_type =~ /OUTLIST$/) {
421 push @{ $outlist_ref }, undef;
423 $self->{in_out}->{$_} = $out_type;
427 if (defined($class)) {
428 my $arg0 = ((defined($static) or $func_name eq 'new')
430 unshift(@args, $arg0);
435 my $report_args = '';
437 foreach my $i (0 .. $#args) {
438 if ($args[$i] =~ s/\.\.\.//) {
440 if ($args[$i] eq '' && $i == $#args) {
441 $report_args .= ", ...";
446 if ($only_C_inlist_ref->{$args[$i]}) {
447 push @args_num, undef;
450 push @args_num, ++$num_args;
451 $report_args .= ", $args[$i]";
453 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
456 $self->{defaults}->{$args[$i]} = $2;
457 $self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
459 $self->{proto_arg}->[$i+1] = '$';
461 my $min_args = $num_args - $extra_args;
462 $report_args =~ s/"/\\"/g;
463 $report_args =~ s/^,\s+//;
464 $self->{func_args} = assign_func_args($self, \@args, $class);
465 @{ $self->{args_match} }{@args} = @args_num;
467 my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} });
468 my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} });
469 # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
470 # to set explicit return values.
471 my $EXPLICIT_RETURN = ($CODE &&
472 ("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
474 # The $ALIAS which follows is only explicitly called within the scope of
475 # process_file(). In principle, it ought to be a lexical, i.e., 'my
476 # $ALIAS' like the other nearby variables. However, implementing that
477 # change produced a slight difference in the resulting .c output in at
478 # least two distributions: B/BD/BDFOY/Crypt-Rijndael and
479 # G/GF/GFUJI/Hash-FieldHash. The difference is, arguably, an improvement
480 # in the resulting C code. Example:
482 # < GvNAME(CvGV(cv)),
484 # > "Crypt::Rijndael::encrypt",
485 # But at this point we're committed to generating the *same* C code that
486 # the current version of ParseXS.pm does. So we're declaring it as 'our'.
487 $ALIAS = grep(/^\s*ALIAS\s*:/, @{ $self->{line} });
489 my $INTERFACE = grep(/^\s*INTERFACE\s*:/, @{ $self->{line} });
491 $xsreturn = 1 if $EXPLICIT_RETURN;
493 $externC = $externC ? qq[extern "C"] : "";
495 # print function header
498 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
499 #XS(XS_${Full_func_name})
507 print Q(<<"EOF") if $ALIAS;
510 print Q(<<"EOF") if $INTERFACE;
511 # dXSFUNCTION($self->{ret_type});
514 $self->{cond} = set_cond($ellipsis, $min_args, $num_args);
516 print Q(<<"EOF") if $self->{except};
524 # croak_xs_usage(cv, "$report_args");
528 # cv likely to be unused
530 # PERL_UNUSED_VAR(cv); /* -W */
534 #gcc -Wall: if an xsub has PPCODE is used
535 #it is possible none of ST, XSRETURN or XSprePUSH macros are used
536 #hence `ax' (setup by dXSARGS) is unused
537 #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
538 #but such a move could break third-party extensions
539 print Q(<<"EOF") if $PPCODE;
540 # PERL_UNUSED_VAR(ax); /* -Wall */
543 print Q(<<"EOF") if $PPCODE;
547 # Now do a block of some sort.
549 $self->{condnum} = 0;
550 $self->{cond} = ''; # last CASE: conditional
551 push(@{ $self->{line} }, "$END:");
552 push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
554 check_conditional_preprocessor_statements();
555 while (@{ $self->{line} }) {
556 $self->CASE_handler($_) if $self->check_keyword("CASE");
561 # do initialization of input variables
562 $self->{thisdone} = 0;
563 $self->{retvaldone} = 0;
564 $self->{deferred} = "";
565 %{ $self->{arg_list} } = ();
566 $self->{gotRETVAL} = 0;
568 $self->INPUT_handler($_);
569 $self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
571 print Q(<<"EOF") if $self->{ScopeThisXSUB};
576 if (!$self->{thisdone} && defined($class)) {
577 if (defined($static) or $func_name eq 'new') {
579 $self->{var_types}->{"CLASS"} = "char *";
584 printed_name => undef,
589 $self->{var_types}->{"THIS"} = "$class *";
594 printed_name => undef,
601 if (/^\s*NOT_IMPLEMENTED_YET/) {
602 print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
606 if ($self->{ret_type} ne "void") {
607 print "\t" . map_type($self, $self->{ret_type}, 'RETVAL') . ";\n"
608 if !$self->{retvaldone};
609 $self->{args_match}->{"RETVAL"} = 0;
610 $self->{var_types}->{"RETVAL"} = $self->{ret_type};
611 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
613 if $self->{optimize} and $outputmap and $outputmap->targetable;
616 if (@fake_INPUT or @fake_INPUT_pre) {
617 unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
619 $self->{processing_arg_with_types} = 1;
620 $self->INPUT_handler($_);
622 print $self->{deferred};
624 $self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
626 if ($self->check_keyword("PPCODE")) {
627 $self->print_section();
628 death( $self, "PPCODE must be last thing") if @{ $self->{line} };
629 print "\tLEAVE;\n" if $self->{ScopeThisXSUB};
630 print "\tPUTBACK;\n\treturn;\n";
632 elsif ($self->check_keyword("CODE")) {
633 $self->print_section();
635 elsif (defined($class) and $func_name eq "DESTROY") {
637 print "delete THIS;\n";
641 if ($self->{ret_type} ne "void") {
645 if (defined($static)) {
646 if ($func_name eq 'new') {
647 $func_name = "$class";
653 elsif (defined($class)) {
654 if ($func_name eq 'new') {
655 $func_name .= " $class";
661 $func_name =~ s/^\Q$args{'s'}//
662 if exists $args{'s'};
663 $func_name = 'XSFUNCTION' if $self->{interface};
664 print "$func_name($self->{func_args});\n";
668 # do output variables
669 $self->{gotRETVAL} = 0; # 1 if RETVAL seen in OUTPUT section;
670 undef $self->{RETVAL_code} ; # code to set RETVAL (from OUTPUT section);
671 # $wantRETVAL set if 'RETVAL =' autogenerated
672 ($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return;
673 undef %{ $self->{outargs} };
674 $self->process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
677 type => $self->{var_types}->{$_},
678 num => $self->{args_match}->{$_},
680 do_setmagic => $self->{DoSetMagic},
682 } ) for grep $self->{in_out}->{$_} =~ /OUT$/, keys %{ $self->{in_out} };
685 # all OUTPUT done, so now push the return value on the stack
686 if ($self->{gotRETVAL} && $self->{RETVAL_code}) {
687 print "\t$self->{RETVAL_code}\n";
689 elsif ($self->{gotRETVAL} || $wantRETVAL) {
690 my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
691 my $t = $self->{optimize} && $outputmap && $outputmap->targetable;
692 # Although the '$var' declared in the next line is never explicitly
693 # used within this 'elsif' block, commenting it out leads to
694 # disaster, starting with the first 'eval qq' inside the 'elsif' block
696 # It appears that this is related to the fact that at this point the
697 # value of $t is a reference to an array whose [2] element includes
698 # '$var' as a substring:
701 my $type = $self->{ret_type};
703 if ($t and not $t->{with_size} and $t->{type} eq 'p') {
704 # PUSHp corresponds to setpvn. Treat setpv directly
705 my $what = eval qq("$t->{what}");
708 print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
712 my $what = eval qq("$t->{what}");
715 my $tsize = $t->{what_size};
716 $tsize = '' unless defined $tsize;
717 $tsize = eval qq("$tsize");
719 print "\tXSprePUSH; PUSH$t->{type}($what$tsize);\n";
723 # RETVAL almost never needs SvSETMAGIC()
725 type => $self->{ret_type},
734 $xsreturn = 1 if $self->{ret_type} ne "void";
736 my $c = @{ $outlist_ref };
737 print "\tXSprePUSH;" if $c and not $prepush_done;
738 print "\tEXTEND(SP,$c);\n" if $c;
741 type => $self->{var_types}->{$_},
746 } ) for @{ $outlist_ref };
749 $self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
751 print Q(<<"EOF") if $self->{ScopeThisXSUB};
754 print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
758 # print function trailer
762 print Q(<<"EOF") if $self->{except};
765 # sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
768 if ($self->check_keyword("CASE")) {
769 blurt( $self, "Error: No `CASE:' at top of function")
770 unless $self->{condnum};
771 $_ = "CASE: $_"; # Restore CASE: label
774 last if $_ eq "$END:";
776 /^$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 blurt( $self, "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 blurt( $self, "Error: invalid argument declaration '$ln'"), next;
1075 # Check for duplicate definitions
1076 blurt( $self, "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->{proto_arg}->[$self->{var_num}] = ($typemap && $typemap->proto) || "\$";
1102 $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr;
1103 if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1104 or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/
1105 and $var_init !~ /\S/) {
1106 if ($printed_name) {
1110 print "\t$var_name;\n";
1113 elsif ($var_init =~ /\S/) {
1116 num => $self->{var_num},
1119 printed_name => $printed_name,
1122 elsif ($self->{var_num}) {
1125 num => $self->{var_num},
1127 printed_name => $printed_name,
1136 sub OUTPUT_handler {
1139 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1141 if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1142 $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
1145 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1146 blurt( $self, "Error: duplicate OUTPUT argument '$outarg' ignored"), next
1147 if $self->{outargs}->{$outarg}++;
1148 if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') {
1149 # deal with RETVAL last
1150 $self->{RETVAL_code} = $outcode;
1151 $self->{gotRETVAL} = 1;
1154 blurt( $self, "Error: OUTPUT $outarg not an argument"), next
1155 unless defined($self->{args_match}->{$outarg});
1156 blurt( $self, "Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1157 unless defined $self->{var_types}->{$outarg};
1158 $self->{var_num} = $self->{args_match}->{$outarg};
1160 print "\t$outcode\n";
1161 print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
1165 type => $self->{var_types}->{$outarg},
1166 num => $self->{var_num},
1168 do_setmagic => $self->{DoSetMagic},
1172 delete $self->{in_out}->{$outarg} # No need to auto-OUTPUT
1173 if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
1177 sub C_ARGS_handler {
1180 my $in = $self->merge_section();
1182 trim_whitespace($in);
1183 $self->{func_args} = $in;
1186 sub INTERFACE_MACRO_handler {
1189 my $in = $self->merge_section();
1191 trim_whitespace($in);
1192 if ($in =~ /\s/) { # two
1193 ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
1196 $self->{interface_macro} = $in;
1197 $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
1199 $self->{interface} = 1; # local
1200 $self->{interfaces} = 1; # global
1203 sub INTERFACE_handler {
1206 my $in = $self->merge_section();
1208 trim_whitespace($in);
1210 foreach (split /[\s,]+/, $in) {
1211 my $iface_name = $_;
1212 $iface_name =~ s/^$self->{Prefix}//;
1213 $self->{Interfaces}->{$iface_name} = $_;
1216 # XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
1218 $self->{interface} = 1; # local
1219 $self->{interfaces} = 1; # global
1222 sub CLEANUP_handler {
1224 $self->print_section();
1227 sub PREINIT_handler {
1229 $self->print_section();
1232 sub POSTCALL_handler {
1234 $self->print_section();
1239 $self->print_section();
1247 # Parse alias definitions
1249 # alias = value alias = value ...
1251 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1252 my ($alias, $value) = ($1, $2);
1253 my $orig_alias = $alias;
1255 # check for optional package definition in the alias
1256 $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
1258 # check for duplicate alias name & duplicate value
1259 Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'")
1260 if defined $self->{XsubAliases}->{$alias};
1262 Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
1263 if $self->{XsubAliasValues}->{$value};
1265 $self->{xsubaliases} = 1;
1266 $self->{XsubAliases}->{$alias} = $value;
1267 $self->{XsubAliasValues}->{$value} = $orig_alias;
1270 blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'")
1278 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1280 trim_whitespace($_);
1281 push @{ $self->{Attributes} }, $_;
1289 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1291 trim_whitespace($_);
1292 $self->get_aliases($_) if $_;
1296 sub OVERLOAD_handler {
1300 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1302 trim_whitespace($_);
1303 while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1304 $self->{Overload} = 1 unless $self->{Overload};
1305 my $overload = "$Package\::(".$1;
1306 push(@{ $self->{InitFileCode} },
1307 " (void)$self->{newXS}(\"$overload\", XS_$Full_func_name, file$self->{proto});\n");
1312 sub FALLBACK_handler {
1316 # the rest of the current line should contain either TRUE,
1319 trim_whitespace($_);
1321 TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1322 FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1323 UNDEF => "&PL_sv_undef",
1326 # check for valid FALLBACK value
1327 death( $self, "Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1329 $self->{Fallback} = $map{uc $_};
1333 sub REQUIRE_handler {
1335 # the rest of the current line should contain a version number
1338 trim_whitespace($Ver);
1340 death( $self, "Error: REQUIRE expects a version number")
1343 # check that the version number is of the form n.n
1344 death( $self, "Error: REQUIRE: expected a number, got '$Ver'")
1345 unless $Ver =~ /^\d+(\.\d*)?/;
1347 death( $self, "Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1348 unless $VERSION >= $Ver;
1351 sub VERSIONCHECK_handler {
1355 # the rest of the current line should contain either ENABLE or
1358 trim_whitespace($_);
1360 # check for ENABLE/DISABLE
1361 death( $self, "Error: VERSIONCHECK: ENABLE/DISABLE")
1362 unless /^(ENABLE|DISABLE)/i;
1364 $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1365 $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
1369 sub PROTOTYPE_handler {
1375 death( $self, "Error: Only 1 PROTOTYPE definition allowed per xsub")
1376 if $self->{proto_in_this_xsub}++;
1378 for (; !/^$self->{BLOCK_re}/o; $_ = shift(@{ $self->{line} })) {
1381 trim_whitespace($_);
1382 if ($_ eq 'DISABLE') {
1383 $self->{ProtoThisXSUB} = 0;
1385 elsif ($_ eq 'ENABLE') {
1386 $self->{ProtoThisXSUB} = 1;
1389 # remove any whitespace
1391 death( $self, "Error: Invalid prototype '$_'")
1392 unless valid_proto_string($_);
1393 $self->{ProtoThisXSUB} = C_string($_);
1397 # If no prototype specified, then assume empty prototype ""
1398 $self->{ProtoThisXSUB} = 2 unless $specified;
1400 $self->{ProtoUsed} = 1;
1407 death( $self, "Error: Only 1 SCOPE declaration allowed per xsub")
1408 if $self->{scope_in_this_xsub}++;
1410 trim_whitespace($_);
1411 death("Error: SCOPE: ENABLE/DISABLE")
1412 unless /^(ENABLE|DISABLE)\b/i;
1413 $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
1416 sub PROTOTYPES_handler {
1420 # the rest of the current line should contain either ENABLE or
1423 trim_whitespace($_);
1425 # check for ENABLE/DISABLE
1426 death("Error: PROTOTYPES: ENABLE/DISABLE")
1427 unless /^(ENABLE|DISABLE)/i;
1429 $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1430 $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
1431 $self->{ProtoUsed} = 1;
1437 # Save the current file context.
1438 push(@{ $self->{XSStack} }, {
1440 LastLine => $self->{lastline},
1441 LastLineNo => $self->{lastline_no},
1442 Line => $self->{line},
1443 LineNo => $self->{line_no},
1444 Filename => $self->{filename},
1445 Filepathname => $self->{filepathname},
1447 IsPipe => scalar($self->{filename} =~ /\|\s*$/),
1453 sub INCLUDE_handler {
1456 # the rest of the current line should contain a valid filename
1458 trim_whitespace($_);
1460 death( $self, "INCLUDE: filename missing")
1463 death( $self, "INCLUDE: output pipe is illegal")
1466 # simple minded recursion detector
1467 death( $self, "INCLUDE loop detected")
1468 if $self->{IncludedFiles}->{$_};
1470 ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
1472 if (/\|\s*$/ && /^\s*perl\s/) {
1473 Warn( $self, "The INCLUDE directive with a command is discouraged." .
1474 " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1475 " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1476 " up the correct perl. The INCLUDE_COMMAND directive allows" .
1477 " the use of \$^X as the currently running perl, see" .
1478 " 'perldoc perlxs' for details.");
1481 $self->PushXSStack();
1483 $FH = Symbol::gensym();
1486 open ($FH, "$_") or death( $self, "Cannot open '$_': $!");
1490 #/* INCLUDE: Including '$_' from '$self->{filename}' */
1494 $self->{filename} = $_;
1495 $self->{filepathname} = File::Spec->catfile($self->{dir}, $self->{filename});
1497 # Prime the pump by reading the first
1500 # skip leading blank lines
1502 last unless /^\s*$/;
1505 $self->{lastline} = $_;
1506 $self->{lastline_no} = $.;
1511 my @args = split /\s+/, $cmd;
1514 $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1516 return join (' ', ($cmd, @args));
1519 sub INCLUDE_COMMAND_handler {
1522 # the rest of the current line should contain a valid command
1524 trim_whitespace($_);
1526 $_ = QuoteArgs($_) if $^O eq 'VMS';
1528 death( $self, "INCLUDE_COMMAND: command missing")
1531 death( $self, "INCLUDE_COMMAND: pipes are illegal")
1532 if /^\s*\|/ or /\|\s*$/;
1534 $self->PushXSStack( IsPipe => 1 );
1536 $FH = Symbol::gensym();
1538 # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1539 # the same perl interpreter as we're currently running
1543 open ($FH, "-|", "$_")
1544 or death( $self, "Cannot run command '$_' to include its output: $!");
1548 #/* INCLUDE_COMMAND: Including output of '$_' from '$self->{filename}' */
1552 $self->{filename} = $_;
1553 $self->{filepathname} = $self->{filename};
1554 $self->{filepathname} =~ s/\"/\\"/g;
1556 # Prime the pump by reading the first
1559 # skip leading blank lines
1561 last unless /^\s*$/;
1564 $self->{lastline} = $_;
1565 $self->{lastline_no} = $.;
1571 return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
1573 my $data = pop @{ $self->{XSStack} };
1574 my $ThisFile = $self->{filename};
1575 my $isPipe = $data->{IsPipe};
1577 --$self->{IncludedFiles}->{$self->{filename}}
1582 $FH = $data->{Handle};
1583 # $filename is the leafname, which for some reason isused for diagnostic
1584 # messages, whereas $filepathname is the full pathname, and is used for
1586 $self->{filename} = $data->{Filename};
1587 $self->{filepathname} = $data->{Filepathname};
1588 $self->{lastline} = $data->{LastLine};
1589 $self->{lastline_no} = $data->{LastLineNo};
1590 @{ $self->{line} } = @{ $data->{Line} };
1591 @{ $self->{line_no} } = @{ $data->{LineNo} };
1593 if ($isPipe and $? ) {
1594 --$self->{lastline_no};
1595 print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
1601 #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
1611 $text =~ s/\[\[/{/g;
1612 $text =~ s/\]\]/}/g;
1616 # Read next xsub into @{ $self->{line} } from ($lastline, <$FH>).
1621 death("Error: Unterminated `#if/#ifdef/#ifndef'")
1622 if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if';
1623 @{ $self->{line} } = ();
1624 @{ $self->{line_no} } = ();
1625 return $self->PopFile() if !defined $self->{lastline};
1627 if ($self->{lastline} =~
1628 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1630 $Package = defined($2) ? $2 : ''; # keep -w happy
1631 $self->{Prefix} = defined($3) ? $3 : ''; # keep -w happy
1632 $self->{Prefix} = quotemeta $self->{Prefix};
1633 ($self->{Module_cname} = $Module) =~ s/\W/_/g;
1634 ($self->{Packid} = $Package) =~ tr/:/_/;
1635 $self->{Packprefix} = $Package;
1636 $self->{Packprefix} .= "::" if $self->{Packprefix} ne "";
1637 $self->{lastline} = "";
1641 # Skip embedded PODs
1642 while ($self->{lastline} =~ /^=/) {
1643 while ($self->{lastline} = <$FH>) {
1644 last if ($self->{lastline} =~ /^=cut\s*$/);
1646 death("Error: Unterminated pod") unless $self->{lastline};
1647 $self->{lastline} = <$FH>;
1648 chomp $self->{lastline};
1649 $self->{lastline} =~ s/^\s+$//;
1651 if ($self->{lastline} !~ /^\s*#/ ||
1653 # ANSI: if ifdef ifndef elif else endif define undef
1655 # gcc: warning include_next
1657 # others: ident (gcc notes that some cpps have this one)
1658 $self->{lastline} =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1659 last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq "";
1660 push(@{ $self->{line} }, $self->{lastline});
1661 push(@{ $self->{line_no} }, $self->{lastline_no});
1664 # Read next line and continuation lines
1665 last unless defined($self->{lastline} = <$FH>);
1666 $self->{lastline_no} = $.;
1668 $self->{lastline} .= $tmp_line
1669 while ($self->{lastline} =~ /\\$/ && defined($tmp_line = <$FH>));
1671 chomp $self->{lastline};
1672 $self->{lastline} =~ s/^\s+$//;
1674 pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq "";
1679 my $argsref = shift;
1680 my ($type, $num, $var, $init, $printed_name) = (
1685 $argsref->{printed_name}
1687 my $arg = "ST(" . ($num - 1) . ")";
1689 if ( $init =~ /^=/ ) {
1690 if ($printed_name) {
1691 eval qq/print " $init\\n"/;
1694 eval qq/print "\\t$var $init\\n"/;
1699 if ( $init =~ s/^\+// && $num ) {
1704 printed_name => $printed_name,
1707 elsif ($printed_name) {
1712 eval qq/print "\\t$var;\\n"/;
1716 $self->{deferred} .= eval qq/"\\n\\t$init\\n"/;
1722 my $argsref = shift;
1723 my ($type, $num, $var, $printed_name) = (
1727 $argsref->{printed_name},
1729 my $arg = "ST(" . ($num - 1) . ")";
1730 my ($argoff, $ntype);
1733 my $typemaps = $self->{typemap};
1735 $type = tidy_type($type);
1736 blurt( $self, "Error: '$type' not in typemap"), return
1737 unless $typemaps->get_typemap(ctype => $type);
1739 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1741 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1742 my $typem = $typemaps->get_typemap(ctype => $type);
1743 my $xstype = $typem->xstype;
1744 $xstype =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1745 if ($xstype eq 'T_PV' and exists $self->{lengthof}->{$var}) {
1746 print "\t$var" unless $printed_name;
1747 print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1748 die "default value not supported with length(NAME) supplied"
1749 if defined $self->{defaults}->{$var};
1752 $type =~ tr/:/_/ unless $self->{hiertype};
1754 my $inputmap = $typemaps->get_inputmap(xstype => $xstype);
1755 blurt( $self, "Error: No INPUT definition for type '$type', typekind '" . $type->xstype . "' found"), return
1756 unless defined $inputmap;
1758 my $expr = $inputmap->cleaned_code;
1759 # Note: This gruesome bit either needs heavy rethinking or documentation. I vote for the former. --Steffen
1760 if ($expr =~ /DO_ARRAY_ELEM/) {
1761 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1762 my $subinputmap = $typemaps->get_inputmap(xstype => $subtypemap->xstype);
1763 blurt( $self, "Error: '$subtype' not in typemap"), return
1765 blurt( $self, "Error: No INPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1766 unless $subinputmap;
1767 my $subexpr = $subinputmap->cleaned_code;
1768 $subexpr =~ s/\$type/\$subtype/g;
1769 $subexpr =~ s/ntype/subtype/g;
1770 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1771 $subexpr =~ s/\n\t/\n\t\t/g;
1772 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1773 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1774 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1776 if ($expr =~ m#/\*.*scope.*\*/#i) { # "scope" in C comments
1777 $self->{ScopeThisXSUB} = 1;
1779 if (defined($self->{defaults}->{$var})) {
1780 $expr =~ s/(\t+)/$1 /g;
1782 if ($printed_name) {
1786 eval qq/print "\\t$var;\\n"/;
1789 if ($self->{defaults}->{$var} eq 'NO_INIT') {
1790 $self->{deferred} .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1793 $self->{deferred} .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1797 elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
1798 if ($printed_name) {
1802 eval qq/print "\\t$var;\\n"/;
1805 $self->{deferred} .= eval qq/"\\n$expr;\\n"/;
1809 die "panic: do not know how to handle this branch for function pointers"
1811 eval qq/print "$expr;\\n"/;
1816 sub generate_output {
1817 my $argsref = shift;
1818 my ($type, $num, $var, $do_setmagic, $do_push) = (
1822 $argsref->{do_setmagic},
1825 my $arg = "ST(" . ($num - ($num != 0)) . ")";
1828 my $typemaps = $self->{typemap};
1830 $type = tidy_type($type);
1831 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1832 print "\t$arg = sv_newmortal();\n";
1833 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1834 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1837 my $typemap = $typemaps->get_typemap(ctype => $type);
1838 my $outputmap = $typemaps->get_outputmap(xstype => $typemap->xstype);
1839 blurt( $self, "Error: '$type' not in typemap"), return
1841 blurt( $self, "Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found"), return
1843 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1844 $ntype =~ s/\(\)//g;
1846 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1848 my $expr = $outputmap->cleaned_code;
1849 if ($expr =~ /DO_ARRAY_ELEM/) {
1850 my $subtypemap = $typemaps->get_typemap(ctype => $subtype);
1851 my $suboutputmap = $typemaps->get_outputmap(xstype => $subtypemap->xstype);
1852 blurt( $self, "Error: '$subtype' not in typemap"), return
1854 blurt( $self, "Error: No OUTPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1855 unless $suboutputmap;
1856 my $subexpr = $suboutputmap->cleaned_code;
1857 $subexpr =~ s/ntype/subtype/g;
1858 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1859 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1860 $subexpr =~ s/\n\t/\n\t\t/g;
1861 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1862 eval "print qq\a$expr\a";
1864 print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1866 elsif ($var eq 'RETVAL') {
1867 if ($expr =~ /^\t\$arg = new/) {
1868 # We expect that $arg has refcnt 1, so we need to
1870 eval "print qq\a$expr\a";
1872 print "\tsv_2mortal(ST($num));\n";
1873 print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1875 elsif ($expr =~ /^\s*\$arg\s*=/) {
1876 # We expect that $arg has refcnt >=1, so we need
1878 eval "print qq\a$expr\a";
1880 print "\tsv_2mortal(ST(0));\n";
1881 print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1884 # Just hope that the entry would safely write it
1885 # over an already mortalized value. By
1886 # coincidence, something like $arg = &sv_undef
1888 print "\tST(0) = sv_newmortal();\n";
1889 eval "print qq\a$expr\a";
1891 # new mortals don't have set magic
1895 print "\tPUSHs(sv_newmortal());\n";
1897 eval "print qq\a$expr\a";
1899 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1901 elsif ($arg =~ /^ST\(\d+\)$/) {
1902 eval "print qq\a$expr\a";
1904 print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1911 # vim: ts=2 sw=2 et: