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