home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / bin / xsubpp.bat < prev   
Encoding:
DOS Batch File  |  2002-12-01  |  50.3 KB  |  1,858 lines

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