This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
check_conditional_preprocessor_statements is not a method
[perl5.git] / dist / ExtUtils-ParseXS / lib / ExtUtils / ParseXS.pm
1 package ExtUtils::ParseXS;
2 use strict;
3
4 use 5.006;  # 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 use ExtUtils::ParseXS::Constants ();
12 use ExtUtils::ParseXS::CountLines;
13 use ExtUtils::ParseXS::Utilities qw(
14   standard_typemap_locations
15   trim_whitespace
16   tidy_type
17   C_string
18   valid_proto_string
19   process_typemaps
20   make_targetable
21   map_type
22   standard_XS_defs
23   assign_func_args
24   analyze_preprocessor_statements
25   set_cond
26   Warn
27   blurt
28   death
29   check_conditional_preprocessor_statements
30 );
31
32 our @ISA = qw(Exporter);
33 our @EXPORT_OK = qw(
34   process_file
35   report_error_count
36 );
37 our $VERSION = '3';
38 $VERSION = eval $VERSION if $VERSION =~ /_/;
39
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.
43 our (
44   $FH, $Package, $func_name, $Full_func_name, $pname, $ALIAS,
45 );
46
47 our $self = bless {} => __PACKAGE__;
48
49 sub process_file {
50
51   # Allow for $package->process_file(%hash) in the future
52   my ($pkg, %options) = @_ % 2 ? @_ : (__PACKAGE__, @_);
53
54   $self->{ProtoUsed} = exists $options{prototypes};
55
56   # Set defaults.
57   my %args = (
58     argtypes        => 1,
59     csuffix         => '.c',
60     except          => 0,
61     hiertype        => 0,
62     inout           => 1,
63     linenumbers     => 1,
64     optimize        => 1,
65     output          => \*STDOUT,
66     prototypes      => 0,
67     typemap         => [],
68     versioncheck    => 1,
69     %options,
70   );
71   $args{except} = $args{except} ? ' TRY' : '';
72
73   # Global Constants
74
75   my ($Is_VMS, $SymSet);
76   if ($^O eq 'VMS') {
77     $Is_VMS = 1;
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);
82   }
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;
89
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
92   # of %args.  -Ken
93
94   $self->{hiertype} = $args{hiertype};
95   $self->{WantPrototypes} = $args{prototypes};
96   $self->{WantVersionChk} = $args{versioncheck};
97   $self->{WantLineNumbers} = $args{linenumbers};
98   $self->{IncludedFiles} = {};
99
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}}++;
106
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};
112     $args{output} = $fh;
113   }
114
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();
119
120   chdir($self->{dir});
121   my $pwd = cwd();
122   my $csuffix = $args{csuffix};
123
124   if ($self->{WantLineNumbers}) {
125     my $cfile;
126     if ( $args{outfile} ) {
127       $cfile = $args{outfile};
128     }
129     else {
130       $cfile = $args{filename};
131       $cfile =~ s/\.xs$/$csuffix/i or $cfile .= $csuffix;
132     }
133     tie(*PSEUDO_STDOUT, 'ExtUtils::ParseXS::CountLines', $cfile, $args{output});
134     select PSEUDO_STDOUT;
135   }
136   else {
137     select $args{output};
138   }
139
140   $self->{typemap} = process_typemaps( $args{typemap}, $pwd );
141
142   my $END = "!End!\n\n";        # "impossible" keyword (multiple newline)
143
144   # Match an XS keyword
145   $self->{BLOCK_re} = '\s*(' .
146     join('|' => @ExtUtils::ParseXS::Constants::XSKeywords) .
147     "|$END)\\s*:";
148
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 }) )*
153                [)}\]] /x;
154   # Chunk in C without comma at toplevel (no comments):
155   $C_arg = qr/ (?: (?> [^()\[\]{},"']+ )
156          |   (??{ $C_group_rex })
157          |   " (?: (?> [^\\"]+ )
158            |   \\.
159            )* "        # String literal
160                 |   ' (?: (?> [^\\']+ ) | \\. )* ' # Char literal
161          )* /xs;
162
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
171
172   foreach my $datum ( qw| argtypes except inout optimize | ) {
173     $self->{$datum} = $args{$datum};
174   }
175
176   # Identify the version of xsubpp used
177   print <<EOM;
178 /*
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.
181  *
182  *    ANY CHANGES MADE HERE WILL BE LOST!
183  *
184  */
185
186 EOM
187
188
189   print("#line 1 \"$self->{filepathname}\"\n")
190     if $self->{WantLineNumbers};
191
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";
195
196   firstmodule:
197   while (<$FH>) {
198     if (/^=/) {
199       my $podstartline = $.;
200       do {
201         if (/^=cut\s*$/) {
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.
214           #     - Nicholas Clark
215           print("#if 0\n  \"Skipped embedded POD.\"\n#endif\n");
216           printf("#line %d \"$self->{filepathname}\"\n", $. + 1)
217             if $self->{WantLineNumbers};
218           next firstmodule
219         }
220
221       } while (<$FH>);
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};
227     }
228     last if ($Package, $self->{Prefix}) =
229       /^MODULE\s*=\s*[\w:]+(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
230
231     print $_;
232   }
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
236   }
237
238   print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
239
240   standard_XS_defs();
241
242   print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
243
244   $self->{lastline}    = $_;
245   $self->{lastline_no} = $.;
246
247   my $BootCode_ref = [];
248   my $XSS_work_idx = 0;
249   my $cpp_next_tmp = 'XSubPPtmpAAAA';
250  PARAGRAPH:
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} });
256       print $ln, "\n";
257       next unless $ln =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
258       my $statement = $+;
259       ( $self, $XSS_work_idx, $BootCode_ref ) =
260         analyze_preprocessor_statements(
261           $self, $statement, $XSS_work_idx, $BootCode_ref
262         );
263     }
264
265     next PARAGRAPH unless @{ $self->{line} };
266
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++;
273     }
274
275     death( $self,
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/;
280
281     # initialize info arrays
282     foreach my $member (qw(args_match var_types defaults arg_list
283                            argtype_seen in_out lengthof))
284     {
285       $self->{$member} = {};
286     }
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;
296
297     my $xsreturn = 0;
298
299     $_ = shift(@{ $self->{line} });
300     while (my $kwd = $self->check_keyword("REQUIRE|PROTOTYPES|FALLBACK|VERSIONCHECK|INCLUDE(?:_COMMAND)?|SCOPE")) {
301       my $method = $kwd . "_handler";
302       $self->$method($_);
303       next PARAGRAPH unless @{ $self->{line} };
304       $_ = shift(@{ $self->{line} });
305     }
306
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} }, "");
312       next PARAGRAPH;
313     }
314
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+//;
318
319     # Allow one-line ANSI-like declaration
320     unshift @{ $self->{line} }, $2
321       if $self->{argtypes}
322         and $self->{ret_type} =~ s/^(.*?\w.*?)\s*\b(\w+\s*\(.*)/$1/s;
323
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} };
327
328     my $externC = 1 if $self->{ret_type} =~ s/^extern "C"\s+//;
329     my $static  = 1 if $self->{ret_type} =~ s/^static\s+//;
330
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;
334
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}/;
339     my $clean_func_name;
340     ($clean_func_name = $func_name) =~ s/^$self->{Prefix}//;
341     $Full_func_name = "$self->{Packid}_$clean_func_name";
342     if ($Is_VMS) {
343       $Full_func_name = $SymSet->addsym($Full_func_name);
344     }
345
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");
350       last;
351     }
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;
358
359     $orig_args =~ s/\\\s*/ /g;    # process line continuations
360     my @args;
361
362     my (@fake_INPUT_pre);    # For length(s) generated variables
363     my (@fake_INPUT);
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);
369         for ( @args ) {
370           s/^\s+//;
371           s/\s+$//;
372           my ($arg, $default) = ($_ =~ m/ ( [^=]* ) ( (?: = .* )? ) /x);
373           my ($pre, $len_name) = ($arg =~ /(.*?) \s*
374                              \b ( \w+ | length\( \s*\w+\s* \) )
375                              \s* $ /x);
376           next unless defined($pre) && length($pre);
377           my $out_type = '';
378           my $inout_var;
379           if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|OUT|IN_OUT)\b\s*//) {
380             my $type = $1;
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*//;
384           }
385           my $islength;
386           if ($len_name =~ /^length\( \s* (\w+) \s* \)\z/x) {
387             $len_name = "XSauto_length_of_$1";
388             $islength = 1;
389             die "Default value on length() argument: `$_'"
390               if length $default;
391           }
392           if (length $pre or $islength) { # Has a type
393             if ($islength) {
394               push @fake_INPUT_pre, $arg;
395             }
396             else {
397               push @fake_INPUT, $arg;
398             }
399             # warn "pushing '$arg'\n";
400             $self->{argtype_seen}->{$len_name}++;
401             $_ = "$len_name$default"; # Assigns to @args
402           }
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;
406         }
407       }
408       else {
409         @args = split(/\s*,\s*/, $orig_args);
410         Warn( $self, "Warning: cannot parse argument list '$orig_args', fallback to split");
411       }
412     }
413     else {
414       @args = split(/\s*,\s*/, $orig_args);
415       for (@args) {
416         if ($self->{inout} and s/^(IN|IN_OUTLIST|OUTLIST|IN_OUT|OUT)\b\s*//) {
417           my $out_type = $1;
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;
422           }
423           $self->{in_out}->{$_} = $out_type;
424         }
425       }
426     }
427     if (defined($class)) {
428       my $arg0 = ((defined($static) or $func_name eq 'new')
429           ? "CLASS" : "THIS");
430       unshift(@args, $arg0);
431     }
432     my $extra_args = 0;
433     my @args_num = ();
434     my $num_args = 0;
435     my $report_args = '';
436     my $ellipsis;
437     foreach my $i (0 .. $#args) {
438       if ($args[$i] =~ s/\.\.\.//) {
439         $ellipsis = 1;
440         if ($args[$i] eq '' && $i == $#args) {
441           $report_args .= ", ...";
442           pop(@args);
443           last;
444         }
445       }
446       if ($only_C_inlist_ref->{$args[$i]}) {
447         push @args_num, undef;
448       }
449       else {
450         push @args_num, ++$num_args;
451           $report_args .= ", $args[$i]";
452       }
453       if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
454         $extra_args++;
455         $args[$i] = $1;
456         $self->{defaults}->{$args[$i]} = $2;
457         $self->{defaults}->{$args[$i]} =~ s/"/\\"/g;
458       }
459       $self->{proto_arg}->[$i+1] = '$';
460     }
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;
466
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 ));
473
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:
481     # 388c388
482     # <                       GvNAME(CvGV(cv)),
483     # ---
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} });
488
489     my $INTERFACE  = grep(/^\s*INTERFACE\s*:/,  @{ $self->{line} });
490
491     $xsreturn = 1 if $EXPLICIT_RETURN;
492
493     $externC = $externC ? qq[extern "C"] : "";
494
495     # print function header
496     print Q(<<"EOF");
497 #$externC
498 #XS(XS_${Full_func_name}); /* prototype to pass -Wmissing-prototypes */
499 #XS(XS_${Full_func_name})
500 #[[
501 ##ifdef dVAR
502 #    dVAR; dXSARGS;
503 ##else
504 #    dXSARGS;
505 ##endif
506 EOF
507     print Q(<<"EOF") if $ALIAS;
508 #    dXSI32;
509 EOF
510     print Q(<<"EOF") if $INTERFACE;
511 #    dXSFUNCTION($self->{ret_type});
512 EOF
513
514     $self->{cond} = set_cond($ellipsis, $min_args, $num_args);
515
516     print Q(<<"EOF") if $self->{except};
517 #    char errbuf[1024];
518 #    *errbuf = '\0';
519 EOF
520
521     if($self->{cond}) {
522       print Q(<<"EOF");
523 #    if ($self->{cond})
524 #       croak_xs_usage(cv,  "$report_args");
525 EOF
526     }
527     else {
528     # cv likely to be unused
529     print Q(<<"EOF");
530 #    PERL_UNUSED_VAR(cv); /* -W */
531 EOF
532     }
533
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 */
541 EOF
542
543     print Q(<<"EOF") if $PPCODE;
544 #    SP -= items;
545 EOF
546
547     # Now do a block of some sort.
548
549     $self->{condnum} = 0;
550     $self->{cond} = '';            # last CASE: conditional
551     push(@{ $self->{line} }, "$END:");
552     push(@{ $self->{line_no} }, $self->{line_no}->[-1]);
553     $_ = '';
554     check_conditional_preprocessor_statements();
555     while (@{ $self->{line} }) {
556       $self->CASE_handler($_) if $self->check_keyword("CASE");
557       print Q(<<"EOF");
558 #   $self->{except} [[
559 EOF
560
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;
567
568       $self->INPUT_handler($_);
569       $self->process_keyword("INPUT|PREINIT|INTERFACE_MACRO|C_ARGS|ALIAS|ATTRS|PROTOTYPE|SCOPE|OVERLOAD");
570
571       print Q(<<"EOF") if $self->{ScopeThisXSUB};
572 #   ENTER;
573 #   [[
574 EOF
575
576       if (!$self->{thisdone} && defined($class)) {
577         if (defined($static) or $func_name eq 'new') {
578           print "\tchar *";
579           $self->{var_types}->{"CLASS"} = "char *";
580           generate_init( {
581             type          => "char *",
582             num           => 1,
583             var           => "CLASS",
584             printed_name  => undef,
585           } );
586         }
587         else {
588           print "\t$class *";
589           $self->{var_types}->{"THIS"} = "$class *";
590           generate_init( {
591             type          => "$class *",
592             num           => 1,
593             var           => "THIS",
594             printed_name  => undef,
595           } );
596         }
597       }
598
599       my ($wantRETVAL);
600       # do code
601       if (/^\s*NOT_IMPLEMENTED_YET/) {
602         print "\n\tPerl_croak(aTHX_ \"$pname: not implemented yet\");\n";
603         $_ = '';
604       }
605       else {
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} );
612           print "\tdXSTARG;\n"
613             if $self->{optimize} and $outputmap and $outputmap->targetable;
614         }
615
616         if (@fake_INPUT or @fake_INPUT_pre) {
617           unshift @{ $self->{line} }, @fake_INPUT_pre, @fake_INPUT, $_;
618           $_ = "";
619           $self->{processing_arg_with_types} = 1;
620           $self->INPUT_handler($_);
621         }
622         print $self->{deferred};
623
624         $self->process_keyword("INIT|ALIAS|ATTRS|PROTOTYPE|INTERFACE_MACRO|INTERFACE|C_ARGS|OVERLOAD");
625
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";
631         }
632         elsif ($self->check_keyword("CODE")) {
633           $self->print_section();
634         }
635         elsif (defined($class) and $func_name eq "DESTROY") {
636           print "\n\t";
637           print "delete THIS;\n";
638         }
639         else {
640           print "\n\t";
641           if ($self->{ret_type} ne "void") {
642             print "RETVAL = ";
643             $wantRETVAL = 1;
644           }
645           if (defined($static)) {
646             if ($func_name eq 'new') {
647               $func_name = "$class";
648             }
649             else {
650               print "${class}::";
651             }
652           }
653           elsif (defined($class)) {
654             if ($func_name eq 'new') {
655               $func_name .= " $class";
656             }
657             else {
658               print "THIS->";
659             }
660           }
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";
665         }
666       }
667
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");
675
676       generate_output( {
677         type        => $self->{var_types}->{$_},
678         num         => $self->{args_match}->{$_},
679         var         => $_,
680         do_setmagic => $self->{DoSetMagic},
681         do_push     => undef,
682       } ) for grep $self->{in_out}->{$_} =~ /OUT$/, keys %{ $self->{in_out} };
683
684       my $prepush_done;
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";
688       }
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
695         # below.
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:
699         # <i> <> <(IV)$var>
700         my $var = 'RETVAL';
701         my $type = $self->{ret_type};
702
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}");
706           warn $@ if $@;
707
708           print "\tsv_setpv(TARG, $what); XSprePUSH; PUSHTARG;\n";
709           $prepush_done = 1;
710         }
711         elsif ($t) {
712           my $what = eval qq("$t->{what}");
713           warn $@ if $@;
714
715           my $tsize = $t->{what_size};
716           $tsize = '' unless defined $tsize;
717           $tsize = eval qq("$tsize");
718           warn $@ if $@;
719           print "\tXSprePUSH; PUSH$t->{type}($what$tsize);\n";
720           $prepush_done = 1;
721         }
722         else {
723           # RETVAL almost never needs SvSETMAGIC()
724           generate_output( {
725             type        => $self->{ret_type},
726             num         => 0,
727             var         => 'RETVAL',
728             do_setmagic => 0,
729             do_push     => undef,
730           } );
731         }
732       }
733
734       $xsreturn = 1 if $self->{ret_type} ne "void";
735       my $num = $xsreturn;
736       my $c = @{ $outlist_ref };
737       print "\tXSprePUSH;" if $c and not $prepush_done;
738       print "\tEXTEND(SP,$c);\n" if $c;
739       $xsreturn += $c;
740       generate_output( {
741         type        => $self->{var_types}->{$_},
742         num         => $num++,
743         var         => $_,
744         do_setmagic => 0,
745         do_push     => 1,
746       } ) for @{ $outlist_ref };
747
748       # do cleanup
749       $self->process_keyword("CLEANUP|ALIAS|ATTRS|PROTOTYPE|OVERLOAD");
750
751       print Q(<<"EOF") if $self->{ScopeThisXSUB};
752 #   ]]
753 EOF
754       print Q(<<"EOF") if $self->{ScopeThisXSUB} and not $PPCODE;
755 #   LEAVE;
756 EOF
757
758       # print function trailer
759       print Q(<<"EOF");
760 #    ]]
761 EOF
762       print Q(<<"EOF") if $self->{except};
763 #    BEGHANDLERS
764 #    CATCHALL
765 #    sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
766 #    ENDHANDLERS
767 EOF
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
772         next;
773       }
774       last if $_ eq "$END:";
775       death( $self,
776         /^$self->{BLOCK_re}/o ? "Misplaced `$1:'" : "Junk at end of function ($_)");
777     }
778
779     print Q(<<"EOF") if $self->{except};
780 #    if (errbuf[0])
781 #    Perl_croak(aTHX_ errbuf);
782 EOF
783
784     if ($xsreturn) {
785       print Q(<<"EOF") unless $PPCODE;
786 #    XSRETURN($xsreturn);
787 EOF
788     }
789     else {
790       print Q(<<"EOF") unless $PPCODE;
791 #    XSRETURN_EMPTY;
792 EOF
793     }
794
795     print Q(<<"EOF");
796 #]]
797 #
798 EOF
799
800     $self->{newXS} = "newXS";
801     $self->{proto} = "";
802
803     # Build the prototype string for the xsub
804     if ($self->{ProtoThisXSUB}) {
805       $self->{newXS} = "newXSproto_portable";
806
807       if ($self->{ProtoThisXSUB} eq 2) {
808         # User has specified empty prototype
809       }
810       elsif ($self->{ProtoThisXSUB} eq 1) {
811         my $s = ';';
812         if ($min_args < $num_args)  {
813           $s = '';
814           $self->{proto_arg}->[$min_args] .= ";";
815         }
816         push @{ $self->{proto_arg} }, "$s\@"
817           if $ellipsis;
818
819         $self->{proto} = join ("", grep defined, @{ $self->{proto_arg} } );
820       }
821       else {
822         # User has specified a prototype
823         $self->{proto} = $self->{ProtoThisXSUB};
824       }
825       $self->{proto} = qq{, "$self->{proto}"};
826     }
827
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;
835 EOF
836       }
837     }
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);
842 EOF
843     }
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);
850 EOF
851       }
852     }
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");
856     }
857     else {
858       push(@{ $self->{InitFileCode} },
859        "        (void)$self->{newXS}(\"$pname\", XS_$Full_func_name, file$self->{proto});\n");
860     }
861   } # END 'PARAGRAPH' 'while' loop
862
863   if ($self->{Overload}) { # make it findable with fetchmethod
864     print Q(<<"EOF");
865 #XS(XS_$self->{Packid}_nil); /* prototype to pass -Wmissing-prototypes */
866 #XS(XS_$self->{Packid}_nil)
867 #{
868 #   dXSARGS;
869 #   XSRETURN_EMPTY;
870 #}
871 #
872 EOF
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
879   }
880
881   # print initialization routine
882
883   print Q(<<"EOF");
884 ##ifdef __cplusplus
885 #extern "C"
886 ##endif
887 EOF
888
889   print Q(<<"EOF");
890 #XS(boot_$self->{Module_cname}); /* prototype to pass -Wmissing-prototypes */
891 #XS(boot_$self->{Module_cname})
892 EOF
893
894   print Q(<<"EOF");
895 #[[
896 ##ifdef dVAR
897 #    dVAR; dXSARGS;
898 ##else
899 #    dXSARGS;
900 ##endif
901 EOF
902
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
907   #so `file' is unused
908   print Q(<<"EOF") if $Full_func_name;
909 ##if (PERL_REVISION == 5 && PERL_VERSION < 9)
910 #    char* file = __FILE__;
911 ##else
912 #    const char* file = __FILE__;
913 ##endif
914 EOF
915
916   print Q("#\n");
917
918   print Q(<<"EOF");
919 #    PERL_UNUSED_VAR(cv); /* -W */
920 #    PERL_UNUSED_VAR(items); /* -W */
921 ##ifdef XS_APIVERSION_BOOTCHECK
922 #    XS_APIVERSION_BOOTCHECK;
923 ##endif
924 EOF
925
926   print Q(<<"EOF") if $self->{WantVersionChk};
927 #    XS_VERSION_BOOTCHECK;
928 #
929 EOF
930
931   print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
932 #    {
933 #        CV * cv;
934 #
935 EOF
936
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. */
943 #    sv_setsv(
944 #        get_sv( "${Package}::()", TRUE ),
945 #        $self->{Fallback}
946 #    );
947 EOF
948
949   print @{ $self->{InitFileCode} };
950
951   print Q(<<"EOF") if defined $self->{xsubaliases} or defined $self->{interfaces};
952 #    }
953 EOF
954
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";
960   }
961
962   print Q(<<'EOF');
963 ##if (PERL_REVISION == 5 && PERL_VERSION >= 9)
964 #  if (PL_unitcheckav)
965 #       call_list(PL_scopestack_ix, PL_unitcheckav);
966 ##endif
967 EOF
968
969   print Q(<<"EOF");
970 #    XSRETURN_YES;
971 #]]
972 #
973 EOF
974
975   warn("Please specify prototyping behavior for $self->{filename} (see perlxs manual)\n")
976     unless $self->{ProtoUsed};
977
978   chdir($orig_cwd);
979   select($orig_fh);
980   untie *PSEUDO_STDOUT if tied *PSEUDO_STDOUT;
981   close $FH;
982
983   return 1;
984 }
985
986 sub report_error_count { $self->{errors} }
987
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
991 sub check_keyword {
992   my $self = shift;
993   $_ = shift(@{ $self->{line} }) while !/\S/ && @{ $self->{line} };
994   s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
995 }
996
997 sub print_section {
998   my $self = shift;
999
1000   # the "do" is required for right semantics
1001   do { $_ = shift(@{ $self->{line} }) } while !/\S/ && @{ $self->{line} };
1002
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} })) {
1006     print "$_\n";
1007   }
1008   print 'ExtUtils::ParseXS::CountLines'->end_marker, "\n" if $self->{WantLineNumbers};
1009 }
1010
1011 sub merge_section {
1012   my $self = shift;
1013   my $in = '';
1014
1015   while (!/\S/ && @{ $self->{line} }) {
1016     $_ = shift(@{ $self->{line} });
1017   }
1018
1019   for (;  defined($_) && !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1020     $in .= "$_\n";
1021   }
1022   chomp $in;
1023   return $in;
1024 }
1025
1026 sub process_keyword {
1027   my($self, $pattern) = @_;
1028
1029   while (my $kwd = $self->check_keyword($pattern)) {
1030     my $method = $kwd . "_handler";
1031     $self->$method($_);
1032   }
1033 }
1034
1035 sub CASE_handler {
1036   my $self = shift;
1037   $_ = shift;
1038   blurt( $self, "Error: `CASE:' after unconditional `CASE:'")
1039     if $self->{condnum} && $self->{cond} eq '';
1040   $self->{cond} = $_;
1041   trim_whitespace($self->{cond});
1042   print "   ", ($self->{condnum}++ ? " else" : ""), ($self->{cond} ? " if ($self->{cond})\n" : "\n");
1043   $_ = '';
1044 }
1045
1046 sub INPUT_handler {
1047   my $self = shift;
1048   $_ = shift;
1049   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1050     last if /^\s*NOT_IMPLEMENTED_YET/;
1051     next unless /\S/;        # skip blank lines
1052
1053     trim_whitespace($_);
1054     my $ln = $_;
1055
1056     # remove trailing semicolon if no initialisation
1057     s/\s*;$//g unless /[=;+].*\S/;
1058
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";
1064     }
1065
1066     # check for optional initialisation code
1067     my $var_init = '';
1068     $var_init = $1 if s/\s*([=;+].*)$//s;
1069     $var_init =~ s/"/\\"/g;
1070
1071     s/\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;
1074
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};
1079
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.
1086     my $printed_name;
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);
1090       $printed_name = 1;
1091     }
1092     else {
1093       print "\t" . map_type($self, $var_type, undef);
1094       $printed_name = 0;
1095     }
1096     $self->{var_num} = $self->{args_match}->{$var_name};
1097
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) || "\$";
1101     }
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) {
1107         print ";\n";
1108       }
1109       else {
1110         print "\t$var_name;\n";
1111       }
1112     }
1113     elsif ($var_init =~ /\S/) {
1114       output_init( {
1115         type          => $var_type,
1116         num           => $self->{var_num},
1117         var           => $var_name,
1118         init          => $var_init,
1119         printed_name  => $printed_name,
1120       } );
1121     }
1122     elsif ($self->{var_num}) {
1123       generate_init( {
1124         type          => $var_type,
1125         num           => $self->{var_num},
1126         var           => $var_name,
1127         printed_name  => $printed_name,
1128       } );
1129     }
1130     else {
1131       print ";\n";
1132     }
1133   }
1134 }
1135
1136 sub OUTPUT_handler {
1137   my $self = shift;
1138   $_ = shift;
1139   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1140     next unless /\S/;
1141     if (/^\s*SETMAGIC\s*:\s*(ENABLE|DISABLE)\s*/) {
1142       $self->{DoSetMagic} = ($1 eq "ENABLE" ? 1 : 0);
1143       next;
1144     }
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;
1152       next;
1153     }
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};
1159     if ($outcode) {
1160       print "\t$outcode\n";
1161       print "\tSvSETMAGIC(ST(" , $self->{var_num} - 1 , "));\n" if $self->{DoSetMagic};
1162     }
1163     else {
1164       generate_output( {
1165         type        => $self->{var_types}->{$outarg},
1166         num         => $self->{var_num},
1167         var         => $outarg,
1168         do_setmagic => $self->{DoSetMagic},
1169         do_push     => undef,
1170       } );
1171     }
1172     delete $self->{in_out}->{$outarg}     # No need to auto-OUTPUT
1173       if exists $self->{in_out}->{$outarg} and $self->{in_out}->{$outarg} =~ /OUT$/;
1174   }
1175 }
1176
1177 sub C_ARGS_handler {
1178   my $self = shift;
1179   $_ = shift;
1180   my $in = $self->merge_section();
1181
1182   trim_whitespace($in);
1183   $self->{func_args} = $in;
1184 }
1185
1186 sub INTERFACE_MACRO_handler {
1187   my $self = shift;
1188   $_ = shift;
1189   my $in = $self->merge_section();
1190
1191   trim_whitespace($in);
1192   if ($in =~ /\s/) {        # two
1193     ($self->{interface_macro}, $self->{interface_macro_set}) = split ' ', $in;
1194   }
1195   else {
1196     $self->{interface_macro} = $in;
1197     $self->{interface_macro_set} = 'UNKNOWN_CVT'; # catch later
1198   }
1199   $self->{interface} = 1;        # local
1200   $self->{interfaces} = 1;        # global
1201 }
1202
1203 sub INTERFACE_handler {
1204   my $self = shift;
1205   $_ = shift;
1206   my $in = $self->merge_section();
1207
1208   trim_whitespace($in);
1209
1210   foreach (split /[\s,]+/, $in) {
1211     my $iface_name = $_;
1212     $iface_name =~ s/^$self->{Prefix}//;
1213     $self->{Interfaces}->{$iface_name} = $_;
1214   }
1215   print Q(<<"EOF");
1216 #    XSFUNCTION = $self->{interface_macro}($self->{ret_type},cv,XSANY.any_dptr);
1217 EOF
1218   $self->{interface} = 1;        # local
1219   $self->{interfaces} = 1;        # global
1220 }
1221
1222 sub CLEANUP_handler {
1223   my $self = shift;
1224   $self->print_section();
1225 }
1226
1227 sub PREINIT_handler {
1228   my $self = shift;
1229   $self->print_section();
1230 }
1231
1232 sub POSTCALL_handler {
1233   my $self = shift;
1234   $self->print_section();
1235 }
1236
1237 sub INIT_handler {
1238   my $self = shift;
1239   $self->print_section();
1240 }
1241
1242 sub get_aliases {
1243   my $self = shift;
1244   my ($line) = @_;
1245   my ($orig) = $line;
1246
1247   # Parse alias definitions
1248   # format is
1249   #    alias = value alias = value ...
1250
1251   while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
1252     my ($alias, $value) = ($1, $2);
1253     my $orig_alias = $alias;
1254
1255     # check for optional package definition in the alias
1256     $alias = $self->{Packprefix} . $alias if $alias !~ /::/;
1257
1258     # check for duplicate alias name & duplicate value
1259     Warn( $self, "Warning: Ignoring duplicate alias '$orig_alias'")
1260       if defined $self->{XsubAliases}->{$alias};
1261
1262     Warn( $self, "Warning: Aliases '$orig_alias' and '$self->{XsubAliasValues}->{$value}' have identical values")
1263       if $self->{XsubAliasValues}->{$value};
1264
1265     $self->{xsubaliases} = 1;
1266     $self->{XsubAliases}->{$alias} = $value;
1267     $self->{XsubAliasValues}->{$value} = $orig_alias;
1268   }
1269
1270   blurt( $self, "Error: Cannot parse ALIAS definitions from '$orig'")
1271     if $line;
1272 }
1273
1274 sub ATTRS_handler {
1275   my $self = shift;
1276   $_ = shift;
1277
1278   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1279     next unless /\S/;
1280     trim_whitespace($_);
1281     push @{ $self->{Attributes} }, $_;
1282   }
1283 }
1284
1285 sub ALIAS_handler {
1286   my $self = shift;
1287   $_ = shift;
1288
1289   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1290     next unless /\S/;
1291     trim_whitespace($_);
1292     $self->get_aliases($_) if $_;
1293   }
1294 }
1295
1296 sub OVERLOAD_handler {
1297   my $self = shift;
1298   $_ = shift;
1299
1300   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1301     next unless /\S/;
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");
1308     }
1309   }
1310 }
1311
1312 sub FALLBACK_handler {
1313   my $self = shift;
1314   $_ = shift;
1315
1316   # the rest of the current line should contain either TRUE,
1317   # FALSE or UNDEF
1318
1319   trim_whitespace($_);
1320   my %map = (
1321     TRUE => "&PL_sv_yes", 1 => "&PL_sv_yes",
1322     FALSE => "&PL_sv_no", 0 => "&PL_sv_no",
1323     UNDEF => "&PL_sv_undef",
1324   );
1325
1326   # check for valid FALLBACK value
1327   death( $self, "Error: FALLBACK: TRUE/FALSE/UNDEF") unless exists $map{uc $_};
1328
1329   $self->{Fallback} = $map{uc $_};
1330 }
1331
1332
1333 sub REQUIRE_handler {
1334   my $self = shift;
1335   # the rest of the current line should contain a version number
1336   my $Ver = shift;
1337
1338   trim_whitespace($Ver);
1339
1340   death( $self, "Error: REQUIRE expects a version number")
1341     unless $Ver;
1342
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*)?/;
1346
1347   death( $self, "Error: xsubpp $Ver (or better) required--this is only $VERSION.")
1348     unless $VERSION >= $Ver;
1349 }
1350
1351 sub VERSIONCHECK_handler {
1352   my $self = shift;
1353   $_ = shift;
1354
1355   # the rest of the current line should contain either ENABLE or
1356   # DISABLE
1357
1358   trim_whitespace($_);
1359
1360   # check for ENABLE/DISABLE
1361   death( $self, "Error: VERSIONCHECK: ENABLE/DISABLE")
1362     unless /^(ENABLE|DISABLE)/i;
1363
1364   $self->{WantVersionChk} = 1 if $1 eq 'ENABLE';
1365   $self->{WantVersionChk} = 0 if $1 eq 'DISABLE';
1366
1367 }
1368
1369 sub PROTOTYPE_handler {
1370   my $self = shift;
1371   $_ = shift;
1372
1373   my $specified;
1374
1375   death( $self, "Error: Only 1 PROTOTYPE definition allowed per xsub")
1376     if $self->{proto_in_this_xsub}++;
1377
1378   for (;  !/^$self->{BLOCK_re}/o;  $_ = shift(@{ $self->{line} })) {
1379     next unless /\S/;
1380     $specified = 1;
1381     trim_whitespace($_);
1382     if ($_ eq 'DISABLE') {
1383       $self->{ProtoThisXSUB} = 0;
1384     }
1385     elsif ($_ eq 'ENABLE') {
1386       $self->{ProtoThisXSUB} = 1;
1387     }
1388     else {
1389       # remove any whitespace
1390       s/\s+//g;
1391       death( $self, "Error: Invalid prototype '$_'")
1392         unless valid_proto_string($_);
1393       $self->{ProtoThisXSUB} = C_string($_);
1394     }
1395   }
1396
1397   # If no prototype specified, then assume empty prototype ""
1398   $self->{ProtoThisXSUB} = 2 unless $specified;
1399
1400   $self->{ProtoUsed} = 1;
1401 }
1402
1403 sub SCOPE_handler {
1404   my $self = shift;
1405   $_ = shift;
1406
1407   death( $self, "Error: Only 1 SCOPE declaration allowed per xsub")
1408     if $self->{scope_in_this_xsub}++;
1409
1410   trim_whitespace($_);
1411   death("Error: SCOPE: ENABLE/DISABLE")
1412       unless /^(ENABLE|DISABLE)\b/i;
1413   $self->{ScopeThisXSUB} = ( uc($1) eq 'ENABLE' );
1414 }
1415
1416 sub PROTOTYPES_handler {
1417   my $self = shift;
1418   $_ = shift;
1419
1420   # the rest of the current line should contain either ENABLE or
1421   # DISABLE
1422
1423   trim_whitespace($_);
1424
1425   # check for ENABLE/DISABLE
1426   death("Error: PROTOTYPES: ENABLE/DISABLE")
1427     unless /^(ENABLE|DISABLE)/i;
1428
1429   $self->{WantPrototypes} = 1 if $1 eq 'ENABLE';
1430   $self->{WantPrototypes} = 0 if $1 eq 'DISABLE';
1431   $self->{ProtoUsed} = 1;
1432 }
1433
1434 sub PushXSStack {
1435   my $self = shift;
1436   my %args = @_;
1437   # Save the current file context.
1438   push(@{ $self->{XSStack} }, {
1439           type            => 'file',
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},
1446           Handle          => $FH,
1447           IsPipe          => scalar($self->{filename} =~ /\|\s*$/),
1448           %args,
1449          });
1450
1451 }
1452
1453 sub INCLUDE_handler {
1454   my $self = shift;
1455   $_ = shift;
1456   # the rest of the current line should contain a valid filename
1457
1458   trim_whitespace($_);
1459
1460   death( $self, "INCLUDE: filename missing")
1461     unless $_;
1462
1463   death( $self, "INCLUDE: output pipe is illegal")
1464     if /^\s*\|/;
1465
1466   # simple minded recursion detector
1467   death( $self, "INCLUDE loop detected")
1468     if $self->{IncludedFiles}->{$_};
1469
1470   ++$self->{IncludedFiles}->{$_} unless /\|\s*$/;
1471
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.");
1479   }
1480
1481   $self->PushXSStack();
1482
1483   $FH = Symbol::gensym();
1484
1485   # open the new file
1486   open ($FH, "$_") or death( $self, "Cannot open '$_': $!");
1487
1488   print Q(<<"EOF");
1489 #
1490 #/* INCLUDE:  Including '$_' from '$self->{filename}' */
1491 #
1492 EOF
1493
1494   $self->{filename} = $_;
1495   $self->{filepathname} = File::Spec->catfile($self->{dir}, $self->{filename});
1496
1497   # Prime the pump by reading the first
1498   # non-blank line
1499
1500   # skip leading blank lines
1501   while (<$FH>) {
1502     last unless /^\s*$/;
1503   }
1504
1505   $self->{lastline} = $_;
1506   $self->{lastline_no} = $.;
1507 }
1508
1509 sub QuoteArgs {
1510   my $cmd = shift;
1511   my @args = split /\s+/, $cmd;
1512   $cmd = shift @args;
1513   for (@args) {
1514     $_ = q(").$_.q(") if !/^\"/ && length($_) > 0;
1515   }
1516   return join (' ', ($cmd, @args));
1517 }
1518
1519 sub INCLUDE_COMMAND_handler {
1520   my $self = shift;
1521   $_ = shift;
1522   # the rest of the current line should contain a valid command
1523
1524   trim_whitespace($_);
1525
1526   $_ = QuoteArgs($_) if $^O eq 'VMS';
1527
1528   death( $self, "INCLUDE_COMMAND: command missing")
1529     unless $_;
1530
1531   death( $self, "INCLUDE_COMMAND: pipes are illegal")
1532     if /^\s*\|/ or /\|\s*$/;
1533
1534   $self->PushXSStack( IsPipe => 1 );
1535
1536   $FH = Symbol::gensym();
1537
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
1540   s/^\s*\$\^X/$^X/;
1541
1542   # open the new file
1543   open ($FH, "-|", "$_")
1544     or death( $self, "Cannot run command '$_' to include its output: $!");
1545
1546   print Q(<<"EOF");
1547 #
1548 #/* INCLUDE_COMMAND:  Including output of '$_' from '$self->{filename}' */
1549 #
1550 EOF
1551
1552   $self->{filename} = $_;
1553   $self->{filepathname} = $self->{filename};
1554   $self->{filepathname} =~ s/\"/\\"/g;
1555
1556   # Prime the pump by reading the first
1557   # non-blank line
1558
1559   # skip leading blank lines
1560   while (<$FH>) {
1561     last unless /^\s*$/;
1562   }
1563
1564   $self->{lastline} = $_;
1565   $self->{lastline_no} = $.;
1566 }
1567
1568 sub PopFile {
1569   my $self = shift;
1570
1571   return 0 unless $self->{XSStack}->[-1]{type} eq 'file';
1572
1573   my $data     = pop @{ $self->{XSStack} };
1574   my $ThisFile = $self->{filename};
1575   my $isPipe   = $data->{IsPipe};
1576
1577   --$self->{IncludedFiles}->{$self->{filename}}
1578     unless $isPipe;
1579
1580   close $FH;
1581
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
1585   # #line directives.
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} };
1592
1593   if ($isPipe and $? ) {
1594     --$self->{lastline_no};
1595     print STDERR "Error reading from pipe '$ThisFile': $! in $self->{filename}, line $self->{lastline_no}\n" ;
1596     exit 1;
1597   }
1598
1599   print Q(<<"EOF");
1600 #
1601 #/* INCLUDE: Returning to '$self->{filename}' from '$ThisFile' */
1602 #
1603 EOF
1604
1605   return 1;
1606 }
1607
1608 sub Q {
1609   my($text) = @_;
1610   $text =~ s/^#//gm;
1611   $text =~ s/\[\[/{/g;
1612   $text =~ s/\]\]/}/g;
1613   $text;
1614 }
1615
1616 # Read next xsub into @{ $self->{line} } from ($lastline, <$FH>).
1617 sub fetch_para {
1618   my $self = shift;
1619
1620   # parse paragraph
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};
1626
1627   if ($self->{lastline} =~
1628       /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
1629     my $Module = $1;
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} = "";
1638   }
1639
1640   for (;;) {
1641     # Skip embedded PODs
1642     while ($self->{lastline} =~ /^=/) {
1643       while ($self->{lastline} = <$FH>) {
1644         last if ($self->{lastline} =~ /^=cut\s*$/);
1645       }
1646       death("Error: Unterminated pod") unless $self->{lastline};
1647       $self->{lastline} = <$FH>;
1648       chomp $self->{lastline};
1649       $self->{lastline} =~ s/^\s+$//;
1650     }
1651     if ($self->{lastline} !~ /^\s*#/ ||
1652     # CPP directives:
1653     #    ANSI:    if ifdef ifndef elif else endif define undef
1654     #        line error pragma
1655     #    gcc:    warning include_next
1656     #   obj-c:    import
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});
1662     }
1663
1664     # Read next line and continuation lines
1665     last unless defined($self->{lastline} = <$FH>);
1666     $self->{lastline_no} = $.;
1667     my $tmp_line;
1668     $self->{lastline} .= $tmp_line
1669       while ($self->{lastline} =~ /\\$/ && defined($tmp_line = <$FH>));
1670
1671     chomp $self->{lastline};
1672     $self->{lastline} =~ s/^\s+$//;
1673   }
1674   pop(@{ $self->{line} }), pop(@{ $self->{line_no} }) while @{ $self->{line} } && $self->{line}->[-1] eq "";
1675   1;
1676 }
1677
1678 sub output_init {
1679   my $argsref = shift;
1680   my ($type, $num, $var, $init, $printed_name) = (
1681     $argsref->{type},
1682     $argsref->{num},
1683     $argsref->{var},
1684     $argsref->{init},
1685     $argsref->{printed_name}
1686   );
1687   my $arg = "ST(" . ($num - 1) . ")";
1688
1689   if (  $init =~ /^=/  ) {
1690     if ($printed_name) {
1691       eval qq/print " $init\\n"/;
1692     }
1693     else {
1694       eval qq/print "\\t$var $init\\n"/;
1695     }
1696     warn $@ if $@;
1697   }
1698   else {
1699     if (  $init =~ s/^\+//  &&  $num  ) {
1700       generate_init( {
1701         type          => $type,
1702         num           => $num,
1703         var           => $var,
1704         printed_name  => $printed_name,
1705       } );
1706     }
1707     elsif ($printed_name) {
1708       print ";\n";
1709       $init =~ s/^;//;
1710     }
1711     else {
1712       eval qq/print "\\t$var;\\n"/;
1713       warn $@ if $@;
1714       $init =~ s/^;//;
1715     }
1716     $self->{deferred} .= eval qq/"\\n\\t$init\\n"/;
1717     warn $@ if $@;
1718   }
1719 }
1720
1721 sub generate_init {
1722   my $argsref = shift;
1723   my ($type, $num, $var, $printed_name) = (
1724     $argsref->{type},
1725     $argsref->{num},
1726     $argsref->{var},
1727     $argsref->{printed_name},
1728   );
1729   my $arg = "ST(" . ($num - 1) . ")";
1730   my ($argoff, $ntype);
1731   $argoff = $num - 1;
1732
1733   my $typemaps = $self->{typemap};
1734
1735   $type = tidy_type($type);
1736   blurt( $self, "Error: '$type' not in typemap"), return
1737     unless $typemaps->get_typemap(ctype => $type);
1738
1739   ($ntype = $type) =~ s/\s*\*/Ptr/g;
1740   my $subtype;
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};
1750     return;
1751   }
1752   $type =~ tr/:/_/ unless $self->{hiertype};
1753
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;
1757
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
1764       unless $subtypemap;
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/;
1775   }
1776   if ($expr =~ m#/\*.*scope.*\*/#i) {  # "scope" in C comments
1777     $self->{ScopeThisXSUB} = 1;
1778   }
1779   if (defined($self->{defaults}->{$var})) {
1780     $expr =~ s/(\t+)/$1    /g;
1781     $expr =~ s/        /\t/g;
1782     if ($printed_name) {
1783       print ";\n";
1784     }
1785     else {
1786       eval qq/print "\\t$var;\\n"/;
1787       warn $@ if $@;
1788     }
1789     if ($self->{defaults}->{$var} eq 'NO_INIT') {
1790       $self->{deferred} .= eval qq/"\\n\\tif (items >= $num) {\\n$expr;\\n\\t}\\n"/;
1791     }
1792     else {
1793       $self->{deferred} .= eval qq/"\\n\\tif (items < $num)\\n\\t    $var = $self->{defaults}->{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1794     }
1795     warn $@ if $@;
1796   }
1797   elsif ($self->{ScopeThisXSUB} or $expr !~ /^\s*\$var =/) {
1798     if ($printed_name) {
1799       print ";\n";
1800     }
1801     else {
1802       eval qq/print "\\t$var;\\n"/;
1803       warn $@ if $@;
1804     }
1805     $self->{deferred} .= eval qq/"\\n$expr;\\n"/;
1806     warn $@ if $@;
1807   }
1808   else {
1809     die "panic: do not know how to handle this branch for function pointers"
1810       if $printed_name;
1811     eval qq/print "$expr;\\n"/;
1812     warn $@ if $@;
1813   }
1814 }
1815
1816 sub generate_output {
1817   my $argsref = shift;
1818   my ($type, $num, $var, $do_setmagic, $do_push) = (
1819     $argsref->{type},
1820     $argsref->{num},
1821     $argsref->{var},
1822     $argsref->{do_setmagic},
1823     $argsref->{do_push}
1824   );
1825   my $arg = "ST(" . ($num - ($num != 0)) . ")";
1826   my $ntype;
1827
1828   my $typemaps = $self->{typemap};
1829
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;
1835   }
1836   else {
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
1840       unless $typemap;
1841     blurt( $self, "Error: No OUTPUT definition for type '$type', typekind '" . $typemap->xstype . "' found"), return
1842       unless $outputmap;
1843     ($ntype = $type) =~ s/\s*\*/Ptr/g;
1844     $ntype =~ s/\(\)//g;
1845     my $subtype;
1846     ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
1847
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
1853         unless $subtypemap;
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";
1863       warn $@ if $@;
1864       print "\t\tSvSETMAGIC(ST(ix_$var));\n" if $do_setmagic;
1865     }
1866     elsif ($var eq 'RETVAL') {
1867       if ($expr =~ /^\t\$arg = new/) {
1868         # We expect that $arg has refcnt 1, so we need to
1869         # mortalize it.
1870         eval "print qq\a$expr\a";
1871         warn $@ if $@;
1872         print "\tsv_2mortal(ST($num));\n";
1873         print "\tSvSETMAGIC(ST($num));\n" if $do_setmagic;
1874       }
1875       elsif ($expr =~ /^\s*\$arg\s*=/) {
1876         # We expect that $arg has refcnt >=1, so we need
1877         # to mortalize it!
1878         eval "print qq\a$expr\a";
1879         warn $@ if $@;
1880         print "\tsv_2mortal(ST(0));\n";
1881         print "\tSvSETMAGIC(ST(0));\n" if $do_setmagic;
1882       }
1883       else {
1884         # Just hope that the entry would safely write it
1885         # over an already mortalized value. By
1886         # coincidence, something like $arg = &sv_undef
1887         # works too.
1888         print "\tST(0) = sv_newmortal();\n";
1889         eval "print qq\a$expr\a";
1890         warn $@ if $@;
1891         # new mortals don't have set magic
1892       }
1893     }
1894     elsif ($do_push) {
1895       print "\tPUSHs(sv_newmortal());\n";
1896       $arg = "ST($num)";
1897       eval "print qq\a$expr\a";
1898       warn $@ if $@;
1899       print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1900     }
1901     elsif ($arg =~ /^ST\(\d+\)$/) {
1902       eval "print qq\a$expr\a";
1903       warn $@ if $@;
1904       print "\tSvSETMAGIC($arg);\n" if $do_setmagic;
1905     }
1906   }
1907 }
1908
1909 1;
1910
1911 # vim: ts=2 sw=2 et: