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