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