This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[RT #36079] Convert ` to '.
[perl5.git] / dist / ExtUtils-ParseXS / lib / ExtUtils / ParseXS.pm
1 package ExtUtils::ParseXS;
2 use strict;
3
4 use 5.008001;  # We use /??{}/ in regexes
5 use Cwd;
6 use Config;
7 use Exporter;
8 use File::Basename;
9 use File::Spec;
10 use Symbol;
11
12 our $VERSION;
13 BEGIN {
14   $VERSION = '3.05';
15 }
16 use ExtUtils::ParseXS::Constants $VERSION;
17 use ExtUtils::ParseXS::CountLines $VERSION;
18 use ExtUtils::ParseXS::Utilities $VERSION;
19 $VERSION = eval $VERSION if $VERSION =~ /_/;
20
21 use ExtUtils::ParseXS::Utilities qw(
22   standard_typemap_locations
23   trim_whitespace
24   tidy_type
25   C_string
26   valid_proto_string
27   process_typemaps
28   make_targetable
29   map_type
30   standard_XS_defs
31   assign_func_args
32   analyze_preprocessor_statements
33   set_cond
34   Warn
35   current_line_number
36   blurt
37   death
38   check_conditional_preprocessor_statements
39 );
40
41 our @ISA = qw(Exporter);
42 our @EXPORT_OK = qw(
43   process_file
44   report_error_count
45 );
46
47 # The scalars in the line below remain as 'our' variables because pulling
48 # them into $self led to build problems.  In most cases, strings being
49 # 'eval'-ed contain the variables' names hard-coded.
50 our (
51   $Package, $func_name, $Full_func_name, $pname, $ALIAS,
52 );
53
54 our $self = bless {} => __PACKAGE__;
55
56 sub process_file {
57
58   # Allow for $package->process_file(%hash) in the future
59   my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
60
61   $self->{ProtoUsed} = exists $options{prototypes};
62
63   # Set defaults.
64   my %args = (
65     argtypes        => 1,
66     csuffix         => '.c',
67     except          => 0,
68     hiertype        => 0,
69     inout           => 1,
70     linenumbers     => 1,
71     optimize        => 1,
72     output          => \*STDOUT,
73     prototypes      => 0,
74     typemap         => [],
75     versioncheck    => 1,
76     FH              => Symbol::gensym(),
77     %options,
78   );
79   $args{except} = $args{except} ? ' TRY' : '';
80
81   # Global Constants
82
83   my ($Is_VMS, $SymSet);
84   if ($^O eq 'VMS') {
85     $Is_VMS = 1;
86     # Establish set of global symbols with max length 28, since xsubpp
87     # will later add the 'XS_' prefix.
88     require ExtUtils::XSSymSet;
89     $SymSet = ExtUtils::XSSymSet->new(28);
90   }
91   @{ $self->{XSStack} } = ({type => 'none'});
92   $self->{InitFileCode} = [ @ExtUtils::ParseXS::Constants::InitFileCode ];
93   $self->{Overload}     = 0;
94   $self->{errors}       = 0;
95   $self->{Fallback}     = '&PL_sv_undef';
96
97   # Most of the 1500 lines below uses these globals.  We'll have to
98   # clean this up sometime, probably.  For now, we just pull them out
99   # of %args.  -Ken
100
101   $self->{hiertype} = $args{hiertype};
102   $self->{WantPrototypes} = $args{prototypes};
103   $self->{WantVersionChk} = $args{versioncheck};
104   $self->{WantLineNumbers} = $args{linenumbers};
105   $self->{IncludedFiles} = {};
106
107   die "Missing required parameter 'filename'" unless $args{filename};
108   $self->{filepathname} = $args{filename};
109   ($self->{dir}, $self->{filename}) =
110     (dirname($args{filename}), basename($args{filename}));
111   $self->{filepathname} =~ s/\\/\\\\/g;
112   $self->{IncludedFiles}->{$args{filename}}++;
113
114   # Open the output file if given as a string.  If they provide some
115   # other kind of reference, trust them that we can print to it.
116   if (not ref $args{output}) {
117     open my($fh), "> $args{output}" or die "Can't create $args{output}: $!";
118     $args{outfile} = $args{output};
119     $args{output} = $fh;
120   }
121
122   # Really, we shouldn't have to chdir() or select() in the first
123   # place.  For now, just save and restore.
124   my $orig_cwd = cwd();
125   my $orig_fh = select();
126
127   chdir($self->{dir});
128   my $pwd = cwd();
129   my $csuffix = $args{csuffix};
130
131   if ($self->{WantLineNumbers}) {
132     my $cfile;
133     if ( $args{outfile} ) {
134       $cfile = $args{outfile};
135     }
136     else {
137       $cfile = $args{filename};
138       $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
139     }
140     tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
141     select PSEUDO_STDOUT;
142   }
143   else {
144     select $args{output};
145   }
146
147   $self->{typemap} = process_typemaps( $args{typemap}, $pwd );
148
149   my $END = "!End!\n\n";        # "impossible" keyword (multiple newline)
150
151   # Match an XS keyword
152   $self->{BLOCK_re} = '\s*(' .
153     join('|' => @ExtUtils::ParseXS::Constants::XSKeywords) .
154     "|$END)\\s*:";
155
156   our ($C_group_rex, $C_arg);
157   # Group in C (no support for comments or literals)
158   $C_group_rex = qr/ [({\[]
159                (?: (?> [^()\[\]{}]+ ) | (??{ $C_group_rex }) )*
160                [)}\]] /x;
161   # Chunk in C without comma at toplevel (no comments):
162   $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
163          |   (??{ $C_group_rex })
164          |   " (?: (?> [^\\"]+ )
165            |   \\.
166            )* "        # String literal
167                 |   ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
168          )* /xs;
169
170   # Since at this point we're ready to begin printing to the output file and
171   # reading from the input file, I want to get as much data as possible into
172   # the proto-object $self.  That means assigning to $self and elements of
173   # %args referenced below this point.
174   # HOWEVER:  This resulted in an error when I tried:
175   #   $args{'s'} ---> $self->{s}.
176   # Use of uninitialized value in quotemeta at
177   #   .../blib/lib/ExtUtils/ParseXS.pm line 733
178
179   foreach my $datum ( qw| argtypes except inout optimize | ) {
180     $self->{$datum} = $args{$datum};
181   }
182
183   # Identify the version of xsubpp used
184   print <<EOM;
185 /*
186  * This file was generated automatically by ExtUtils::ParseXS version $VERSION from the
187  * contents of $self->{filename}. Do not edit this file, edit $self->{filename} instead.
188  *
189  *    ANY CHANGES MADE HERE WILL BE LOST!
190  *
191  */
192
193 EOM
194
195
196   print("#line 1 \"$self->{filepathname}\"\n")
197     if $self->{WantLineNumbers};
198
199   # Open the input file (using $self->{filename} which
200   # is a basename'd $args{filename} due to chdir above)
201   open($self->{FH}, '<', $self->{filename}) or die "cannot open $self->{filename}: $!\n";
202
203   firstmodule:
204   while (readline($self->{FH})) {
205     if (/^=/) {
206       my $podstartline = $.;
207       do {
208         if (/^=cut\s*$/) {
209           # We can't just write out a /* */ comment, as our embedded
210           # POD might itself be in a comment. We can't put a /**/
211           # comment inside #if 0, as the C standard says that the source
212           # file is decomposed into preprocessing characters in the stage
213           # before preprocessing commands are executed.
214           # I don't want to leave the text as barewords, because the spec
215           # isn't clear whether macros are expanded before or after
216           # preprocessing commands are executed, and someone pathological
217           # may just have defined one of the 3 words as a macro that does
218           # something strange. Multiline strings are illegal in C, so
219           # the "" we write must be a string literal. And they aren't
220           # concatenated until 2 steps later, so we are safe.
221           #     - Nicholas Clark
222           print("#if 0\n  \"Skipped embedded POD.\"\n#endif\n");
223           printf("#line %d \"$self->{filepathname}\"\n", $. + 1)
224             if $self->{WantLineNumbers};
225           next firstmodule
226         }
227
228       } while (readline($self->{FH}));
229       # At this point $. is at end of file so die won't state the start
230       # of the problem, and as we haven't yet read any lines &death won't
231       # show the correct line in the message either.
232       die ("Error: Unterminated pod in $self->{filename}, line $podstartline\n")
233         unless $self->{lastline};
234     }
235     last if ($Package, $self->{Prefix}) =
236       /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
237
238     print $_;
239   }
240   unless (defined $_) {
241     warn "Didn't find a 'MODULE ... PACKAGE ... PREFIX' line\n";
242     exit 0; # Not a fatal error for the caller process
243   }
244
245   print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
246
247   standard_XS_defs();
248
249   print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
250
251   $self->{lastline}    = $_;
252   $self->{lastline_no} = $.;
253
254   my $BootCode_ref = [];
255   my $XSS_work_idx = 0;
256   my $cpp_next_tmp = 'XSubPPtmpAAAA';
257  PARAGRAPH:
258   while ($self->fetch_para()) {
259     my $outlist_ref  = [];
260     # Print initial preprocessor statements and blank lines
261     while (@{ $self->{line} } && $self->{line}->[0] !~ /^[^\#]/) {
262       my $ln = shift(@{ $self->{line} });
263       print $ln, "\n";
264       next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
265       my $statement = $+;
266       ( $self, $XSS_work_idx, $BootCode_ref ) =
267         analyze_preprocessor_statements(
268           $self, $statement, $XSS_work_idx, $BootCode_ref
269         );
270     }
271
272     next PARAGRAPH unless @{ $self->{line} };
273
274     if ($XSS_work_idx && !$self->{XSStack}->[$XSS_work_idx]{varname}) {
275       # We are inside an #if, but have not yet #defined its xsubpp variable.
276       print "#define $cpp_next_tmp 1\n\n";
277       push(@{ $self->{InitFileCode} }, "#if $cpp_next_tmp\n");
278       push(@{ $BootCode_ref },     "#if $cpp_next_tmp");
279       $self->{XSStack}->[$XSS_work_idx]{varname} = $cpp_next_tmp++;
280     }
281
282     $self->death(
283       "Code is not inside a function"
284         ." (maybe last function was ended by a blank line "
285         ." followed by a statement on column one?)")
286       if $self->{line}->[0] =~ /^\s/;
287
288     # initialize info arrays
289     foreach my $member (qw(args_match var_types defaults arg_list
290                            argtype_seen in_out lengthof))
291     {
292       $self->{$member} = {};
293     }
294     $self->{proto_arg} = [];
295     $self->{processing_arg_with_types} = undef;
296     $self->{proto_in_this_xsub}        = undef;
297     $self->{scope_in_this_xsub}        = undef;
298     $self->{interface}                 = undef;
299     $self->{interface_macro}           = 'XSINTERFACE_FUNC';
300     $self->{interface_macro_set}       = 'XSINTERFACE_FUNC_SET';
301     $self->{ProtoThisXSUB}             = $self->{WantPrototypes};
302     $self->{ScopeThisXSUB}             = 0;
303
304     my $xsreturn = 0;
305
306     $_ = shift(@{ $self->{line} });
307     while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|EXPORT_XSUB_SYMBOLS|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
308       my $method = $kwd . "_handler";
309       $self->$method($_);
310       next PARAGRAPH unless @{ $self->{line} };
311       $_ = shift(@{ $self->{line} });
312     }
313
314     if ($self->check_keyword("BOOT")) {
315       check_conditional_preprocessor_statements($self);
316       push (@{ $BootCode_ref }, "#line $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} }] \"$self->{filepathname}\"")
317         if $self->{WantLineNumbers} && $self->{line}->[0] !~ /^\s*#\s*line\b/;
318       push (@{ $BootCode_ref }, @{ $self->{line} }, "");
319       next PARAGRAPH;
320     }
321
322     # extract return type, function name and arguments
323     ($self->{ret_type}) = tidy_type($_);
324     my $RETVAL_no_return = 1 if $self->{ret_type} =~ s/^NO_OUTPUT\s+//;
325
326     # Allow one-line ANSI-like declaration
327     unshift @{ $self->{line} }, $2
328       if $self->{argtypes}
329         and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
330
331     # a function definition needs at least 2 lines
332     $self->blurt("Error: Function definition too short '$self->{ret_type}'"), next PARAGRAPH
333       unless @{ $self->{line} };
334
335     my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
336     my $static  = 1 if $self->{ret_type} =~ s/^static\s+//;
337
338     my $func_header = shift(@{ $self->{line} });
339     $self->blurt("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
340       unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*(const)?\s*(;\s*)?$/s;
341
342     my ($class, $orig_args);
343     ($class, $func_name, $orig_args) =  ($1, $2, $3);
344     $class = "$4 $class" if $4;
345     ($pname = $func_name) =~ s/^($self->{Prefix})?/$self->{Packprefix}/;
346     my $clean_func_name;
347     ($clean_func_name = $func_name) =~ s/^$self->{Prefix}//;
348     $Full_func_name = "$self->{Packid}_$clean_func_name";
349     if ($Is_VMS) {
350       $Full_func_name = $SymSet->addsym($Full_func_name);
351     }
352
353     # Check for duplicate function definition
354     for my $tmp (@{ $self->{XSStack} }) {
355       next unless defined $tmp->{functions}{$Full_func_name};
356       Warn( $self, "Warning: duplicate function definition '$clean_func_name' detected");
357       last;
358     }
359     $self->{XSStack}->[$XSS_work_idx]{functions}{$Full_func_name}++;
360     %{ $self->{XsubAliases} }     = ();
361     %{ $self->{XsubAliasValues} } = ();
362     %{ $self->{Interfaces} }      = ();
363     @{ $self->{Attributes} }      = ();
364     $self->{DoSetMagic} = 1;
365
366     $orig_args =~ s/\\\s*/ /g;    # process line continuations
367     my @args;
368
369     my (@fake_INPUT_pre);    # For length(s) generated variables
370     my (@fake_INPUT);
371     my $only_C_inlist_ref = {};        # Not in the signature of Perl function
372     if ($self->{argtypes} and $orig_args =~ /\S/) {
373       my $args = "$orig_args ,";
374       if ($args =~ /^( (??{ $C_arg }) , )* $ /x) {
375         @args = ($args =~ /\G ( (??{ $C_arg }) ) , /xg);
376         for ( @args ) {
377           s/^\s+//;
378           s/\s+$//;
379           my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
380           my ($pre, $len_name) = ($arg =~ /(.*?) \s*
381                              \b ( \w+ | length\( \s*\w+\s* \) )
382                              \s* $ /x);
383           next unless defined($pre) && length($pre);
384           my $out_type = '';
385           my $inout_var;
386           if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
387             my $type = $1;
388             $out_type = $type if $type ne 'IN';
389             $arg =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
390             $pre =~ s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//;
391           }
392           my $islength;
393           if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
394             $len_name = "XSauto_length_of_$1";
395             $islength = 1;
396             die "Default value on length() argument: '$_'"
397               if length $default;
398           }
399           if (length $pre or $islength) { # Has a type
400             if ($islength) {
401               push @fake_INPUT_pre, $arg;
402             }
403             else {
404               push @fake_INPUT, $arg;
405             }
406             # warn "pushing '$arg'\n";
407             $self->{argtype_seen}->{$len_name}++;
408             $_ = "$len_name$default"; # Assigns to @args
409           }
410           $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST" or $islength;
411           push @{ $outlist_ref }, $len_name if $out_type =~ /OUTLIST$/;
412           $self->{in_out}->{$len_name} = $out_type if $out_type;
413         }
414       }
415       else {
416         @args = split(/\s*,\s*/, $orig_args);
417         Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split");
418       }
419     }
420     else {
421       @args = split(/\s*,\s*/, $orig_args);
422       for (@args) {
423         if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
424           my $out_type = $1;
425           next if $out_type eq 'IN';
426           $only_C_inlist_ref->{$_} = 1 if $out_type eq "OUTLIST";
427           if ($out_type =~ /OUTLIST$/) {
428               push @{ $outlist_ref }, undef;
429           }
430           $self->{in_out}->{$_} = $out_type;
431         }
432       }
433     }
434     if (defined($class)) {
435       my $arg0 = ((defined($static) or $func_name eq 'new')
436           ? "CLASS" : "THIS");
437       unshift(@args, $arg0);
438     }
439     my $extra_args = 0;
440     my @args_num = ();
441     my $num_args = 0;
442     my $report_args = '';
443     my $ellipsis;
444     foreach my $i (0 .. $#args) {
445       if ($args[$i] =~ s/\.\.\.//) {
446         $ellipsis = 1;
447         if ($args[$i] eq '' && $i == $#args) {
448           $report_args .= ", ...";
449           pop(@args);
450           last;
451         }
452       }
453       if ($only_C_inlist_ref->{$args[$i]}) {
454         push @args_num, undef;
455       }
456       else {
457         push @args_num, ++$num_args;
458           $report_args .= ", $args[$i]";
459       }
460       if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
461         $extra_args++;
462         $args[$i] = $1;
463         $self->{defaults}->{$args[$i]} = $2;
464         $self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
465       }
466       $self->{proto_arg}->[$i+1] = '$';
467     }
468     my $min_args = $num_args - $extra_args;
469     $report_args =~ s/"/\\"/g;
470     $report_args =~ s/^,\s+//;
471     $self->{func_args} = assign_func_args($self, \@args, $class);
472     @{ $self->{args_match} }{@args} = @args_num;
473
474     my $PPCODE = grep(/^\s*PPCODE\s*:/, @{ $self->{line} });
475     my $CODE = grep(/^\s*CODE\s*:/, @{ $self->{line} });
476     # Detect CODE: blocks which use ST(n)= or XST_m*(n,v)
477     # to set explicit return values.
478     my $EXPLICIT_RETURN = ($CODE &&
479             ("@{ $self->{line} }" =~ /(\bST\s*\([^;]*=) | (\bXST_m\w+\s*\()/x ));
480
481     # The $ALIAS which follows is only explicitly called within the scope of
482     # process_file().  In principle, it ought to be a lexical, i.e., 'my
483     # $ALIAS' like the other nearby variables.  However, implementing that
484     # change produced a slight difference in the resulting .c output in at
485     # least two distributions:  B/BD/BDFOY/Crypt-Rijndael and
486     # G/GF/GFUJI/Hash-FieldHash.  The difference is, arguably, an improvement
487     # in the resulting C code.  Example:
488     # 388c388
489     # <                       GvNAME(CvGV(cv)),
490     # ---
491     # >                       "Crypt::Rijndael::encrypt",
492     # But at this point we're committed to generating the *same* C code that
493     # the current version of ParseXS.pm does.  So we're declaring it as 'our'.
494     $ALIAS  = grep(/^\s*ALIAS\s*:/,  @{ $self->{line} });
495
496     my $INTERFACE  = grep(/^\s*INTERFACE\s*:/,  @{ $self->{line} });
497
498     $xsreturn = 1 if $EXPLICIT_RETURN;
499
500     $externC = $externC ? qq[extern "C"] : "";
501
502     # print function header
503     print Q(<<"EOF");
504 #$externC
505 #XS_EUPXS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
506 #XS_EUPXS(XS_${Full_func_name})
507 #[[
508 #    dVAR; dXSARGS;
509 EOF
510     print Q(<<"EOF") if $ALIAS;
511 #    dXSI32;
512 EOF
513     print Q(<<"EOF") if $INTERFACE;
514 #    dXSFUNCTION($self->{ret_type});
515 EOF
516
517     $self->{cond} = set_cond($ellipsis, $min_args, $num_args);
518
519     print Q(<<"EOF") if $self->{except};
520 #    char errbuf[1024];
521 #    *errbuf = '\\0';
522 EOF
523
524     if($self->{cond}) {
525       print Q(<<"EOF");
526 #    if ($self->{cond})
527 #       croak_xs_usage(cv,  "$report_args");
528 EOF
529     }
530     else {
531     # cv likely to be unused
532     print Q(<<"EOF");
533 #    PERL_UNUSED_VAR(cv); /* -W */
534 EOF
535     }
536
537     #gcc -Wall: if an xsub has PPCODE is used
538     #it is possible none of ST, XSRETURN or XSprePUSH macros are used
539     #hence 'ax' (setup by dXSARGS) is unused
540     #XXX: could breakup the dXSARGS; into dSP;dMARK;dITEMS
541     #but such a move could break third-party extensions
542     print Q(<<"EOF") if $PPCODE;
543 #    PERL_UNUSED_VAR(ax); /* -Wall */
544 EOF
545
546     print Q(<<"EOF") if $PPCODE;
547 #    SP -= items;
548 EOF
549
550     # Now do a block of some sort.
551
552     $self->{condnum} = 0;
553     $self->{cond} = '';            # last CASE: conditional
554     push(@{ $self->{line} }, "$END:");
555     push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
556     $_ = '';
557     check_conditional_preprocessor_statements();
558     while (@{ $self->{line} }) {
559
560       $self->CASE_handler($_) if $self->check_keyword("CASE");
561       print Q(<<"EOF");
562 #   $self->{except} [[
563 EOF
564
565       # do initialization of input variables
566       $self->{thisdone} = 0;
567       $self->{retvaldone} = 0;
568       $self->{deferred} = "";
569       %{ $self->{arg_list} } = ();
570       $self->{gotRETVAL} = 0;
571       $self->INPUT_handler($_);
572       $self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
573
574       print Q(<<"EOF") if $self->{ScopeThisXSUB};
575 #   ENTER;
576 #   [[
577 EOF
578
579       if (!$self->{thisdone} && defined($class)) {
580         if (defined($static) or $func_name eq 'new') {
581           print "\tchar *";
582           $self->{var_types}->{"CLASS"} = "char *";
583           generate_init( {
584             type          => "char *",
585             num           => 1,
586             var           => "CLASS",
587             printed_name  => undef,
588           } );
589         }
590         else {
591           print "\t$class *";
592           $self->{var_types}->{"THIS"} = "$class *";
593           generate_init( {
594             type          => "$class *",
595             num           => 1,
596             var           => "THIS",
597             printed_name  => undef,
598           } );
599         }
600       }
601
602       # These are set if OUTPUT is found and/or CODE using RETVAL
603       $self->{have_OUTPUT} = $self->{have_CODE_with_RETVAL} = 0;
604
605       my ($wantRETVAL);
606       # do code
607       if (/^\s*NOT_IMPLEMENTED_YET/) {
608         print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
609         $_ = '';
610       }
611       else {
612         if ($self->{ret_type} ne "void") {
613           print "\t" . map_type($self, $self->{ret_type}, 'RETVAL') . ";\n"
614             if !$self->{retvaldone};
615           $self->{args_match}->{"RETVAL"} = 0;
616           $self->{var_types}->{"RETVAL"} = $self->{ret_type};
617           my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
618           print "\tdXSTARG;\n"
619             if $self->{optimize} and $outputmap and $outputmap->targetable;
620         }
621
622         if (@fake_INPUT or @fake_INPUT_pre) {
623           unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
624           $_ = "";
625           $self->{processing_arg_with_types} = 1;
626           $self->INPUT_handler($_);
627         }
628         print $self->{deferred};
629
630         $self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
631
632         if ($self->check_keyword("PPCODE")) {
633           $self->print_section();
634           $self->death("PPCODE must be last thing") if @{ $self->{line} };
635           print "\tLEAVE;\n" if $self->{ScopeThisXSUB};
636           print "\tPUTBACK;\n\treturn;\n";
637         }
638         elsif ($self->check_keyword("CODE")) {
639           my $consumed_code = $self->print_section();
640           if ($consumed_code =~ /\bRETVAL\b/) {
641             $self->{have_CODE_with_RETVAL} = 1;
642           }
643         }
644         elsif (defined($class) and $func_name eq "DESTROY") {
645           print "\n\t";
646           print "delete THIS;\n";
647         }
648         else {
649           print "\n\t";
650           if ($self->{ret_type} ne "void") {
651             print "RETVAL = ";
652             $wantRETVAL = 1;
653           }
654           if (defined($static)) {
655             if ($func_name eq 'new') {
656               $func_name = "$class";
657             }
658             else {
659               print "${class}::";
660             }
661           }
662           elsif (defined($class)) {
663             if ($func_name eq 'new') {
664               $func_name .= " $class";
665             }
666             else {
667               print "THIS->";
668             }
669           }
670           $func_name =~ s/^\Q$args{'s'}//
671             if exists $args{'s'};
672           $func_name = 'XSFUNCTION' if $self->{interface};
673           print "$func_name($self->{func_args});\n";
674         }
675       }
676
677       # do output variables
678       $self->{gotRETVAL} = 0;        # 1 if RETVAL seen in OUTPUT section;
679       undef $self->{RETVAL_code} ;    # code to set RETVAL (from OUTPUT section);
680       # $wantRETVAL set if 'RETVAL =' autogenerated
681       ($wantRETVAL, $self->{ret_type}) = (0, 'void') if $RETVAL_no_return;
682       undef %{ $self->{outargs} };
683
684       $self->process_keyword("POSTCALL|OUTPUT|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
685
686       # A CODE section with RETVAL, but no OUTPUT? FAIL!
687       if ($self->{have_CODE_with_RETVAL} and not $self->{have_OUTPUT} and $self->{ret_type} ne 'void') {
688         $self->Warn("Warning: Found a 'CODE' section which seems to be using 'RETVAL' but no 'OUTPUT' section.");
689       }
690
691       generate_output( {
692         type        => $self->{var_types}->{$_},
693         num         => $self->{args_match}->{$_},
694         var         => $_,
695         do_setmagic => $self->{DoSetMagic},
696         do_push     => undef,
697       } ) for grep $self->{in_out}->{$_} =~ /OUT$/, keys %{ $self->{in_out} };
698
699       my $prepush_done;
700       # all OUTPUT done, so now push the return value on the stack
701       if ($self->{gotRETVAL} && $self->{RETVAL_code}) {
702         print "\t$self->{RETVAL_code}\n";
703       }
704       elsif ($self->{gotRETVAL} || $wantRETVAL) {
705         my $outputmap = $self->{typemap}->get_outputmap( ctype => $self->{ret_type} );
706         my $t = $self->{optimize} && $outputmap && $outputmap->targetable;
707         # Although the '$var' declared in the next line is never explicitly
708         # used within this 'elsif' block, commenting it out leads to
709         # disaster, starting with the first 'eval qq' inside the 'elsif' block
710         # below.
711         # It appears that this is related to the fact that at this point the
712         # value of $t is a reference to an array whose [2] element includes
713         # '$var' as a substring:
714         # <i> <> <(IV)$var>
715         my $var = 'RETVAL';
716         my $type = $self->{ret_type};
717
718         if ($t and not $t->{with_size} and $t->{type} eq 'p') {
719           # PUSHp corresponds to setpvn.  Treat setpv directly
720           my $what = eval qq("$t->{what}");
721           warn $@ if $@;
722
723           print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
724           $prepush_done = 1;
725         }
726         elsif ($t) {
727           my $what = eval qq("$t->{what}");
728           warn $@ if $@;
729
730           my $tsize = $t->{what_size};
731           $tsize = '' unless defined $tsize;
732           $tsize = eval qq("$tsize");
733           warn $@ if $@;
734           print "\tXSprePUSH; PUSH$t->{type}($what$tsize);\n";
735           $prepush_done = 1;
736         }
737         else {
738           # RETVAL almost never needs SvSETMAGIC()
739           generate_output( {
740             type        => $self->{ret_type},
741             num         => 0,
742             var         => 'RETVAL',
743             do_setmagic => 0,
744             do_push     => undef,
745           } );
746         }
747       }
748
749       $xsreturn = 1 if $self->{ret_type} ne "void";
750       my $num = $xsreturn;
751       my $c = @{ $outlist_ref };
752       print "\tXSprePUSH;" if $c and not $prepush_done;
753       print "\tEXTEND(SP,$c);\n" if $c;
754       $xsreturn += $c;
755       generate_output( {
756         type        => $self->{var_types}->{$_},
757         num         => $num++,
758         var         => $_,
759         do_setmagic => 0,
760         do_push     => 1,
761       } ) for @{ $outlist_ref };
762
763       # do cleanup
764       $self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
765
766       print Q(<<"EOF") if $self->{ScopeThisXSUB};
767 #   ]]
768 EOF
769       print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
770 #   LEAVE;
771 EOF
772
773       # print function trailer
774       print Q(<<"EOF");
775 #    ]]
776 EOF
777       print Q(<<"EOF") if $self->{except};
778 #    BEGHANDLERS
779 #    CATCHALL
780 #    sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
781 #    ENDHANDLERS
782 EOF
783       if ($self->check_keyword("CASE")) {
784         $self->blurt("Error: No 'CASE:' at top of function")
785           unless $self->{condnum};
786         $_ = "CASE: $_";    # Restore CASE: label
787         next;
788       }
789       last if $_ eq "$END:";
790       $self->death(/^$self->{BLOCK_re}/o ? "Misplaced '$1:'" : "Junk at end of function ($_)");
791     }
792
793     print Q(<<"EOF") if $self->{except};
794 #    if (errbuf[0])
795 #    Perl_croak(aTHX_ errbuf);
796 EOF
797
798     if ($xsreturn) {
799       print Q(<<"EOF") unless $PPCODE;
800 #    XSRETURN($xsreturn);
801 EOF
802     }
803     else {
804       print Q(<<"EOF") unless $PPCODE;
805 #    XSRETURN_EMPTY;
806 EOF
807     }
808
809     print Q(<<"EOF");
810 #]]
811 #
812 EOF
813
814     $self->{newXS} = "newXS";
815     $self->{proto} = "";
816
817     # Build the prototype string for the xsub
818     if ($self->{ProtoThisXSUB}) {
819       $self->{newXS} = "newXSproto_portable";
820
821       if ($self->{ProtoThisXSUB} eq 2) {
822         # User has specified empty prototype
823       }
824       elsif ($self->{ProtoThisXSUB} eq 1) {
825         my $s = ';';
826         if ($min_args < $num_args)  {
827           $s = '';
828           $self->{proto_arg}->[$min_args] .= ";";
829         }
830         push @{ $self->{proto_arg} }, "$s\@"
831           if $ellipsis;
832
833         $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
834       }
835       else {
836         # User has specified a prototype
837         $self->{proto} = $self->{ProtoThisXSUB};
838       }
839       $self->{proto} = qq{, "$self->{proto}"};
840     }
841
842     if (%{ $self->{XsubAliases} }) {
843       $self->{XsubAliases}->{$pname} = 0
844         unless defined $self->{XsubAliases}->{$pname};
845       while ( my ($xname, $value) = each %{ $self->{XsubAliases} }) {
846         push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
847 #        cv = $self->{newXS}(\"$xname\", XS_$Full_func_name, file$self->{proto});
848 #        XSANY.any_i32 = $value;
849 EOF
850       }
851     }
852     elsif (@{ $self->{Attributes} }) {
853       push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
854 #        cv = $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});
855 #        apply_attrs_string("$Package", cv, "@{ $self->{Attributes} }", 0);
856 EOF
857     }
858     elsif ($self->{interface}) {
859       while ( my ($yname, $value) = each %{ $self->{Interfaces} }) {
860         $yname = "$Package\::$yname" unless $yname =~ /::/;
861         push(@{ $self->{InitFileCode} }, Q(<<"EOF"));
862 #        cv = $self->{newXS}(\"$yname\", XS_$Full_func_name, file$self->{proto});
863 #        $self->{interface_macro_set}(cv,$value);
864 EOF
865       }
866     }
867     elsif($self->{newXS} eq 'newXS'){ # work around P5NCI's empty newXS macro
868       push(@{ $self->{InitFileCode} },
869        "        $self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
870     }
871     else {
872       push(@{ $self->{InitFileCode} },
873        "        (void)$self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
874     }
875   } # END 'PARAGRAPH' 'while' loop
876
877   if ($self->{Overload}) { # make it findable with fetchmethod
878     print Q(<<"EOF");
879 #XS_EUPXS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */
880 #XS_EUPXS(XS_$self->{Packid}_nil)
881 #{
882 #   dXSARGS;
883 #   XSRETURN_EMPTY;
884 #}
885 #
886 EOF
887     unshift(@{ $self->{InitFileCode} }, <<"MAKE_FETCHMETHOD_WORK");
888     /* Making a sub named "${Package}::()" allows the package */
889     /* to be findable via fetchmethod(), and causes */
890     /* overload::Overloaded("${Package}") to return true. */
891     (void)$self->{newXS}("${Package}::()", XS_$self->{Packid}_nil, file$self->{proto});
892 MAKE_FETCHMETHOD_WORK
893   }
894
895   # print initialization routine
896
897   print Q(<<"EOF");
898 ##ifdef __cplusplus
899 #extern "C"
900 ##endif
901 EOF
902
903   print Q(<<"EOF");
904 #XS_EXTERNAL(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
905 #XS_EXTERNAL(boot_$self->{Module_cname})
906 EOF
907
908   print Q(<<"EOF");
909 #[[
910 #    dVAR; dXSARGS;
911 EOF
912
913   #Under 5.8.x and lower, newXS is declared in proto.h as expecting a non-const
914   #file name argument. If the wrong qualifier is used, it causes breakage with
915   #C++ compilers and warnings with recent gcc.
916   #-Wall: if there is no $Full_func_name there are no xsubs in this .xs
917   #so 'file' is unused
918   print Q(<<"EOF") if $Full_func_name;
919 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
920 #    char* file = __FILE__;
921 ##else
922 #    const char* file = __FILE__;
923 ##endif
924 EOF
925
926   print Q("#\n");
927
928   print Q(<<"EOF");
929 #    PERL_UNUSED_VAR(cv); /* -W */
930 #    PERL_UNUSED_VAR(items); /* -W */
931 ##ifdef XS_APIVERSION_BOOTCHECK
932 #    XS_APIVERSION_BOOTCHECK;
933 ##endif
934 EOF
935
936   print Q(<<"EOF") if $self->{WantVersionChk};
937 #    XS_VERSION_BOOTCHECK;
938 #
939 EOF
940
941   print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
942 #    {
943 #        CV * cv;
944 #
945 EOF
946
947   print Q(<<"EOF") if ($self->{Overload});
948 #    /* register the overloading (type 'A') magic */
949 #    PL_amagic_generation++;
950 #    /* The magic for overload gets a GV* via gv_fetchmeth as */
951 #    /* mentioned above, and looks in the SV* slot of it for */
952 #    /* the "fallback" status. */
953 #    sv_setsv(
954 #        get_sv( "${Package}::()", TRUE ),
955 #        $self->{Fallback}
956 #    );
957 EOF
958
959   print @{ $self->{InitFileCode} };
960
961   print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
962 #    }
963 EOF
964
965   if (@{ $BootCode_ref }) {
966     print "\n    /* Initialisation Section */\n\n";
967     @{ $self->{line} } = @{ $BootCode_ref };
968     $self->print_section();
969     print "\n    /* End of Initialisation Section */\n\n";
970   }
971
972   print Q(<<'EOF');
973 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
974 #  if (PL_unitcheckav)
975 #       call_list(PL_scopestack_ix, PL_unitcheckav);
976 ##endif
977 EOF
978
979   print Q(<<"EOF");
980 #    XSRETURN_YES;
981 #]]
982 #
983 EOF
984
985   warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
986     unless $self->{ProtoUsed};
987
988   chdir($orig_cwd);
989   select($orig_fh);
990   untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
991   close $self->{FH};
992
993   return 1;
994 }
995
996 sub report_error_count { $self->{errors} }
997
998 # Input:  ($self, $_, @{ $self->{line} }) == unparsed input.
999 # Output: ($_, @{ $self->{line} }) == (rest of line, following lines).
1000 # Return: the matched keyword if found, otherwise 0
1001 sub check_keyword {
1002   my $self = shift;
1003   $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} };
1004   s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
1005 }
1006
1007 sub print_section {
1008   my $self = shift;
1009
1010   # the "do" is required for right semantics
1011   do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} };
1012
1013   my $consumed_code = '';
1014
1015   print("#line ", $self->{line_no}->[@{ $self->{line_no} } - @{ $self->{line} } -1], " \"$self->{filepathname}\"\n")
1016     if $self->{WantLineNumbers} && !/^\s*#\s*line\b/ && !/^#if XSubPPtmp/;
1017   for (;  defined($_) && !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1018     print "$_\n";
1019     $consumed_code .= "$_\n";
1020   }
1021   print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
1022
1023   return $consumed_code;
1024 }
1025
1026 sub merge_section {
1027   my $self = shift;
1028   my $in = '';
1029
1030   while (!/\S/ && @{ $self->{line} }) {
1031     $_ = shift(@{ $self->{line} });
1032   }
1033
1034   for (;  defined($_) && !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1035     $in .= "$_\n";
1036   }
1037   chomp $in;
1038   return $in;
1039 }
1040
1041 sub process_keyword {
1042   my($self, $pattern) = @_;
1043
1044   while (my $kwd = $self->check_keyword($pattern)) {
1045     my $method = $kwd . "_handler";
1046     $self->$method($_);
1047   }
1048 }
1049
1050 sub CASE_handler {
1051   my $self = shift;
1052   $_ = shift;
1053   $self->blurt("Error: 'CASE:' after unconditional 'CASE:'")
1054     if $self->{condnum} && $self->{cond} eq '';
1055   $self->{cond} = $_;
1056   trim_whitespace($self->{cond});
1057   print "   ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n");
1058   $_ = '';
1059 }
1060
1061 sub INPUT_handler {
1062   my $self = shift;
1063   $_ = shift;
1064   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1065     last if /^\s*NOT_IMPLEMENTED_YET/;
1066     next unless /\S/;        # skip blank lines
1067
1068     trim_whitespace($_);
1069     my $ln = $_;
1070
1071     # remove trailing semicolon if no initialisation
1072     s/\s*;$//g unless /[=;+].*\S/;
1073
1074     # Process the length(foo) declarations
1075     if (s/^([^=]*)\blength\(\s*(\w+)\s*\)\s*$/$1 XSauto_length_of_$2=NO_INIT/x) {
1076       print "\tSTRLEN\tSTRLEN_length_of_$2;\n";
1077       $self->{lengthof}->{$2} = undef;
1078       $self->{deferred} .= "\n\tXSauto_length_of_$2 = STRLEN_length_of_$2;\n";
1079     }
1080
1081     # check for optional initialisation code
1082     my $var_init = '';
1083     $var_init = $1 if s/\s*([=;+].*)$//s;
1084     $var_init =~ s/"/\\"/g;
1085     # *sigh* It's valid to supply explicit input typemaps in the argument list...
1086     my $is_overridden_typemap = $var_init =~ /ST\s*\(|\$arg\b/;
1087
1088     s/\s+/ /g;
1089     my ($var_type, $var_addr, $var_name) = /^(.*?[^&\s])\s*(\&?)\s*\b(\w+)$/s
1090       or $self->blurt("Error: invalid argument declaration '$ln'"), next;
1091
1092     # Check for duplicate definitions
1093     $self->blurt("Error: duplicate definition of argument '$var_name' ignored"), next
1094       if $self->{arg_list}->{$var_name}++
1095         or defined $self->{argtype_seen}->{$var_name} and not $self->{processing_arg_with_types};
1096
1097     $self->{thisdone} |= $var_name eq "THIS";
1098     $self->{retvaldone} |= $var_name eq "RETVAL";
1099     $self->{var_types}->{$var_name} = $var_type;
1100     # XXXX This check is a safeguard against the unfinished conversion of
1101     # generate_init().  When generate_init() is fixed,
1102     # one can use 2-args map_type() unconditionally.
1103     my $printed_name;
1104     if ($var_type =~ / \( \s* \* \s* \) /x) {
1105       # Function pointers are not yet supported with output_init()!
1106       print "\t" . map_type($self, $var_type, $var_name);
1107       $printed_name = 1;
1108     }
1109     else {
1110       print "\t" . map_type($self, $var_type, undef);
1111       $printed_name = 0;
1112     }
1113     $self->{var_num} = $self->{args_match}->{$var_name};
1114
1115     if ($self->{var_num}) {
1116       my $typemap = $self->{typemap}->get_typemap(ctype => $var_type);
1117       $self->death("Could not find a typemap for C type '$var_type'")
1118         if not $typemap and not $is_overridden_typemap;
1119       $self->{proto_arg}->[$self->{var_num}] = ($typemap && $typemap->proto) || "\$";
1120     }
1121     $self->{func_args} =~ s/\b($var_name)\b/&$1/ if $var_addr;
1122     if ($var_init =~ /^[=;]\s*NO_INIT\s*;?\s*$/
1123       or $self->{in_out}->{$var_name} and $self->{in_out}->{$var_name} =~ /^OUT/
1124       and $var_init !~ /\S/) {
1125       if ($printed_name) {
1126         print ";\n";
1127       }
1128       else {
1129         print "\t$var_name;\n";
1130       }
1131     }
1132     elsif ($var_init =~ /\S/) {
1133       output_init( {
1134         type          => $var_type,
1135         num           => $self->{var_num},
1136         var           => $var_name,
1137         init          => $var_init,
1138         printed_name  => $printed_name,
1139       } );
1140     }
1141     elsif ($self->{var_num}) {
1142       generate_init( {
1143         type          => $var_type,
1144         num           => $self->{var_num},
1145         var           => $var_name,
1146         printed_name  => $printed_name,
1147       } );
1148     }
1149     else {
1150       print ";\n";
1151     }
1152   }
1153 }
1154
1155 sub OUTPUT_handler {
1156   my $self = shift;
1157   $self->{have_OUTPUT} = 1;
1158
1159   $_ = shift;
1160   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1161     next unless /\S/;
1162     if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1163       $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
1164       next;
1165     }
1166     my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s;
1167     $self->blurt("Error: duplicate OUTPUT argument '$outarg' ignored"), next
1168       if $self->{outargs}->{$outarg}++;
1169     if (!$self->{gotRETVAL} and $outarg eq 'RETVAL') {
1170       # deal with RETVAL last
1171       $self->{RETVAL_code} = $outcode;
1172       $self->{gotRETVAL} = 1;
1173       next;
1174     }
1175     $self->blurt("Error: OUTPUT $outarg not an argument"), next
1176       unless defined($self->{args_match}->{$outarg});
1177     $self->blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
1178       unless defined $self->{var_types}->{$outarg};
1179     $self->{var_num} = $self->{args_match}->{$outarg};
1180     if ($outcode) {
1181       print "\t$outcode\n";
1182       print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
1183     }
1184     else {
1185       generate_output( {
1186         type        => $self->{var_types}->{$outarg},
1187         num         => $self->{var_num},
1188         var         => $outarg,
1189         do_setmagic => $self->{DoSetMagic},
1190         do_push     => undef,
1191       } );
1192     }
1193     delete $self->{in_out}->{$outarg}     # No need to auto-OUTPUT
1194       if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
1195   }
1196 }
1197
1198 sub C_ARGS_handler {
1199   my $self = shift;
1200   $_ = shift;
1201   my $in = $self->merge_section();
1202
1203   trim_whitespace($in);
1204   $self->{func_args} = $in;
1205 }
1206
1207 sub INTERFACE_MACRO_handler {
1208   my $self = shift;
1209   $_ = shift;
1210   my $in = $self->merge_section();
1211
1212   trim_whitespace($in);
1213   if ($in =~ /\s/) {        # two
1214     ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
1215   }
1216   else {
1217     $self->{interface_macro} = $in;
1218     $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
1219   }
1220   $self->{interface} = 1;        # local
1221   $self->{interfaces} = 1;        # global
1222 }
1223
1224 sub INTERFACE_handler {
1225   my $self = shift;
1226   $_ = shift;
1227   my $in = $self->merge_section();
1228
1229   trim_whitespace($in);
1230
1231   foreach (split /[\s,]+/, $in) {
1232     my $iface_name = $_;
1233     $iface_name =~ s/^$self->{Prefix}//;
1234     $self->{Interfaces}->{$iface_name} = $_;
1235   }
1236   print Q(<<"EOF");
1237 #    XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
1238 EOF
1239   $self->{interface} = 1;        # local
1240   $self->{interfaces} = 1;        # global
1241 }
1242
1243 sub CLEANUP_handler {
1244   my $self = shift;
1245   $self->print_section();
1246 }
1247
1248 sub PREINIT_handler {
1249   my $self = shift;
1250   $self->print_section();
1251 }
1252
1253 sub POSTCALL_handler {
1254   my $self = shift;
1255   $self->print_section();
1256 }
1257
1258 sub INIT_handler {
1259   my $self = shift;
1260   $self->print_section();
1261 }
1262
1263 sub get_aliases {
1264   my $self = shift;
1265   my ($line) = @_;
1266   my ($orig) = $line;
1267
1268   # Parse alias definitions
1269   # format is
1270   #    alias = value alias = value ...
1271
1272   while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1273     my ($alias, $value) = ($1, $2);
1274     my $orig_alias = $alias;
1275
1276     # check for optional package definition in the alias
1277     $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
1278
1279     # check for duplicate alias name & duplicate value
1280     Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'")
1281       if defined $self->{XsubAliases}->{$alias};
1282
1283     Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
1284       if $self->{XsubAliasValues}->{$value};
1285
1286     $self->{xsubaliases} = 1;
1287     $self->{XsubAliases}->{$alias} = $value;
1288     $self->{XsubAliasValues}->{$value} = $orig_alias;
1289   }
1290
1291   blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'")
1292     if $line;
1293 }
1294
1295 sub ATTRS_handler {
1296   my $self = shift;
1297   $_ = shift;
1298
1299   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1300     next unless /\S/;
1301     trim_whitespace($_);
1302     push @{ $self->{Attributes} }, $_;
1303   }
1304 }
1305
1306 sub ALIAS_handler {
1307   my $self = shift;
1308   $_ = shift;
1309
1310   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1311     next unless /\S/;
1312     trim_whitespace($_);
1313     $self->get_aliases($_) if $_;
1314   }
1315 }
1316
1317 sub OVERLOAD_handler {
1318   my $self = shift;
1319   $_ = shift;
1320
1321   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1322     next unless /\S/;
1323     trim_whitespace($_);
1324     while ( s/^\s*([\w:"\\)\+\-\*\/\%\<\>\.\&\|\^\!\~\{\}\=]+)\s*//) {
1325       $self->{Overload} = 1 unless $self->{Overload};
1326       my $overload = "$Package\::(".$1;
1327       push(@{ $self->{InitFileCode} },
1328        "        (void)$self->{newXS}(\"$overload\", XS_$Full_func_name, file$self->{proto});\n");
1329     }
1330   }
1331 }
1332
1333 sub FALLBACK_handler {
1334   my $self = shift;
1335   $_ = shift;
1336
1337   # the rest of the current line should contain either TRUE,
1338   # FALSE or UNDEF
1339
1340   trim_whitespace($_);
1341   my %map = (
1342     TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1343     FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1344     UNDEF => "&PL_sv_undef",
1345   );
1346
1347   # check for valid FALLBACK value
1348   $self->death("Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1349
1350   $self->{Fallback} = $map{uc $_};
1351 }
1352
1353
1354 sub REQUIRE_handler {
1355   my $self = shift;
1356   # the rest of the current line should contain a version number
1357   my $Ver = shift;
1358
1359   trim_whitespace($Ver);
1360
1361   $self->death("Error: REQUIRE expects a version number")
1362     unless $Ver;
1363
1364   # check that the version number is of the form n.n
1365   $self->death("Error: REQUIRE: expected a number, got '$Ver'")
1366     unless $Ver =~ /^\d+(\.\d*)?/;
1367
1368   $self->death("Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1369     unless $VERSION >= $Ver;
1370 }
1371
1372 sub VERSIONCHECK_handler {
1373   my $self = shift;
1374   $_ = shift;
1375
1376   # the rest of the current line should contain either ENABLE or
1377   # DISABLE
1378
1379   trim_whitespace($_);
1380
1381   # check for ENABLE/DISABLE
1382   $self->death("Error: VERSIONCHECK: ENABLE/DISABLE")
1383     unless /^(ENABLE|DISABLE)/i;
1384
1385   $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1386   $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
1387
1388 }
1389
1390 sub PROTOTYPE_handler {
1391   my $self = shift;
1392   $_ = shift;
1393
1394   my $specified;
1395
1396   $self->death("Error: Only 1 PROTOTYPE definition allowed per xsub")
1397     if $self->{proto_in_this_xsub}++;
1398
1399   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1400     next unless /\S/;
1401     $specified = 1;
1402     trim_whitespace($_);
1403     if ($_ eq 'DISABLE') {
1404       $self->{ProtoThisXSUB} = 0;
1405     }
1406     elsif ($_ eq 'ENABLE') {
1407       $self->{ProtoThisXSUB} = 1;
1408     }
1409     else {
1410       # remove any whitespace
1411       s/\s+//g;
1412       $self->death("Error: Invalid prototype '$_'")
1413         unless valid_proto_string($_);
1414       $self->{ProtoThisXSUB} = C_string($_);
1415     }
1416   }
1417
1418   # If no prototype specified, then assume empty prototype ""
1419   $self->{ProtoThisXSUB} = 2 unless $specified;
1420
1421   $self->{ProtoUsed} = 1;
1422 }
1423
1424 sub SCOPE_handler {
1425   my $self = shift;
1426   $_ = shift;
1427
1428   $self->death("Error: Only 1 SCOPE declaration allowed per xsub")
1429     if $self->{scope_in_this_xsub}++;
1430
1431   trim_whitespace($_);
1432   $self->death("Error: SCOPE: ENABLE/DISABLE")
1433       unless /^(ENABLE|DISABLE)\b/i;
1434   $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
1435 }
1436
1437 sub PROTOTYPES_handler {
1438   my $self = shift;
1439   $_ = shift;
1440
1441   # the rest of the current line should contain either ENABLE or
1442   # DISABLE
1443
1444   trim_whitespace($_);
1445
1446   # check for ENABLE/DISABLE
1447   $self->death("Error: PROTOTYPES: ENABLE/DISABLE")
1448     unless /^(ENABLE|DISABLE)/i;
1449
1450   $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1451   $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
1452   $self->{ProtoUsed} = 1;
1453 }
1454
1455 sub EXPORT_XSUB_SYMBOLS_handler {
1456   my $self = shift;
1457   $_ = shift;
1458
1459   # the rest of the current line should contain either ENABLE or
1460   # DISABLE
1461
1462   trim_whitespace($_);
1463
1464   # check for ENABLE/DISABLE
1465   $self->death("Error: EXPORT_XSUB_SYMBOLS: ENABLE/DISABLE")
1466     unless /^(ENABLE|DISABLE)/i;
1467
1468   my $xs_impl = $1 eq 'ENABLE' ? 'XS_EXTERNAL' : 'XS_INTERNAL';
1469
1470   print Q(<<"EOF");
1471 ##undef XS_EUPXS
1472 ##if defined(PERL_EUPXS_ALWAYS_EXPORT)
1473 ##  define XS_EUPXS(name) XS_EXTERNAL(name)
1474 ##elif defined(PERL_EUPXS_NEVER_EXPORT)
1475 ##  define XS_EUPXS(name) XS_INTERNAL(name)
1476 ##else
1477 ##  define XS_EUPXS(name) $xs_impl(name)
1478 ##endif
1479 EOF
1480 }
1481
1482
1483 sub PushXSStack {
1484   my $self = shift;
1485   my %args = @_;
1486   # Save the current file context.
1487   push(@{ $self->{XSStack} }, {
1488           type            => 'file',
1489           LastLine        => $self->{lastline},
1490           LastLineNo      => $self->{lastline_no},
1491           Line            => $self->{line},
1492           LineNo          => $self->{line_no},
1493           Filename        => $self->{filename},
1494           Filepathname    => $self->{filepathname},
1495           Handle          => $self->{FH},
1496           IsPipe          => scalar($self->{filename} =~ /\|\s*$/),
1497           %args,
1498          });
1499
1500 }
1501
1502 sub INCLUDE_handler {
1503   my $self = shift;
1504   $_ = shift;
1505   # the rest of the current line should contain a valid filename
1506
1507   trim_whitespace($_);
1508
1509   $self->death("INCLUDE: filename missing")
1510     unless $_;
1511
1512   $self->death("INCLUDE: output pipe is illegal")
1513     if /^\s*\|/;
1514
1515   # simple minded recursion detector
1516   $self->death("INCLUDE loop detected")
1517     if $self->{IncludedFiles}->{$_};
1518
1519   ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
1520
1521   if (/\|\s*$/ && /^\s*perl\s/) {
1522     Warn( $self, "The INCLUDE directive with a command is discouraged." .
1523           " Use INCLUDE_COMMAND instead! In particular using 'perl'" .
1524           " in an 'INCLUDE: ... |' directive is not guaranteed to pick" .
1525           " up the correct perl. The INCLUDE_COMMAND directive allows" .
1526           " the use of \$^X as the currently running perl, see" .
1527           " 'perldoc perlxs' for details.");
1528   }
1529
1530   $self->PushXSStack();
1531
1532   $self->{FH} = Symbol::gensym();
1533
1534   # open the new file
1535   open($self->{FH}, $_) or $self->death("Cannot open '$_': $!");
1536
1537   print Q(<<"EOF");
1538 #
1539 #/* INCLUDE:  Including '$_' from '$self->{filename}' */
1540 #
1541 EOF
1542
1543   $self->{filename} = $_;
1544   $self->{filepathname} = ( $^O =~ /^mswin/i )
1545                           ? qq($self->{dir}/$self->{filename}) # See CPAN RT #61908: gcc doesn't like backslashes on win32?
1546                           : File::Spec->catfile($self->{dir}, $self->{filename});
1547
1548   # Prime the pump by reading the first
1549   # non-blank line
1550
1551   # skip leading blank lines
1552   while (readline($self->{FH})) {
1553     last unless /^\s*$/;
1554   }
1555
1556   $self->{lastline} = $_;
1557   $self->{lastline_no} = $.;
1558 }
1559
1560 sub QuoteArgs {
1561   my $cmd = shift;
1562   my @args = split /\s+/, $cmd;
1563   $cmd = shift @args;
1564   for (@args) {
1565     $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1566   }
1567   return join (' ', ($cmd, @args));
1568 }
1569
1570 sub INCLUDE_COMMAND_handler {
1571   my $self = shift;
1572   $_ = shift;
1573   # the rest of the current line should contain a valid command
1574
1575   trim_whitespace($_);
1576
1577   $_ = QuoteArgs($_) if $^O eq 'VMS';
1578
1579   $self->death("INCLUDE_COMMAND: command missing")
1580     unless $_;
1581
1582   $self->death("INCLUDE_COMMAND: pipes are illegal")
1583     if /^\s*\|/ or /\|\s*$/;
1584
1585   $self->PushXSStack( IsPipe => 1 );
1586
1587   $self->{FH} = Symbol::gensym();
1588
1589   # If $^X is used in INCLUDE_COMMAND, we know it's supposed to be
1590   # the same perl interpreter as we're currently running
1591   s/^\s*\$\^X/$^X/;
1592
1593   # open the new file
1594   open ($self->{FH}, "-|", $_)
1595     or $self->death( $self, "Cannot run command '$_' to include its output: $!");
1596
1597   print Q(<<"EOF");
1598 #
1599 #/* INCLUDE_COMMAND:  Including output of '$_' from '$self->{filename}' */
1600 #
1601 EOF
1602
1603   $self->{filename} = $_;
1604   $self->{filepathname} = $self->{filename};
1605   #$self->{filepathname} =~ s/\"/\\"/g; # Fails? See CPAN RT #53938: MinGW Broken after 2.21
1606   $self->{filepathname} =~ s/\\/\\\\/g; # Works according to reporter of #53938
1607
1608   # Prime the pump by reading the first
1609   # non-blank line
1610
1611   # skip leading blank lines
1612   while (readline($self->{FH})) {
1613     last unless /^\s*$/;
1614   }
1615
1616   $self->{lastline} = $_;
1617   $self->{lastline_no} = $.;
1618 }
1619
1620 sub PopFile {
1621   my $self = shift;
1622
1623   return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
1624
1625   my $data     = pop @{ $self->{XSStack} };
1626   my $ThisFile = $self->{filename};
1627   my $isPipe   = $data->{IsPipe};
1628
1629   --$self->{IncludedFiles}->{$self->{filename}}
1630     unless $isPipe;
1631
1632   close $self->{FH};
1633
1634   $self->{FH}         = $data->{Handle};
1635   # $filename is the leafname, which for some reason isused for diagnostic
1636   # messages, whereas $filepathname is the full pathname, and is used for
1637   # #line directives.
1638   $self->{filename}   = $data->{Filename};
1639   $self->{filepathname} = $data->{Filepathname};
1640   $self->{lastline}   = $data->{LastLine};
1641   $self->{lastline_no} = $data->{LastLineNo};
1642   @{ $self->{line} }       = @{ $data->{Line} };
1643   @{ $self->{line_no} }    = @{ $data->{LineNo} };
1644
1645   if ($isPipe and $? ) {
1646     --$self->{lastline_no};
1647     print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
1648     exit 1;
1649   }
1650
1651   print Q(<<"EOF");
1652 #
1653 #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
1654 #
1655 EOF
1656
1657   return 1;
1658 }
1659
1660 sub Q {
1661   my($text) = @_;
1662   $text =~ s/^#//gm;
1663   $text =~ s/\[\[/{/g;
1664   $text =~ s/\]\]/}/g;
1665   $text;
1666 }
1667
1668 # Read next xsub into @{ $self->{line} } from ($lastline, readline($self->{FH})).
1669 sub fetch_para {
1670   my $self = shift;
1671
1672   # parse paragraph
1673   $self->death("Error: Unterminated '#if/#ifdef/#ifndef'")
1674     if !defined $self->{lastline} && $self->{XSStack}->[-1]{type} eq 'if';
1675   @{ $self->{line} } = ();
1676   @{ $self->{line_no} } = ();
1677   return $self->PopFile() if !defined $self->{lastline};
1678
1679   if ($self->{lastline} =~
1680       /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1681     my $Module = $1;
1682     $Package = defined($2) ? $2 : ''; # keep -w happy
1683     $self->{Prefix}  = defined($3) ? $3 : ''; # keep -w happy
1684     $self->{Prefix} = quotemeta $self->{Prefix};
1685     ($self->{Module_cname} = $Module) =~ s/\W/_/g;
1686     ($self->{Packid} = $Package) =~ tr/:/_/;
1687     $self->{Packprefix} = $Package;
1688     $self->{Packprefix} .= "::" if $self->{Packprefix} ne "";
1689     $self->{lastline} = "";
1690   }
1691
1692   for (;;) {
1693     # Skip embedded PODs
1694     while ($self->{lastline} =~ /^=/) {
1695       while ($self->{lastline} = readline($self->{FH})) {
1696         last if ($self->{lastline} =~ /^=cut\s*$/);
1697       }
1698       $self->death("Error: Unterminated pod") unless $self->{lastline};
1699       $self->{lastline} = readline($self->{FH});
1700       chomp $self->{lastline};
1701       $self->{lastline} =~ s/^\s+$//;
1702     }
1703
1704     # This chunk of code strips out (and parses) embedded TYPEMAP blocks
1705     # which support a HEREdoc-alike block syntax.
1706     # This is special cased from the usual paragraph-handler logic
1707     # due to the HEREdoc-ish syntax.
1708     if ($self->{lastline} =~ /^TYPEMAP\s*:\s*<<\s*(?:(["'])(.+?)\1|([^\s'"]+))\s*;?\s*$/) {
1709       my $end_marker = quotemeta(defined($1) ? $2 : $3);
1710       my @tmaplines;
1711       while (1) {
1712         $self->{lastline} = readline($self->{FH});
1713         $self->death("Error: Unterminated typemap") if not defined $self->{lastline};
1714         last if $self->{lastline} =~ /^$end_marker\s*$/;
1715         push @tmaplines, $self->{lastline};
1716       }
1717
1718       my $tmapcode = join "", @tmaplines;
1719       my $tmap = ExtUtils::Typemaps->new(
1720         string => $tmapcode,
1721         lineno_offset => $self->current_line_number()+1,
1722         fake_filename => $self->{filename},
1723       );
1724       $self->{typemap}->merge(typemap => $tmap, replace => 1);
1725
1726       last unless defined($self->{lastline} = readline($self->{FH}));
1727       next;
1728     }
1729
1730     if ($self->{lastline} !~ /^\s*#/ ||
1731     # CPP directives:
1732     #    ANSI:    if ifdef ifndef elif else endif define undef
1733     #        line error pragma
1734     #    gcc:    warning include_next
1735     #   obj-c:    import
1736     #   others:    ident (gcc notes that some cpps have this one)
1737     $self->{lastline} =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
1738       last if $self->{lastline} =~ /^\S/ && @{ $self->{line} } && $self->{line}->[-1] eq "";
1739       push(@{ $self->{line} }, $self->{lastline});
1740       push(@{ $self->{line_no} }, $self->{lastline_no});
1741     }
1742
1743     # Read next line and continuation lines
1744     last unless defined($self->{lastline} = readline($self->{FH}));
1745     $self->{lastline_no} = $.;
1746     my $tmp_line;
1747     $self->{lastline} .= $tmp_line
1748       while ($self->{lastline} =~ /\\$/ && defined($tmp_line = readline($self->{FH})));
1749
1750     chomp $self->{lastline};
1751     $self->{lastline} =~ s/^\s+$//;
1752   }
1753   pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq "";
1754   1;
1755 }
1756
1757 sub output_init {
1758   my $argsref = shift;
1759   my ($type, $num, $var, $init, $printed_name) = (
1760     $argsref->{type},
1761     $argsref->{num},
1762     $argsref->{var},
1763     $argsref->{init},
1764     $argsref->{printed_name}
1765   );
1766   my $arg = "ST(" . ($num - 1) . ")";
1767
1768   if (  $init =~ /^=/  ) {
1769     if ($printed_name) {
1770       eval qq/print " $init\\n"/;
1771     }
1772     else {
1773       eval qq/print "\\t$var $init\\n"/;
1774     }
1775     warn $@ if $@;
1776   }
1777   else {
1778     if (  $init =~ s/^\+//  &&  $num  ) {
1779       generate_init( {
1780         type          => $type,
1781         num           => $num,
1782         var           => $var,
1783         printed_name  => $printed_name,
1784       } );
1785     }
1786     elsif ($printed_name) {
1787       print ";\n";
1788       $init =~ s/^;//;
1789     }
1790     else {
1791       eval qq/print "\\t$var;\\n"/;
1792       warn $@ if $@;
1793       $init =~ s/^;//;
1794     }
1795     $self->{deferred} .= eval qq/"\\n\\t$init\\n"/;
1796     warn $@ if $@;
1797   }
1798 }
1799
1800 sub generate_init {
1801   my $argsref = shift;
1802   my ($type, $num, $var, $printed_name) = (
1803     $argsref->{type},
1804     $argsref->{num},
1805     $argsref->{var},
1806     $argsref->{printed_name},
1807   );
1808   my $arg = "ST(" . ($num - 1) . ")";
1809   my ($argoff, $ntype);
1810   $argoff = $num - 1;
1811
1812   my $typemaps = $self->{typemap};
1813
1814   $type = tidy_type($type);
1815   $self->blurt("Error: '$type' not in typemap"), return
1816     unless $typemaps->get_typemap(ctype => $type);
1817
1818   ($ntype = $type) =~ s/\s*\*/Ptr/g;
1819   my $subtype;
1820   ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1821   my $typem = $typemaps->get_typemap(ctype => $type);
1822   my $xstype = $typem->xstype;
1823   $xstype =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
1824   if ($xstype eq 'T_PV' and exists $self->{lengthof}->{$var}) {
1825     print "\t$var" unless $printed_name;
1826     print " = ($type)SvPV($arg, STRLEN_length_of_$var);\n";
1827     die "default value not supported with length(NAME) supplied"
1828       if defined $self->{defaults}->{$var};
1829     return;
1830   }
1831   $type =~ tr/:/_/ unless $self->{hiertype};
1832
1833   my $inputmap = $typemaps->get_inputmap(xstype => $xstype);
1834   $self->blurt("Error: No INPUT definition for type '$type', typekind '" . $type->xstype . "' found"), return
1835     unless defined $inputmap;
1836
1837   my $expr = $inputmap->cleaned_code;
1838   # Note: This gruesome bit either needs heavy rethinking or documentation. I vote for the former. --Steffen
1839   if ($expr =~ /DO_ARRAY_ELEM/) {
1840     my $subtypemap  = $typemaps->get_typemap(ctype => $subtype);
1841     $self->blurt("Error: C type '$subtype' not in typemap"), return
1842       if not $subtypemap;
1843     my $subinputmap = $typemaps->get_inputmap(xstype => $subtypemap->xstype);
1844     $self->blurt("Error: No INPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1845       unless $subinputmap;
1846     my $subexpr = $subinputmap->cleaned_code;
1847     $subexpr =~ s/\$type/\$subtype/g;
1848     $subexpr =~ s/ntype/subtype/g;
1849     $subexpr =~ s/\$arg/ST(ix_$var)/g;
1850     $subexpr =~ s/\n\t/\n\t\t/g;
1851     $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
1852     $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
1853     $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1854   }
1855   if ($expr =~ m#/\*.*scope.*\*/#i) {  # "scope" in C comments
1856     $self->{ScopeThisXSUB} = 1;
1857   }
1858   if (defined($self->{defaults}->{$var})) {
1859     $expr =~ s/(\t+)/$1    /g;
1860     $expr =~ s/        /\t/g;
1861     if ($printed_name) {
1862       print ";\n";
1863     }
1864     else {
1865       eval qq/print "\\t$var;\\n"/;
1866       warn $@ if $@;
1867     }
1868     if ($self->{defaults}->{$var} eq 'NO_INIT') {
1869       $self->{deferred} .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1870     }
1871     else {
1872       $self->{deferred} .= eval qq/"\\n\\tif (items < $num)\\n\\t    $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1873     }
1874     warn $@ if $@;
1875   }
1876   elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
1877     if ($printed_name) {
1878       print ";\n";
1879     }
1880     else {
1881       eval qq/print "\\t$var;\\n"/;
1882       warn $@ if $@;
1883     }
1884     $self->{deferred} .= eval qq/"\\n$expr;\\n"/;
1885     warn $@ if $@;
1886   }
1887   else {
1888     die "panic: do not know how to handle this branch for function pointers"
1889       if $printed_name;
1890     eval qq/print "$expr;\\n"/;
1891     warn $@ if $@;
1892   }
1893 }
1894
1895 sub generate_output {
1896   my $argsref = shift;
1897   my ($type, $num, $var, $do_setmagic, $do_push) = (
1898     $argsref->{type},
1899     $argsref->{num},
1900     $argsref->{var},
1901     $argsref->{do_setmagic},
1902     $argsref->{do_push}
1903   );
1904   my $arg = "ST(" . ($num - ($num != 0)) . ")";
1905   my $ntype;
1906
1907   my $typemaps = $self->{typemap};
1908
1909   $type = tidy_type($type);
1910   if ($type =~ /^array\(([^,]*),(.*)\)/) {
1911     print "\t$arg = sv_newmortal();\n";
1912     print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1));\n";
1913     print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1914   }
1915   else {
1916     my $typemap   = $typemaps->get_typemap(ctype => $type);
1917     $self->blurt("Could not find a typemap for C type '$type'"), return
1918       if not $typemap;
1919     my $outputmap = $typemaps->get_outputmap(xstype => $typemap->xstype);
1920     $self->blurt("Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found"), return
1921       unless $outputmap;
1922     ($ntype = $type) =~ s/\s*\*/Ptr/g;
1923     $ntype =~ s/\(\)//g;
1924     my $subtype;
1925     ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1926
1927     my $expr = $outputmap->cleaned_code;
1928     if ($expr =~ /DO_ARRAY_ELEM/) {
1929       my $subtypemap   = $typemaps->get_typemap(ctype => $subtype);
1930       $self->blurt("Could not find a typemap for C type '$subtype'"), return
1931         if not $subtypemap;
1932       my $suboutputmap = $typemaps->get_outputmap(xstype => $subtypemap->xstype);
1933       $self->blurt("Error: No OUTPUT definition for type '$subtype', typekind '" . $subtypemap->xstype . "' found"), return
1934         unless $suboutputmap;
1935       my $subexpr = $suboutputmap->cleaned_code;
1936       $subexpr =~ s/ntype/subtype/g;
1937       $subexpr =~ s/\$arg/ST(ix_$var)/g;
1938       $subexpr =~ s/\$var/${var}[ix_$var]/g;
1939       $subexpr =~ s/\n\t/\n\t\t/g;
1940       $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
1941       eval "print qq\a$expr\a";
1942       warn $@ if $@;
1943       print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1944     }
1945     elsif ($var eq 'RETVAL') {
1946       if ($expr =~ /^\t\$arg = new/) {
1947         # We expect that $arg has refcnt 1, so we need to
1948         # mortalize it.
1949         eval "print qq\a$expr\a";
1950         warn $@ if $@;
1951         print "\tsv_2mortal(ST($num));\n";
1952         print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1953       }
1954       elsif ($expr =~ /^\s*\$arg\s*=/) {
1955         # We expect that $arg has refcnt >=1, so we need
1956         # to mortalize it!
1957         eval "print qq\a$expr\a";
1958         warn $@ if $@;
1959         print "\tsv_2mortal(ST(0));\n";
1960         print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1961       }
1962       else {
1963         # Just hope that the entry would safely write it
1964         # over an already mortalized value. By
1965         # coincidence, something like $arg = &sv_undef
1966         # works too.
1967         print "\tST(0) = sv_newmortal();\n";
1968         eval "print qq\a$expr\a";
1969         warn $@ if $@;
1970         # new mortals don't have set magic
1971       }
1972     }
1973     elsif ($do_push) {
1974       print "\tPUSHs(sv_newmortal());\n";
1975       $arg = "ST($num)";
1976       eval "print qq\a$expr\a";
1977       warn $@ if $@;
1978       print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1979     }
1980     elsif ($arg =~ /^ST\(\d+\)$/) {
1981       eval "print qq\a$expr\a";
1982       warn $@ if $@;
1983       print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1984     }
1985   }
1986 }
1987
1988 1;
1989
1990 # vim: ts=2 sw=2 et: