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