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