perl 5.003_02: [changes beteween cumulative patches and tarball release]
[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
8fc38fda 9B<xsubpp> [B<-v>] [B<-C++>] [B<-except>] [B<-s pattern>] [B<-prototypes>] [B<-noversioncheck>] [B<-typemap typemap>]... 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
75f92628 58=back
59
60=head1 ENVIRONMENT
61
62No environment variables are used.
63
64=head1 AUTHOR
65
66Larry Wall
67
f06db76b 68=head1 MODIFICATION HISTORY
69
8e07c86e 70See the file F<changes.pod>.
e50aee73 71
75f92628 72=head1 SEE ALSO
73
8fc38fda 74perl(1), perlxs(1), perlxstut(1), perlapi(1)
75f92628 75
76=cut
93a17b20 77
f06db76b 78# Global Constants
93d3b392 79$XSUBPP_version = "1.937";
382b8d97 80require 5.002;
4230ab3f 81use vars '$cplusplus';
382b8d97 82
8fc38fda 83sub Q ;
84
c07a80fd 85$FH = 'File0000' ;
8fc38fda 86
87$usage = "Usage: xsubpp [-v] [-C++] [-except] [-prototypes] [-noversioncheck] [-s pattern] [-typemap typemap]... file.xs\n";
f06db76b 88
382b8d97 89$proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
93a17b20 90
8e07c86e 91$except = "";
8fc38fda 92$WantPrototypes = -1 ;
93$WantVersionChk = 1 ;
94$ProtoUsed = 0 ;
8e07c86e 95SWITCH: while (@ARGV and $ARGV[0] =~ /^-./) {
93a17b20 96 $flag = shift @ARGV;
e50aee73 97 $flag =~ s/^-// ;
8990e307 98 $spat = shift, next SWITCH if $flag eq 's';
99 $cplusplus = 1, next SWITCH if $flag eq 'C++';
382b8d97 100 $WantPrototypes = 0, next SWITCH if $flag eq 'noprototypes';
101 $WantPrototypes = 1, next SWITCH if $flag eq 'prototypes';
8fc38fda 102 $WantVersionChk = 0, next SWITCH if $flag eq 'noversioncheck';
103 $WantVersionChk = 1, next SWITCH if $flag eq 'versioncheck';
8e07c86e 104 $except = " TRY", next SWITCH if $flag eq 'except';
8990e307 105 push(@tm,shift), next SWITCH if $flag eq 'typemap';
8e07c86e 106 (print "xsubpp version $XSUBPP_version\n"), exit
107 if $flag eq 'v';
93a17b20 108 die $usage;
109}
8fc38fda 110if ($WantPrototypes == -1)
111 { $WantPrototypes = 0}
112else
113 { $ProtoUsed = 1 }
114
115
8990e307 116@ARGV == 1 or die $usage;
c2960299 117($dir, $filename) = $ARGV[0] =~ m#(.*)/(.*)#
118 or ($dir, $filename) = $ARGV[0] =~ m#(.*[>\]])(.*)#
8990e307 119 or ($dir, $filename) = ('.', $ARGV[0]);
120chdir($dir);
8fc38fda 121# Check for VMS; Config.pm may not be installed yet, but this routine
122# is built into VMS perl
123if (defined(&VMS::Filespec::vmsify)) { $Is_VMS = 1; $pwd = $ENV{DEFAULT}; }
124else { $Is_VMS = 0; chomp($pwd = `pwd`); }
125
126++ $IncludedFiles{$ARGV[0]} ;
93a17b20 127
4230ab3f 128my(@XSStack) = ({type => 'none'}); # Stack of conditionals and INCLUDEs
129my($XSS_work_idx, $cpp_next_tmp) = (0, "XSubPPtmpAAAA");
130
f06db76b 131sub TrimWhitespace
132{
133 $_[0] =~ s/^\s+|\s+$//go ;
134}
135
136sub TidyType
137{
138 local ($_) = @_ ;
139
140 # rationalise any '*' by joining them into bunches and removing whitespace
141 s#\s*(\*+)\s*#$1#g;
e50aee73 142 s#(\*+)# $1 #g ;
f06db76b 143
144 # change multiple whitespace into a single space
145 s/\s+/ /g ;
146
147 # trim leading & trailing whitespace
148 TrimWhitespace($_) ;
149
150 $_ ;
151}
152
93a17b20 153$typemap = shift @ARGV;
8990e307 154foreach $typemap (@tm) {
155 die "Can't find $typemap in $pwd\n" unless -r $typemap;
93a17b20 156}
748a9306 157unshift @tm, qw(../../../../lib/ExtUtils/typemap ../../../lib/ExtUtils/typemap
158 ../../lib/ExtUtils/typemap ../../../typemap ../../typemap
159 ../typemap typemap);
8990e307 160foreach $typemap (@tm) {
f06db76b 161 next unless -e $typemap ;
162 # skip directories, binary files etc.
163 warn("Warning: ignoring non-text typemap file '$typemap'\n"), next
164 unless -T $typemap ;
165 open(TYPEMAP, $typemap)
166 or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
e50aee73 167 $mode = 'Typemap';
c2960299 168 $junk = "" ;
8990e307 169 $current = \$junk;
170 while (<TYPEMAP>) {
e50aee73 171 next if /^\s*#/;
8e07c86e 172 if (/^INPUT\s*$/) { $mode = 'Input'; $current = \$junk; next; }
173 if (/^OUTPUT\s*$/) { $mode = 'Output'; $current = \$junk; next; }
174 if (/^TYPEMAP\s*$/) { $mode = 'Typemap'; $current = \$junk; next; }
e50aee73 175 if ($mode eq 'Typemap') {
176 chomp;
f06db76b 177 my $line = $_ ;
178 TrimWhitespace($_) ;
179 # skip blank lines and comment lines
180 next if /^$/ or /^#/ ;
382b8d97 181 my($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or
182 warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next;
183 $type = TidyType($type) ;
184 $type_kind{$type} = $kind ;
185 # prototype defaults to '$'
93d3b392 186 $proto = "\$" unless $proto ;
382b8d97 187 warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n")
188 unless ValidProtoString($proto) ;
189 $proto_letter{$type} = C_string($proto) ;
8e07c86e 190 }
191 elsif (/^\s/) {
192 $$current .= $_;
463ee0b2 193 }
e50aee73 194 elsif ($mode eq 'Input') {
8e07c86e 195 s/\s+$//;
196 $input_expr{$_} = '';
197 $current = \$input_expr{$_};
93a17b20 198 }
8990e307 199 else {
8e07c86e 200 s/\s+$//;
201 $output_expr{$_} = '';
202 $current = \$output_expr{$_};
93a17b20 203 }
8990e307 204 }
205 close(TYPEMAP);
206}
93a17b20 207
8990e307 208foreach $key (keys %input_expr) {
209 $input_expr{$key} =~ s/\n+$//;
210}
93a17b20 211
8e07c86e 212$END = "!End!\n\n"; # "impossible" keyword (multiple newline)
213
214# Match an XS keyword
382b8d97 215$BLOCK_re= '\s*(' . join('|', qw(
216 REQUIRE BOOT CASE PREINIT INPUT INIT CODE PPCODE OUTPUT
8fc38fda 217 CLEANUP ALIAS PROTOTYPES PROTOTYPE VERSIONCHECK INCLUDE
382b8d97 218 )) . "|$END)\\s*:";
8e07c86e 219
220# Input: ($_, @line) == unparsed input.
221# Output: ($_, @line) == (rest of line, following lines).
222# Return: the matched keyword if found, otherwise 0
223sub check_keyword {
224 $_ = shift(@line) while !/\S/ && @line;
225 s/^(\s*)($_[0])\s*:\s*(?:#.*)?/$1/s && $2;
226}
227
228
229sub print_section {
230 $_ = shift(@line) while !/\S/ && @line;
231 for (; defined($_) && !/^$BLOCK_re/o; $_ = shift(@line)) {
232 print "$_\n";
233 }
234}
235
8fc38fda 236sub process_keyword($)
237{
238 my($pattern) = @_ ;
239 my $kwd ;
240
241 &{"${kwd}_handler"}()
242 while $kwd = check_keyword($pattern) ;
243}
244
8e07c86e 245sub CASE_handler {
246 blurt ("Error: `CASE:' after unconditional `CASE:'")
247 if $condnum && $cond eq '';
248 $cond = $_;
249 TrimWhitespace($cond);
250 print " ", ($condnum++ ? " else" : ""), ($cond ? " if ($cond)\n" : "\n");
251 $_ = '' ;
252}
253
254sub INPUT_handler {
255 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
256 last if /^\s*NOT_IMPLEMENTED_YET/;
257 next unless /\S/; # skip blank lines
258
259 TrimWhitespace($_) ;
260 my $line = $_ ;
261
262 # remove trailing semicolon if no initialisation
263 s/\s*;$//g unless /=/ ;
264
265 # check for optional initialisation code
266 my $var_init = '' ;
267 $var_init = $1 if s/\s*(=.*)$//s ;
268 $var_init =~ s/"/\\"/g;
269
270 s/\s+/ /g;
271 my ($var_type, $var_addr, $var_name) = /^(.*?[^& ]) *(\&?) *\b(\w+)$/s
272 or blurt("Error: invalid argument declaration '$line'"), next;
273
274 # Check for duplicate definitions
275 blurt ("Error: duplicate definition of argument '$var_name' ignored"), next
276 if $arg_list{$var_name} ++ ;
277
278 $thisdone |= $var_name eq "THIS";
279 $retvaldone |= $var_name eq "RETVAL";
280 $var_types{$var_name} = $var_type;
281 print "\t" . &map_type($var_type);
282 $var_num = $args_match{$var_name};
382b8d97 283
8fc38fda 284 $proto_arg[$var_num] = ProtoString($var_type)
285 if $var_num ;
8e07c86e 286 if ($var_addr) {
287 $var_addr{$var_name} = 1;
288 $func_args =~ s/\b($var_name)\b/&$1/;
289 }
290 if ($var_init =~ /^=\s*NO_INIT\s*;?\s*$/) {
291 print "\t$var_name;\n";
292 } elsif ($var_init =~ /\S/) {
293 &output_init($var_type, $var_num, "$var_name $var_init");
294 } elsif ($var_num) {
295 # generate initialization code
296 &generate_init($var_type, $var_num, $var_name);
297 } else {
298 print ";\n";
299 }
300 }
301}
302
303sub OUTPUT_handler {
304 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
305 next unless /\S/;
306 my ($outarg, $outcode) = /^\s*(\S+)\s*(.*?)\s*$/s ;
307 blurt ("Error: duplicate OUTPUT argument '$outarg' ignored"), next
308 if $outargs{$outarg} ++ ;
309 if (!$gotRETVAL and $outarg eq 'RETVAL') {
310 # deal with RETVAL last
311 $RETVAL_code = $outcode ;
312 $gotRETVAL = 1 ;
313 next ;
314 }
315 blurt ("Error: OUTPUT $outarg not an argument"), next
316 unless defined($args_match{$outarg});
317 blurt("Error: No input definition for OUTPUT argument '$outarg' - ignored"), next
318 unless defined $var_types{$outarg} ;
319 if ($outcode) {
320 print "\t$outcode\n";
321 } else {
322 $var_num = $args_match{$outarg};
323 &generate_output($var_types{$outarg}, $var_num, $outarg);
324 }
325 }
326}
327
8fc38fda 328sub CLEANUP_handler() { print_section() }
329sub PREINIT_handler() { print_section() }
330sub INIT_handler() { print_section() }
331
8e07c86e 332sub GetAliases
333{
334 my ($line) = @_ ;
335 my ($orig) = $line ;
336 my ($alias) ;
337 my ($value) ;
338
339 # Parse alias definitions
340 # format is
341 # alias = value alias = value ...
342
343 while ($line =~ s/^\s*([\w:]+)\s*=\s*(\w+)\s*//) {
344 $alias = $1 ;
345 $orig_alias = $alias ;
346 $value = $2 ;
347
348 # check for optional package definition in the alias
349 $alias = $Packprefix . $alias if $alias !~ /::/ ;
350
351 # check for duplicate alias name & duplicate value
352 Warn("Warning: Ignoring duplicate alias '$orig_alias'")
4230ab3f 353 if defined $XsubAliases{$alias} ;
8e07c86e 354
4230ab3f 355 Warn("Warning: Aliases '$orig_alias' and '$XsubAliasValues{$value}' have identical values")
356 if $XsubAliasValues{$value} ;
8e07c86e 357
4230ab3f 358 $XsubAliases = 1;
359 $XsubAliases{$alias} = $value ;
360 $XsubAliasValues{$value} = $orig_alias ;
8e07c86e 361 }
362
363 blurt("Error: Cannot parse ALIAS definitions from '$orig'")
364 if $line ;
365}
366
382b8d97 367sub ALIAS_handler ()
8e07c86e 368{
369 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
370 next unless /\S/;
371 TrimWhitespace($_) ;
372 GetAliases($_) if $_ ;
373 }
374}
375
382b8d97 376sub REQUIRE_handler ()
8e07c86e 377{
378 # the rest of the current line should contain a version number
379 my ($Ver) = $_ ;
380
381 TrimWhitespace($Ver) ;
382
383 death ("Error: REQUIRE expects a version number")
384 unless $Ver ;
385
386 # check that the version number is of the form n.n
387 death ("Error: REQUIRE: expected a number, got '$Ver'")
388 unless $Ver =~ /^\d+(\.\d*)?/ ;
389
390 death ("Error: xsubpp $Ver (or better) required--this is only $XSUBPP_version.")
391 unless $XSUBPP_version >= $Ver ;
392}
393
8fc38fda 394sub VERSIONCHECK_handler ()
395{
396 # the rest of the current line should contain either ENABLE or
397 # DISABLE
398
399 TrimWhitespace($_) ;
400
401 # check for ENABLE/DISABLE
402 death ("Error: VERSIONCHECK: ENABLE/DISABLE")
403 unless /^(ENABLE|DISABLE)/i ;
404
405 $WantVersionChk = 1 if $1 eq 'ENABLE' ;
406 $WantVersionChk = 0 if $1 eq 'DISABLE' ;
407
408}
409
382b8d97 410sub PROTOTYPE_handler ()
411{
7d41bd0a 412 my $specified ;
413
c07a80fd 414 death("Error: Only 1 PROTOTYPE definition allowed per xsub")
415 if $proto_in_this_xsub ++ ;
416
382b8d97 417 for (; !/^$BLOCK_re/o; $_ = shift(@line)) {
418 next unless /\S/;
7d41bd0a 419 $specified = 1 ;
382b8d97 420 TrimWhitespace($_) ;
421 if ($_ eq 'DISABLE') {
422 $ProtoThisXSUB = 0
423 }
424 elsif ($_ eq 'ENABLE') {
425 $ProtoThisXSUB = 1
426 }
427 else {
428 # remove any whitespace
429 s/\s+//g ;
430 death("Error: Invalid prototype '$_'")
431 unless ValidProtoString($_) ;
432 $ProtoThisXSUB = C_string($_) ;
433 }
434 }
c07a80fd 435
7d41bd0a 436 # If no prototype specified, then assume empty prototype ""
437 $ProtoThisXSUB = 2 unless $specified ;
438
8fc38fda 439 $ProtoUsed = 1 ;
c07a80fd 440
382b8d97 441}
442
443sub PROTOTYPES_handler ()
444{
445 # the rest of the current line should contain either ENABLE or
446 # DISABLE
447
448 TrimWhitespace($_) ;
449
450 # check for ENABLE/DISABLE
451 death ("Error: PROTOTYPES: ENABLE/DISABLE")
452 unless /^(ENABLE|DISABLE)/i ;
453
454 $WantPrototypes = 1 if $1 eq 'ENABLE' ;
455 $WantPrototypes = 0 if $1 eq 'DISABLE' ;
8fc38fda 456 $ProtoUsed = 1 ;
382b8d97 457
458}
459
8fc38fda 460sub INCLUDE_handler ()
461{
462 # the rest of the current line should contain a valid filename
463
464 TrimWhitespace($_) ;
465
8fc38fda 466 death("INCLUDE: filename missing")
467 unless $_ ;
468
469 death("INCLUDE: output pipe is illegal")
470 if /^\s*\|/ ;
471
472 # simple minded recursion detector
473 death("INCLUDE loop detected")
474 if $IncludedFiles{$_} ;
475
476 ++ $IncludedFiles{$_} unless /\|\s*$/ ;
477
478 # Save the current file context.
4230ab3f 479 push(@XSStack, {
480 type => 'file',
8fc38fda 481 LastLine => $lastline,
482 LastLineNo => $lastline_no,
483 Line => \@line,
484 LineNo => \@line_no,
485 Filename => $filename,
c07a80fd 486 Handle => $FH,
8fc38fda 487 }) ;
488
c07a80fd 489 ++ $FH ;
8fc38fda 490
491 # open the new file
c07a80fd 492 open ($FH, "$_") or death("Cannot open '$_': $!") ;
8fc38fda 493
494 print Q<<"EOF" ;
495#
496#/* INCLUDE: Including '$_' from '$filename' */
497#
498EOF
499
8fc38fda 500 $filename = $_ ;
501
c07a80fd 502 # Prime the pump by reading the first
503 # non-blank line
504
505 # skip leading blank lines
506 while (<$FH>) {
507 last unless /^\s*$/ ;
508 }
509
510 $lastline = $_ ;
8fc38fda 511 $lastline_no = $. ;
512
513}
514
515sub PopFile()
516{
4230ab3f 517 return 0 unless $XSStack[-1]{type} eq 'file' ;
518
519 my $data = pop @XSStack ;
8fc38fda 520 my $ThisFile = $filename ;
521 my $isPipe = ($filename =~ /\|\s*$/) ;
522
523 -- $IncludedFiles{$filename}
524 unless $isPipe ;
525
c07a80fd 526 close $FH ;
8fc38fda 527
c07a80fd 528 $FH = $data->{Handle} ;
8fc38fda 529 $filename = $data->{Filename} ;
530 $lastline = $data->{LastLine} ;
531 $lastline_no = $data->{LastLineNo} ;
532 @line = @{ $data->{Line} } ;
533 @line_no = @{ $data->{LineNo} } ;
4230ab3f 534
8fc38fda 535 if ($isPipe and $? ) {
536 -- $lastline_no ;
537 print STDERR "Error reading from pipe '$ThisFile': $! in $filename, line $lastline_no\n" ;
538 exit 1 ;
539 }
540
541 print Q<<"EOF" ;
542#
543#/* INCLUDE: Returning to '$filename' from '$ThisFile' */
544#
545EOF
546
547 return 1 ;
548}
549
382b8d97 550sub ValidProtoString ($)
551{
552 my($string) = @_ ;
553
554 if ( $string =~ /^$proto_re+$/ ) {
555 return $string ;
556 }
557
558 return 0 ;
559}
560
561sub C_string ($)
562{
563 my($string) = @_ ;
564
565 $string =~ s[\\][\\\\]g ;
566 $string ;
567}
568
569sub ProtoString ($)
570{
571 my ($type) = @_ ;
572
93d3b392 573 $proto_letter{$type} or "\$" ;
382b8d97 574}
575
8e07c86e 576sub check_cpp {
577 my @cpp = grep(/^\#\s*(?:if|e\w+)/, @line);
578 if (@cpp) {
579 my ($cpp, $cpplevel);
580 for $cpp (@cpp) {
581 if ($cpp =~ /^\#\s*if/) {
582 $cpplevel++;
583 } elsif (!$cpplevel) {
584 Warn("Warning: #else/elif/endif without #if in this function");
4230ab3f 585 print STDERR " (precede it with a blank line if the matching #if is outside the function)\n"
586 if $XSStack[-1]{type} eq 'if';
8e07c86e 587 return;
588 } elsif ($cpp =~ /^\#\s*endif/) {
589 $cpplevel--;
590 }
591 }
592 Warn("Warning: #if without #endif in this function") if $cpplevel;
593 }
594}
595
596
8990e307 597sub Q {
e50aee73 598 my($text) = @_;
4633a7c4 599 $text =~ s/^#//gm;
2304df62 600 $text =~ s/\[\[/{/g;
601 $text =~ s/\]\]/}/g;
8990e307 602 $text;
93a17b20 603}
604
c07a80fd 605open($FH, $filename) or die "cannot open $filename: $!\n";
c2960299 606
f06db76b 607# Identify the version of xsubpp used
f06db76b 608print <<EOM ;
e50aee73 609/*
610 * This file was generated automatically by xsubpp version $XSUBPP_version from the
93d3b392 611 * contents of $filename. Do not edit this file, edit $filename instead.
e50aee73 612 *
613 * ANY CHANGES MADE HERE WILL BE LOST!
f06db76b 614 *
615 */
e50aee73 616
f06db76b 617EOM
618
619
c07a80fd 620while (<$FH>) {
e50aee73 621 last if ($Module, $Package, $Prefix) =
622 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/;
a0d0e21e 623 print $_;
93a17b20 624}
e50aee73 625&Exit unless defined $_;
626
8fc38fda 627$lastline = $_;
628$lastline_no = $.;
93a17b20 629
e50aee73 630
c07a80fd 631# Read next xsub into @line from ($lastline, <$FH>).
2304df62 632sub fetch_para {
633 # parse paragraph
4230ab3f 634 death ("Error: Unterminated `#if/#ifdef/#ifndef'")
635 if !defined $lastline && $XSStack[-1]{type} eq 'if';
2304df62 636 @line = ();
c2960299 637 @line_no = () ;
4230ab3f 638 return PopFile() if !defined $lastline;
e50aee73 639
640 if ($lastline =~
641 /^MODULE\s*=\s*([\w:]+)(?:\s+PACKAGE\s*=\s*([\w:]+))?(?:\s+PREFIX\s*=\s*(\S+))?\s*$/) {
642 $Module = $1;
8e07c86e 643 $Package = defined($2) ? $2 : ''; # keep -w happy
644 $Prefix = defined($3) ? $3 : ''; # keep -w happy
e50aee73 645 ($Module_cname = $Module) =~ s/\W/_/g;
8e07c86e 646 ($Packid = $Package) =~ tr/:/_/;
e50aee73 647 $Packprefix = $Package;
8e07c86e 648 $Packprefix .= "::" if $Packprefix ne "";
2304df62 649 $lastline = "";
e50aee73 650 }
651
652 for(;;) {
653 if ($lastline !~ /^\s*#/ ||
4230ab3f 654 # CPP directives:
655 # ANSI: if ifdef ifndef elif else endif define undef
656 # line error pragma
657 # gcc: warning include_next
658 # obj-c: import
659 # others: ident (gcc notes that some cpps have this one)
660 $lastline =~ /^#[ \t]*(?:(?:if|ifn?def|elif|else|endif|define|undef|pragma|error|warning|line\s+\d+|ident)\b|(?:include(?:_next)?|import)\s*["<].*[>"])/) {
e50aee73 661 last if $lastline =~ /^\S/ && @line && $line[-1] eq "";
662 push(@line, $lastline);
663 push(@line_no, $lastline_no) ;
93a17b20 664 }
e50aee73 665
666 # Read next line and continuation lines
c07a80fd 667 last unless defined($lastline = <$FH>);
e50aee73 668 $lastline_no = $.;
669 my $tmp_line;
670 $lastline .= $tmp_line
c07a80fd 671 while ($lastline =~ /\\$/ && defined($tmp_line = <$FH>));
e50aee73 672
8e07c86e 673 chomp $lastline;
e50aee73 674 $lastline =~ s/^\s+$//;
2304df62 675 }
e50aee73 676 pop(@line), pop(@line_no) while @line && $line[-1] eq "";
e50aee73 677 1;
2304df62 678}
93a17b20 679
c2960299 680PARAGRAPH:
8e07c86e 681while (fetch_para()) {
e50aee73 682 # Print initial preprocessor statements and blank lines
4230ab3f 683 while (@line && $line[0] !~ /^[^\#]/) {
684 my $line = shift(@line);
685 print $line, "\n";
686 next unless $line =~ /^\#\s*((if)(?:n?def)?|elsif|else|endif)\b/;
687 my $statement = $+;
688 if ($statement eq 'if') {
689 $XSS_work_idx = @XSStack;
690 push(@XSStack, {type => 'if'});
691 } else {
692 death ("Error: `$statement' with no matching `if'")
693 if $XSStack[-1]{type} ne 'if';
694 if ($XSStack[-1]{varname}) {
695 push(@InitFileCode, "#endif\n");
696 push(@BootCode, "#endif");
697 }
698
699 my(@fns) = keys %{$XSStack[-1]{functions}};
700 if ($statement ne 'endif') {
701 # Hide the functions defined in other #if branches, and reset.
702 @{$XSStack[-1]{other_functions}}{@fns} = (1) x @fns;
703 @{$XSStack[-1]}{qw(varname functions)} = ('', {});
704 } else {
705 my($tmp) = pop(@XSStack);
706 0 while (--$XSS_work_idx
707 && $XSStack[$XSS_work_idx]{type} ne 'if');
708 # Keep all new defined functions
709 push(@fns, keys %{$tmp->{other_functions}});
710 @{$XSStack[$XSS_work_idx]{functions}}{@fns} = (1) x @fns;
711 }
712 }
713 }
e50aee73 714
715 next PARAGRAPH unless @line;
716
4230ab3f 717 if ($XSS_work_idx && !$XSStack[$XSS_work_idx]{varname}) {
718 # We are inside an #if, but have not yet #defined its xsubpp variable.
719 print "#define $cpp_next_tmp 1\n\n";
720 push(@InitFileCode, "#if $cpp_next_tmp\n");
721 push(@BootCode, "#if $cpp_next_tmp");
722 $XSStack[$XSS_work_idx]{varname} = $cpp_next_tmp++;
723 }
724
e50aee73 725 death ("Code is not inside a function")
726 if $line[0] =~ /^\s/;
727
2304df62 728 # initialize info arrays
729 undef(%args_match);
730 undef(%var_types);
731 undef(%var_addr);
732 undef(%defaults);
733 undef($class);
734 undef($static);
735 undef($elipsis);
f06db76b 736 undef($wantRETVAL) ;
737 undef(%arg_list) ;
382b8d97 738 undef(@proto_arg) ;
c07a80fd 739 undef($proto_in_this_xsub) ;
382b8d97 740 $ProtoThisXSUB = $WantPrototypes ;
2304df62 741
8e07c86e 742 $_ = shift(@line);
8fc38fda 743 while ($kwd = check_keyword("REQUIRE|PROTOTYPES|VERSIONCHECK|INCLUDE")) {
744 &{"${kwd}_handler"}() ;
8e07c86e 745 next PARAGRAPH unless @line ;
746 $_ = shift(@line);
747 }
c2960299 748
8e07c86e 749 if (check_keyword("BOOT")) {
750 &check_cpp;
751 push (@BootCode, $_, @line, "") ;
c2960299 752 next PARAGRAPH ;
a0d0e21e 753 }
c2960299 754
8e07c86e 755
756 # extract return type, function name and arguments
757 my($ret_type) = TidyType($_);
758
c2960299 759 # a function definition needs at least 2 lines
760 blurt ("Error: Function definition too short '$ret_type'"), next PARAGRAPH
761 unless @line ;
762
8e07c86e 763 $static = 1 if $ret_type =~ s/^static\s+//;
764
2304df62 765 $func_header = shift(@line);
c2960299 766 blurt ("Error: Cannot parse function definition from '$func_header'"), next PARAGRAPH
8e07c86e 767 unless $func_header =~ /^(?:([\w:]*)::)?(\w+)\s*\(\s*(.*?)\s*\)\s*$/s;
c2960299 768
8e07c86e 769 ($class, $func_name, $orig_args) = ($1, $2, $3) ;
2304df62 770 ($pname = $func_name) =~ s/^($Prefix)?/$Packprefix/;
4230ab3f 771 $Full_func_name = "${Packid}_$func_name";
c2960299 772
773 # Check for duplicate function definition
4230ab3f 774 for $tmp (@XSStack) {
775 next unless defined $tmp->{functions}{$Full_func_name};
776 Warn("Warning: duplicate function definition '$func_name' detected");
777 last;
8e07c86e 778 }
4230ab3f 779 $XSStack[$XSS_work_idx]{functions}{$Full_func_name} ++ ;
780 %XsubAliases = %XsubAliasValues = ();
c2960299 781
2304df62 782 @args = split(/\s*,\s*/, $orig_args);
a0d0e21e 783 if (defined($class)) {
8fc38fda 784 my $arg0 = ((defined($static) or $func_name =~ /^new/) ? "CLASS" : "THIS");
8e07c86e 785 unshift(@args, $arg0);
786 ($orig_args = "$arg0, $orig_args") =~ s/^$arg0, $/$arg0/;
2304df62 787 }
788 $orig_args =~ s/"/\\"/g;
789 $min_args = $num_args = @args;
790 foreach $i (0..$num_args-1) {
791 if ($args[$i] =~ s/\.\.\.//) {
792 $elipsis = 1;
793 $min_args--;
c2960299 794 if ($args[$i] eq '' && $i == $num_args - 1) {
2304df62 795 pop(@args);
796 last;
797 }
798 }
8e07c86e 799 if ($args[$i] =~ /^([^=]*[^\s=])\s*=\s*(.*)/s) {
2304df62 800 $min_args--;
801 $args[$i] = $1;
802 $defaults{$args[$i]} = $2;
803 $defaults{$args[$i]} =~ s/"/\\"/g;
804 }
93d3b392 805 $proto_arg[$i+1] = "\$" ;
2304df62 806 }
a0d0e21e 807 if (defined($class)) {
2304df62 808 $func_args = join(", ", @args[1..$#args]);
809 } else {
810 $func_args = join(", ", @args);
811 }
812 @args_match{@args} = 1..@args;
813
8e07c86e 814 $PPCODE = grep(/^\s*PPCODE\s*:/, @line);
93d3b392 815 $CODE = grep(/^\s*CODE\s*:/, @line);
8e07c86e 816 $ALIAS = grep(/^\s*ALIAS\s*:/, @line);
817
2304df62 818 # print function header
a0d0e21e 819 print Q<<"EOF";
820#XS(XS_${Packid}_$func_name)
2304df62 821#[[
a0d0e21e 822# dXSARGS;
93a17b20 823EOF
8e07c86e 824 print Q<<"EOF" if $ALIAS ;
825# dXSI32;
826EOF
2304df62 827 if ($elipsis) {
8e07c86e 828 $cond = ($min_args ? qq(items < $min_args) : 0);
2304df62 829 }
830 elsif ($min_args == $num_args) {
831 $cond = qq(items != $min_args);
832 }
833 else {
834 $cond = qq(items < $min_args || items > $num_args);
835 }
8990e307 836
2304df62 837 print Q<<"EOF" if $except;
838# char errbuf[1024];
839# *errbuf = '\0';
840EOF
841
8e07c86e 842 if ($ALIAS)
843 { print Q<<"EOF" if $cond }
844# if ($cond)
845# croak("Usage: %s($orig_args)", GvNAME(CvGV(cv)));
846EOF
847 else
848 { print Q<<"EOF" if $cond }
849# if ($cond)
8990e307 850# croak("Usage: $pname($orig_args)");
93a17b20 851EOF
852
a0d0e21e 853 print Q<<"EOF" if $PPCODE;
854# SP -= items;
855EOF
856
2304df62 857 # Now do a block of some sort.
93a17b20 858
2304df62 859 $condnum = 0;
8e07c86e 860 $cond = ''; # last CASE: condidional
861 push(@line, "$END:");
862 push(@line_no, $line_no[-1]);
863 $_ = '';
864 &check_cpp;
2304df62 865 while (@line) {
8e07c86e 866 &CASE_handler if check_keyword("CASE");
867 print Q<<"EOF";
868# $except [[
93a17b20 869EOF
870
871 # do initialization of input variables
872 $thisdone = 0;
873 $retvaldone = 0;
463ee0b2 874 $deferred = "";
c2960299 875 %arg_list = () ;
876 $gotRETVAL = 0;
f06db76b 877
8fc38fda 878 INPUT_handler() ;
879 process_keyword("INPUT|PREINIT|ALIAS|PROTOTYPE") ;
880
a0d0e21e 881 if (!$thisdone && defined($class)) {
8fc38fda 882 if (defined($static) or $func_name =~ /^new/) {
a0d0e21e 883 print "\tchar *";
884 $var_types{"CLASS"} = "char *";
885 &generate_init("char *", 1, "CLASS");
886 }
887 else {
93a17b20 888 print "\t$class *";
889 $var_types{"THIS"} = "$class *";
890 &generate_init("$class *", 1, "THIS");
a0d0e21e 891 }
93a17b20 892 }
893
894 # do code
895 if (/^\s*NOT_IMPLEMENTED_YET/) {
4633a7c4 896 print "\n\tcroak(\"$pname: not implemented yet\");\n";
897 $_ = '' ;
93a17b20 898 } else {
899 if ($ret_type ne "void") {
900 print "\t" . &map_type($ret_type) . "\tRETVAL;\n"
901 if !$retvaldone;
902 $args_match{"RETVAL"} = 0;
903 $var_types{"RETVAL"} = $ret_type;
904 }
8e07c86e 905 print $deferred;
8fc38fda 906 process_keyword("INIT|ALIAS|PROTOTYPE") ;
8e07c86e 907
908 if (check_keyword("PPCODE")) {
8fc38fda 909 print_section();
8e07c86e 910 death ("PPCODE must be last thing") if @line;
a0d0e21e 911 print "\tPUTBACK;\n\treturn;\n";
8e07c86e 912 } elsif (check_keyword("CODE")) {
8fc38fda 913 print_section() ;
914 } elsif (defined($class) and $func_name eq "DESTROY") {
a0d0e21e 915 print "\n\t";
8e07c86e 916 print "delete THIS;\n";
93a17b20 917 } else {
918 print "\n\t";
919 if ($ret_type ne "void") {
463ee0b2 920 print "RETVAL = ";
e50aee73 921 $wantRETVAL = 1;
93a17b20 922 }
923 if (defined($static)) {
a0d0e21e 924 if ($func_name =~ /^new/) {
8fc38fda 925 $func_name = "$class";
8e07c86e 926 } else {
927 print "${class}::";
a0d0e21e 928 }
93a17b20 929 } elsif (defined($class)) {
8fc38fda 930 if ($func_name =~ /^new/) {
931 $func_name .= " $class";
932 } else {
93a17b20 933 print "THIS->";
8fc38fda 934 }
93a17b20 935 }
e50aee73 936 $func_name =~ s/^($spat)//
937 if defined($spat);
93a17b20 938 print "$func_name($func_args);\n";
93a17b20 939 }
940 }
941
942 # do output variables
8e07c86e 943 $gotRETVAL = 0;
944 undef $RETVAL_code ;
945 undef %outargs ;
8fc38fda 946 process_keyword("OUTPUT|ALIAS|PROTOTYPE");
f06db76b 947
948 # all OUTPUT done, so now push the return value on the stack
8e07c86e 949 if ($gotRETVAL && $RETVAL_code) {
950 print "\t$RETVAL_code\n";
951 } elsif ($gotRETVAL || $wantRETVAL) {
952 &generate_output($ret_type, 0, 'RETVAL');
953 }
f06db76b 954
93a17b20 955 # do cleanup
8fc38fda 956 process_keyword("CLEANUP|ALIAS|PROTOTYPE") ;
8e07c86e 957
93a17b20 958 # print function trailer
8e07c86e 959 print Q<<EOF;
2304df62 960# ]]
8e07c86e 961EOF
962 print Q<<EOF if $except;
8990e307 963# BEGHANDLERS
964# CATCHALL
965# sprintf(errbuf, "%s: %s\\tpropagated", Xname, Xreason);
966# ENDHANDLERS
93a17b20 967EOF
8e07c86e 968 if (check_keyword("CASE")) {
969 blurt ("Error: No `CASE:' at top of function")
970 unless $condnum;
971 $_ = "CASE: $_"; # Restore CASE: label
972 next;
8990e307 973 }
8e07c86e 974 last if $_ eq "$END:";
975 death(/^$BLOCK_re/o ? "Misplaced `$1:'" : "Junk at end of function");
2304df62 976 }
a0d0e21e 977
2304df62 978 print Q<<EOF if $except;
979# if (errbuf[0])
980# croak(errbuf);
981EOF
a0d0e21e 982
93d3b392 983 if ($ret_type ne "void" or $CODE) {
984 print Q<<EOF unless $PPCODE;
a0d0e21e 985# XSRETURN(1);
986EOF
93d3b392 987 } else {
988 print Q<<EOF unless $PPCODE;
989# XSRETURN_EMPTY;
990EOF
991 }
a0d0e21e 992
2304df62 993 print Q<<EOF;
2304df62 994#]]
8990e307 995#
93a17b20 996EOF
382b8d97 997
4230ab3f 998 my $newXS = "newXS" ;
999 my $proto = "" ;
1000
382b8d97 1001 # Build the prototype string for the xsub
1002 if ($ProtoThisXSUB) {
4230ab3f 1003 $newXS = "newXSproto";
1004
1005 if ($ProtoThisXSUB == 2) {
1006 # User has specified empty prototype
1007 $proto = ', ""' ;
1008 }
7d41bd0a 1009 elsif ($ProtoThisXSUB != 1) {
1010 # User has specified a prototype
4230ab3f 1011 $proto = ', "' . $ProtoThisXSUB . '"';
382b8d97 1012 }
1013 else {
1014 my $s = ';';
1015 if ($min_args < $num_args) {
1016 $s = '';
1017 $proto_arg[$min_args] .= ";" ;
1018 }
4230ab3f 1019 push @proto_arg, "$s\@"
382b8d97 1020 if $elipsis ;
1021
4230ab3f 1022 $proto = ', "' . join ("", @proto_arg) . '"';
382b8d97 1023 }
1024 }
1025
4230ab3f 1026 if (%XsubAliases) {
1027 $XsubAliases{$pname} = 0
1028 unless defined $XsubAliases{$pname} ;
1029 while ( ($name, $value) = each %XsubAliases) {
1030 push(@InitFileCode, Q<<"EOF");
1031# cv = newXS(\"$name\", XS_$Full_func_name, file);
1032# XSANY.any_i32 = $value ;
1033EOF
1034 push(@InitFileCode, Q<<"EOF") if $proto;
1035# sv_setpv((SV*)cv$proto) ;
1036EOF
1037 }
1038 }
1039 else {
1040 push(@InitFileCode,
1041 " ${newXS}(\"$pname\", XS_$Full_func_name, file$proto);\n");
1042 }
93a17b20 1043}
1044
1045# print initialization routine
8990e307 1046print Q<<"EOF";
4633a7c4 1047##ifdef __cplusplus
1048#extern "C"
1049##endif
a0d0e21e 1050#XS(boot_$Module_cname)
2304df62 1051#[[
a0d0e21e 1052# dXSARGS;
8990e307 1053# char* file = __FILE__;
1054#
93a17b20 1055EOF
1056
8fc38fda 1057print Q<<"EOF" if $WantVersionChk ;
1058# XS_VERSION_BOOTCHECK ;
1059#
1060EOF
1061
4230ab3f 1062print Q<<"EOF" if defined $XsubAliases ;
8e07c86e 1063# {
1064# CV * cv ;
1065#
1066EOF
1067
4230ab3f 1068print @InitFileCode;
a0d0e21e 1069
4230ab3f 1070print Q<<"EOF" if defined $XsubAliases ;
8e07c86e 1071# }
1072EOF
1073
a0d0e21e 1074if (@BootCode)
1075{
8e07c86e 1076 print "\n /* Initialisation Section */\n" ;
a0d0e21e 1077 print grep (s/$/\n/, @BootCode) ;
8e07c86e 1078 print "\n /* End of Initialisation Section */\n\n" ;
93a17b20 1079}
a0d0e21e 1080
e50aee73 1081print Q<<"EOF";;
1082# ST(0) = &sv_yes;
1083# XSRETURN(1);
1084#]]
1085EOF
1086
8fc38fda 1087warn("Please specify prototyping behavior for $filename (see perlxs manual)\n")
1088 unless $ProtoUsed ;
e50aee73 1089&Exit;
1090
93a17b20 1091
1092sub output_init {
2304df62 1093 local($type, $num, $init) = @_;
a0d0e21e 1094 local($arg) = "ST(" . ($num - 1) . ")";
93a17b20 1095
2304df62 1096 eval qq/print " $init\\\n"/;
93a17b20 1097}
1098
c2960299 1099sub Warn
1100{
1101 # work out the line number
1102 my $line_no = $line_no[@line_no - @line -1] ;
1103
1104 print STDERR "@_ in $filename, line $line_no\n" ;
1105}
1106
1107sub blurt
1108{
1109 Warn @_ ;
1110 $errors ++
1111}
1112
1113sub death
1114{
1115 Warn @_ ;
1116 exit 1 ;
1117}
8990e307 1118
93a17b20 1119sub generate_init {
2304df62 1120 local($type, $num, $var) = @_;
a0d0e21e 1121 local($arg) = "ST(" . ($num - 1) . ")";
2304df62 1122 local($argoff) = $num - 1;
1123 local($ntype);
1124 local($tk);
93a17b20 1125
f06db76b 1126 $type = TidyType($type) ;
c2960299 1127 blurt("Error: '$type' not in typemap"), return
1128 unless defined($type_kind{$type});
1129
2304df62 1130 ($ntype = $type) =~ s/\s*\*/Ptr/g;
8e07c86e 1131 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
2304df62 1132 $tk = $type_kind{$type};
1133 $tk =~ s/OBJ$/REF/ if $func_name =~ /DESTROY$/;
8e07c86e 1134 $type =~ tr/:/_/;
c2960299 1135 blurt("Error: No INPUT definition for type '$type' found"), return
1136 unless defined $input_expr{$tk} ;
2304df62 1137 $expr = $input_expr{$tk};
1138 if ($expr =~ /DO_ARRAY_ELEM/) {
c2960299 1139 blurt("Error: '$subtype' not in typemap"), return
1140 unless defined($type_kind{$subtype});
1141 blurt("Error: No INPUT definition for type '$subtype' found"), return
1142 unless defined $input_expr{$type_kind{$subtype}} ;
2304df62 1143 $subexpr = $input_expr{$type_kind{$subtype}};
1144 $subexpr =~ s/ntype/subtype/g;
1145 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1146 $subexpr =~ s/\n\t/\n\t\t/g;
93d3b392 1147 $subexpr =~ s/is not of (.*\")/[arg %d] is not of $1, ix_$var + 1/g;
a0d0e21e 1148 $subexpr =~ s/\$var/${var}[ix_$var - $argoff]/;
2304df62 1149 $expr =~ s/DO_ARRAY_ELEM/$subexpr/;
1150 }
1151 if (defined($defaults{$var})) {
1152 $expr =~ s/(\t+)/$1 /g;
1153 $expr =~ s/ /\t/g;
1154 eval qq/print "\\t$var;\\n"/;
1155 $deferred .= eval qq/"\\n\\tif (items < $num)\\n\\t $var = $defaults{$var};\\n\\telse {\\n$expr;\\n\\t}\\n"/;
1156 } elsif ($expr !~ /^\t\$var =/) {
1157 eval qq/print "\\t$var;\\n"/;
1158 $deferred .= eval qq/"\\n$expr;\\n"/;
1159 } else {
1160 eval qq/print "$expr;\\n"/;
1161 }
93a17b20 1162}
1163
1164sub generate_output {
2304df62 1165 local($type, $num, $var) = @_;
a0d0e21e 1166 local($arg) = "ST(" . ($num - ($num != 0)) . ")";
2304df62 1167 local($argoff) = $num - 1;
1168 local($ntype);
93a17b20 1169
f06db76b 1170 $type = TidyType($type) ;
2304df62 1171 if ($type =~ /^array\(([^,]*),(.*)\)/) {
1172 print "\tsv_setpvn($arg, (char *)$var, $2 * sizeof($1)), XFree((char *)$var);\n";
1173 } else {
f06db76b 1174 blurt("Error: '$type' not in typemap"), return
2304df62 1175 unless defined($type_kind{$type});
c2960299 1176 blurt("Error: No OUTPUT definition for type '$type' found"), return
1177 unless defined $output_expr{$type_kind{$type}} ;
2304df62 1178 ($ntype = $type) =~ s/\s*\*/Ptr/g;
1179 $ntype =~ s/\(\)//g;
8e07c86e 1180 ($subtype = $ntype) =~ s/(?:Array)?(?:Ptr)?$//;
2304df62 1181 $expr = $output_expr{$type_kind{$type}};
1182 if ($expr =~ /DO_ARRAY_ELEM/) {
c2960299 1183 blurt("Error: '$subtype' not in typemap"), return
1184 unless defined($type_kind{$subtype});
1185 blurt("Error: No OUTPUT definition for type '$subtype' found"), return
1186 unless defined $output_expr{$type_kind{$subtype}} ;
2304df62 1187 $subexpr = $output_expr{$type_kind{$subtype}};
1188 $subexpr =~ s/ntype/subtype/g;
1189 $subexpr =~ s/\$arg/ST(ix_$var)/g;
1190 $subexpr =~ s/\$var/${var}[ix_$var]/g;
1191 $subexpr =~ s/\n\t/\n\t\t/g;
1192 $expr =~ s/DO_ARRAY_ELEM\n/$subexpr/;
a0d0e21e 1193 eval "print qq\a$expr\a";
2304df62 1194 }
a0d0e21e 1195 elsif ($var eq 'RETVAL') {
93d3b392 1196 if ($expr =~ /^\t\$arg\s*=\s*\$var\s*;/) {
1197 eval "print qq\a$expr\a";
1198 print "\tif (SvREFCNT(ST(0))) sv_2mortal(ST(0));\n";
1199 }
1200 elsif ($expr =~ /^\t\$arg = /) {
a0d0e21e 1201 eval "print qq\a$expr\a";
2304df62 1202 print "\tsv_2mortal(ST(0));\n";
93a17b20 1203 }
2304df62 1204 else {
8990e307 1205 print "\tST(0) = sv_newmortal();\n";
a0d0e21e 1206 eval "print qq\a$expr\a";
463ee0b2 1207 }
2304df62 1208 }
a0d0e21e 1209 elsif ($arg =~ /^ST\(\d+\)$/) {
1210 eval "print qq\a$expr\a";
1211 }
2304df62 1212 }
93a17b20 1213}
1214
1215sub map_type {
e50aee73 1216 my($type) = @_;
93a17b20 1217
8e07c86e 1218 $type =~ tr/:/_/;
1219 $type =~ s/^array\(([^,]*),(.*)\).*/$1 */s;
1220 $type;
93a17b20 1221}
8990e307 1222
e50aee73 1223
1224sub Exit {
748a9306 1225# If this is VMS, the exit status has meaning to the shell, so we
8fc38fda 1226# use a predictable value (SS$_Normal or SS$_Abort) rather than an
1227# arbitrary number.
1228 exit ($Is_VMS ? ($errors ? 44 : 1) : $errors) ;
e50aee73 1229}