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