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