home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / bin / h2ph.bat < prev    next >
Encoding:
DOS Batch File  |  2002-12-01  |  23.7 KB  |  807 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. #!perl
  14. #line 15
  15.     eval 'exec D:\p4\Apps\Gecko\MSI\data\ActivePerl\Perl\bin\perl.exe -S $0 ${1+"$@"}'
  16.     if $running_under_some_shell;
  17.  
  18. use strict;
  19.  
  20. use Config;
  21. use File::Path qw(mkpath);
  22. use Getopt::Std;
  23.  
  24. getopts('Dd:rlhaQ');
  25. use vars qw($opt_D $opt_d $opt_r $opt_l $opt_h $opt_a $opt_Q);
  26. die "-r and -a options are mutually exclusive\n" if ($opt_r and $opt_a);
  27. my @inc_dirs = inc_dirs() if $opt_a;
  28.  
  29. my $Exit = 0;
  30.  
  31. my $Dest_dir = $opt_d || $Config{installsitearch};
  32. die "Destination directory $Dest_dir doesn't exist or isn't a directory\n"
  33.     unless -d $Dest_dir;
  34.  
  35. my @isatype = split(' ',<<END);
  36.     char    uchar    u_char
  37.     short    ushort    u_short
  38.     int    uint    u_int
  39.     long    ulong    u_long
  40.     FILE    key_t    caddr_t
  41. END
  42.  
  43. my %isatype;
  44. @isatype{@isatype} = (1) x @isatype;
  45. my $inif = 0;
  46. my %Is_converted;
  47.  
  48. @ARGV = ('-') unless @ARGV;
  49.  
  50. build_preamble_if_necessary();
  51.  
  52. my ($t, $tab, %curargs, $new, $eval_index, $dir, $name, $args, $outfile);
  53. my ($incl, $next);
  54. while (defined (my $file = next_file())) {
  55.     if (-l $file and -d $file) {
  56.         link_if_possible($file) if ($opt_l);
  57.         next;
  58.     }
  59.  
  60.     # Recover from header files with unbalanced cpp directives
  61.     $t = '';
  62.     $tab = 0;
  63.  
  64.     # $eval_index goes into ``#line'' directives, to help locate syntax errors:
  65.     $eval_index = 1;
  66.  
  67.     if ($file eq '-') {
  68.     open(IN, "-");
  69.     open(OUT, ">-");
  70.     } else {
  71.     ($outfile = $file) =~ s/\.h$/.ph/ || next;
  72.     print "$file -> $outfile\n" unless $opt_Q;
  73.     if ($file =~ m|^(.*)/|) {
  74.         $dir = $1;
  75.         mkpath "$Dest_dir/$dir";
  76.     }
  77.  
  78.     if ($opt_a) { # automagic mode:  locate header file in @inc_dirs
  79.         foreach (@inc_dirs) {
  80.         chdir $_;
  81.         last if -f $file;
  82.         }
  83.     }
  84.  
  85.     open(IN,"$file") || (($Exit = 1),(warn "Can't open $file: $!\n"),next);
  86.     open(OUT,">$Dest_dir/$outfile") || die "Can't create $outfile: $!\n";
  87.     }
  88.  
  89.     print OUT "require '_h2ph_pre.ph';\n\n";
  90.  
  91.     while (defined (local $_ = next_line($file))) {
  92.     if (s/^\s*\#\s*//) {
  93.         if (s/^define\s+(\w+)//) {
  94.         $name = $1;
  95.         $new = '';
  96.         s/\s+$//;
  97.         s/\(\w+\s*\(\*\)\s*\(\w*\)\)\s*(-?\d+)/$1/; # (int (*)(foo_t))0
  98.         if (s/^\(([\w,\s]*)\)//) {
  99.             $args = $1;
  100.                     my $proto = '() ';
  101.             if ($args ne '') {
  102.                         $proto = '';
  103.             foreach my $arg (split(/,\s*/,$args)) {
  104.                 $arg =~ s/^\s*([^\s].*[^\s])\s*$/$1/;
  105.                 $curargs{$arg} = 1;
  106.             }
  107.             $args =~ s/\b(\w)/\$$1/g;
  108.             $args = "local($args) = \@_;\n$t    ";
  109.             }
  110.             s/^\s+//;
  111.             expr();
  112.             $new =~ s/(["\\])/\\$1/g;       #"]);
  113.             $new = reindent($new);
  114.             $args = reindent($args);
  115.             if ($t ne '') {
  116.             $new =~ s/(['\\])/\\$1/g;   #']);
  117.             if ($opt_h) {
  118.                 print OUT $t,
  119.                             "eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name $proto\{\n$t    ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
  120.                             $eval_index++;
  121.             } else {
  122.                 print OUT $t,
  123.                             "eval 'sub $name $proto\{\n$t    ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
  124.             }
  125.             } else {
  126.                       print OUT "unless(defined(\&$name)) {\n    sub $name $proto\{\n\t${args}eval q($new);\n    }\n}\n";
  127.             }
  128.             %curargs = ();
  129.         } else {
  130.             s/^\s+//;
  131.             expr();
  132.             $new = 1 if $new eq '';
  133.             $new = reindent($new);
  134.             $args = reindent($args);
  135.             if ($t ne '') {
  136.             $new =~ s/(['\\])/\\$1/g;        #']);
  137.  
  138.             if ($opt_h) {
  139.                 print OUT $t,"eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name () {",$new,";}' unless defined(\&$name);\n";
  140.                 $eval_index++;
  141.             } else {
  142.                 print OUT $t,"eval 'sub $name () {",$new,";}' unless defined(\&$name);\n";
  143.             }
  144.             } else {
  145.                 # Shunt around such directives as `#define FOO FOO':
  146.                 next if " \&$name" eq $new;
  147.  
  148.                       print OUT $t,"unless(defined(\&$name)) {\n    sub $name () {\t",$new,";}\n}\n";
  149.             }
  150.         }
  151.         } elsif (/^(include|import)\s*[<"](.*)[>"]/) {
  152.         ($incl = $2) =~ s/\.h$/.ph/;
  153.         print OUT $t,"require '$incl';\n";
  154.         } elsif(/^include_next\s*[<"](.*)[>"]/) {
  155.         ($incl = $1) =~ s/\.h$/.ph/;
  156.         print OUT ($t,
  157.                "eval {\n");
  158.                 $tab += 4;
  159.                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  160.         print OUT ($t,
  161.                "my(\%INCD) = map { \$INC{\$_} => 1 } ",
  162.                "(grep { \$_ eq \"$incl\" } keys(\%INC));\n");
  163.         print OUT ($t,
  164.                "my(\@REM) = map { \"\$_/$incl\" } ",
  165.                "(grep { not exists(\$INCD{\"\$_/$incl\"})",
  166.                "and -f \"\$_/$incl\" } \@INC);\n");
  167.         print OUT ($t,
  168.                "require \"\$REM[0]\" if \@REM;\n");
  169.                 $tab -= 4;
  170.                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  171.                 print OUT ($t,
  172.                "};\n");
  173.         print OUT ($t,
  174.                "warn(\$\@) if \$\@;\n");
  175.         } elsif (/^ifdef\s+(\w+)/) {
  176.         print OUT $t,"if(defined(&$1)) {\n";
  177.         $tab += 4;
  178.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  179.         } elsif (/^ifndef\s+(\w+)/) {
  180.         print OUT $t,"unless(defined(&$1)) {\n";
  181.         $tab += 4;
  182.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  183.         } elsif (s/^if\s+//) {
  184.         $new = '';
  185.         $inif = 1;
  186.         expr();
  187.         $inif = 0;
  188.         print OUT $t,"if($new) {\n";
  189.         $tab += 4;
  190.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  191.         } elsif (s/^elif\s+//) {
  192.         $new = '';
  193.         $inif = 1;
  194.         expr();
  195.         $inif = 0;
  196.         $tab -= 4;
  197.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  198.         print OUT $t,"}\n elsif($new) {\n";
  199.         $tab += 4;
  200.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  201.         } elsif (/^else/) {
  202.         $tab -= 4;
  203.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  204.         print OUT $t,"} else {\n";
  205.         $tab += 4;
  206.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  207.         } elsif (/^endif/) {
  208.         $tab -= 4;
  209.         $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
  210.         print OUT $t,"}\n";
  211.         } elsif(/^undef\s+(\w+)/) {
  212.         print OUT $t, "undef(&$1) if defined(&$1);\n";
  213.         } elsif(/^error\s+(".*")/) {
  214.         print OUT $t, "die($1);\n";
  215.         } elsif(/^error\s+(.*)/) {
  216.         print OUT $t, "die(\"", quotemeta($1), "\");\n";
  217.         } elsif(/^warning\s+(.*)/) {
  218.         print OUT $t, "warn(\"", quotemeta($1), "\");\n";
  219.         } elsif(/^ident\s+(.*)/) {
  220.         print OUT $t, "# $1\n";
  221.         }
  222.     } elsif(/^\s*(typedef\s*)?enum\s*(\s+[a-zA-Z_]\w*\s*)?/) {
  223.         until(/\{[^}]*\}.*;/ || /;/) {
  224.         last unless defined ($next = next_line($file));
  225.         chomp $next;
  226.         # drop "#define FOO FOO" in enums
  227.         $next =~ s/^\s*#\s*define\s+(\w+)\s+\1\s*$//;
  228.         $_ .= $next;
  229.         print OUT "# $next\n" if $opt_D;
  230.         }
  231.         s/#\s*if.*?#\s*endif//g; # drop #ifdefs
  232.         s@/\*.*?\*/@@g;
  233.         s/\s+/ /g;
  234.         next unless /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/;
  235.         (my $enum_subs = $3) =~ s/\s//g;
  236.         my @enum_subs = split(/,/, $enum_subs);
  237.         my $enum_val = -1;
  238.         foreach my $enum (@enum_subs) {
  239.         my ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/;
  240.         $enum_value =~ s/^=//;
  241.         $enum_val = (length($enum_value) ? $enum_value : $enum_val + 1);
  242.         if ($opt_h) {
  243.             print OUT ($t,
  244.                    "eval(\"\\n#line $eval_index $outfile\\n",
  245.                    "sub $enum_name () \{ $enum_val; \}\") ",
  246.                    "unless defined(\&$enum_name);\n");
  247.             ++ $eval_index;
  248.         } else {
  249.             print OUT ($t,
  250.                    "eval(\"sub $enum_name () \{ $enum_val; \}\") ",
  251.                    "unless defined(\&$enum_name);\n");
  252.         }
  253.         }
  254.     }
  255.     }
  256.     print OUT "1;\n";
  257.  
  258.     $Is_converted{$file} = 1;
  259.     queue_includes_from($file) if ($opt_a);
  260. }
  261.  
  262. exit $Exit;
  263.  
  264.  
  265. sub reindent($) {
  266.     my($text) = shift;
  267.     $text =~ s/\n/\n    /g;
  268.     $text =~ s/        /\t/g;
  269.     $text;
  270. }
  271.  
  272.  
  273. sub expr {
  274.     my $joined_args;
  275.     if(keys(%curargs)) {
  276.     $joined_args = join('|', keys(%curargs));
  277.     }
  278.     while ($_ ne '') {
  279.     s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator
  280.     s/^\&([\(a-z\)]+)/$1/i;    # hack for things that take the address of
  281.     s/^(\s+)//        && do {$new .= ' '; next;};
  282.     s/^0X([0-9A-F]+)[UL]*//i 
  283.         && do {my $hex = $1;
  284.            $hex =~ s/^0+//;
  285.            if (length $hex > 8 && !$Config{use64bitint}) {
  286.                # Croak if nv_preserves_uv_bits < 64 ?
  287.                $new .=         hex(substr($hex, -8)) +
  288.                    2**32 * hex(substr($hex,  0, -8));
  289.                # The above will produce "errorneus" code
  290.                # if the hex constant was e.g. inside UINT64_C
  291.                # macro, but then again, h2ph is an approximation.
  292.            } else {
  293.                $new .= lc("0x$hex");
  294.            }
  295.            next;};
  296.     s/^(-?\d+\.\d+E[-+]?\d+)[FL]?//i    && do {$new .= $1; next;};
  297.     s/^(\d+)\s*[LU]*//i    && do {$new .= $1; next;};
  298.     s/^("(\\"|[^"])*")//    && do {$new .= $1; next;};
  299.     s/^'((\\"|[^"])*)'//    && do {
  300.         if ($curargs{$1}) {
  301.         $new .= "ord('\$$1')";
  302.         } else {
  303.         $new .= "ord('$1')";
  304.         }
  305.         next;
  306.     };
  307.         # replace "sizeof(foo)" with "{foo}"
  308.         # also, remove * (C dereference operator) to avoid perl syntax
  309.         # problems.  Where the %sizeof array comes from is anyone's
  310.         # guess (c2ph?), but this at least avoids fatal syntax errors.
  311.         # Behavior is undefined if sizeof() delimiters are unbalanced.
  312.         # This code was modified to able to handle constructs like this:
  313.         #   sizeof(*(p)), which appear in the HP-UX 10.01 header files.
  314.         s/^sizeof\s*\(// && do {
  315.             $new .= '$sizeof';
  316.             my $lvl = 1;  # already saw one open paren
  317.             # tack { on the front, and skip it in the loop
  318.             $_ = "{" . "$_";
  319.             my $index = 1;
  320.             # find balanced closing paren
  321.             while ($index <= length($_) && $lvl > 0) {
  322.                 $lvl++ if substr($_, $index, 1) eq "(";
  323.                 $lvl-- if substr($_, $index, 1) eq ")";
  324.                 $index++;
  325.             }
  326.             # tack } on the end, replacing )
  327.             substr($_, $index - 1, 1) = "}";
  328.             # remove pesky * operators within the sizeof argument
  329.             substr($_, 0, $index - 1) =~ s/\*//g;
  330.             next;
  331.         };
  332.     # Eliminate typedefs
  333.     /\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do {
  334.         foreach (split /\s+/, $1) {  # Make sure all the words are types,
  335.         last unless ($isatype{$_} or $_ eq 'struct' or $_ eq 'union');
  336.         }
  337.         s/\([\w\s]+[\*\s]*\)// && next;      # then eliminate them.
  338.     };
  339.     # struct/union member, including arrays:
  340.     s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do {
  341.         my $id = $1;
  342.         $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g;
  343.         $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args);
  344.         while($id =~ /\[\s*([^\$\&\d\]]+)\]/) {
  345.         my($index) = $1;
  346.         $index =~ s/\s//g;
  347.         if(exists($curargs{$index})) {
  348.             $index = "\$$index";
  349.         } else {
  350.             $index = "&$index";
  351.         }
  352.         $id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/;
  353.         }
  354.         $new .= " (\$$id)";
  355.     };
  356.     s/^([_a-zA-Z]\w*)//    && do {
  357.         my $id = $1;
  358.         if ($id eq 'struct' || $id eq 'union') {
  359.         s/^\s+(\w+)//;
  360.         $id .= ' ' . $1;
  361.         $isatype{$id} = 1;
  362.         } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) {
  363.         while (s/^\s+(\w+)//) { $id .= ' ' . $1; }
  364.         $isatype{$id} = 1;
  365.         }
  366.         if ($curargs{$id}) {
  367.         $new .= "\$$id";
  368.         $new .= '->' if /^[\[\{]/;
  369.         } elsif ($id eq 'defined') {
  370.         $new .= 'defined';
  371.         } elsif (/^\s*\(/) {
  372.         s/^\s*\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i;    # cheat
  373.         $new .= " &$id";
  374.         } elsif ($isatype{$id}) {
  375.         if ($new =~ /{\s*$/) {
  376.             $new .= "'$id'";
  377.         } elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) {
  378.             $new =~ s/\(\s*$//;
  379.             s/^[\s*]*\)//;
  380.         } else {
  381.             $new .= q(').$id.q(');
  382.         }
  383.         } else {
  384.         if ($inif && $new !~ /defined\s*\($/) {
  385.             $new .= '(defined(&' . $id . ') ? &' . $id . ' : 0)';
  386.         } elsif (/^\[/) {
  387.             $new .= " \$$id";
  388.         } else {
  389.             $new .= ' &' . $id;
  390.         }
  391.         }
  392.         next;
  393.     };
  394.     s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;};
  395.     }
  396. }
  397.  
  398.  
  399. sub next_line
  400. {
  401.     my $file = shift;
  402.     my ($in, $out);
  403.     my $pre_sub_tri_graphs = 1;
  404.  
  405.     READ: while (not eof IN) {
  406.         $in  .= <IN>;
  407.         chomp $in;
  408.         next unless length $in;
  409.  
  410.         while (length $in) {
  411.             if ($pre_sub_tri_graphs) {
  412.                 # Preprocess all tri-graphs 
  413.                 # including things stuck in quoted string constants.
  414.                 $in =~ s/\?\?=/#/g;                         # | ??=|  #|
  415.                 $in =~ s/\?\?\!/|/g;                        # | ??!|  ||
  416.                 $in =~ s/\?\?'/^/g;                         # | ??'|  ^|
  417.                 $in =~ s/\?\?\(/[/g;                        # | ??(|  [|
  418.                 $in =~ s/\?\?\)/]/g;                        # | ??)|  ]|
  419.                 $in =~ s/\?\?\-/~/g;                        # | ??-|  ~|
  420.                 $in =~ s/\?\?\//\\/g;                       # | ??/|  \|
  421.                 $in =~ s/\?\?</{/g;                         # | ??<|  {|
  422.                 $in =~ s/\?\?>/}/g;                         # | ??>|  }|
  423.             }
  424.         if ($in =~ /^\#ifdef __LANGUAGE_PASCAL__/) {
  425.                 # Tru64 disassembler.h evilness: mixed C and Pascal.
  426.         while (<IN>) {
  427.             last if /^\#endif/; 
  428.         }
  429.         next READ;
  430.         }
  431.         if ($in =~ /^extern inline / && # Inlined assembler.
  432.         $^O eq 'linux' && $file =~ m!(?:^|/)asm/[^/]+\.h$!) {
  433.          while (<IN>) {
  434.             last if /^}/; 
  435.         }
  436.         next READ;
  437.         }
  438.             if ($in =~ s/\\$//) {                           # \-newline
  439.                 $out    .= ' ';
  440.                 next READ;
  441.             } elsif ($in =~ s/^([^"'\\\/]+)//) {            # Passthrough
  442.                 $out    .= $1;
  443.             } elsif ($in =~ s/^(\\.)//) {                   # \...
  444.                 $out    .= $1;
  445.             } elsif ($in =~ s/^('(\\.|[^'\\])*')//) {       # '...
  446.                 $out    .= $1;
  447.             } elsif ($in =~ s/^("(\\.|[^"\\])*")//) {       # "...
  448.                 $out    .= $1;
  449.             } elsif ($in =~ s/^\/\/.*//) {                  # //...
  450.                 # fall through
  451.             } elsif ($in =~ m/^\/\*/) {                     # /*...
  452.                 # C comment removal adapted from perlfaq6:
  453.                 if ($in =~ s/^\/\*[^*]*\*+([^\/*][^*]*\*+)*\///) {
  454.                     $out    .= ' ';
  455.                 } else {                                    # Incomplete /* */
  456.                     next READ;
  457.                 }
  458.             } elsif ($in =~ s/^(\/)//) {                    # /...
  459.                 $out    .= $1;
  460.             } elsif ($in =~ s/^([^\'\"\\\/]+)//) {
  461.                 $out    .= $1;
  462.             } elsif ($^O eq 'linux' &&
  463.                      $file =~ m!(?:^|/)linux/byteorder/pdp_endian\.h$! &&
  464.                      $in   =~ s!\'T KNOW!!) {
  465.                 $out    =~ s!I DON$!I_DO_NOT_KNOW!;
  466.             } else {
  467.         die "Cannot parse:\n$in\n";
  468.             }
  469.         }
  470.  
  471.         last READ if $out =~ /\S/;
  472.     }
  473.  
  474.     return $out;
  475. }
  476.  
  477.  
  478. # Handle recursive subdirectories without getting a grotesquely big stack.
  479. # Could this be implemented using File::Find?
  480. sub next_file
  481. {
  482.     my $file;
  483.  
  484.     while (@ARGV) {
  485.         $file = shift @ARGV;
  486.  
  487.         if ($file eq '-' or -f $file or -l $file) {
  488.             return $file;
  489.         } elsif (-d $file) {
  490.             if ($opt_r) {
  491.                 expand_glob($file);
  492.             } else {
  493.                 print STDERR "Skipping directory `$file'\n";
  494.             }
  495.         } elsif ($opt_a) {
  496.             return $file;
  497.         } else {
  498.             print STDERR "Skipping `$file':  not a file or directory\n";
  499.         }
  500.     }
  501.  
  502.     return undef;
  503. }
  504.  
  505.  
  506. # Put all the files in $directory into @ARGV for processing.
  507. sub expand_glob
  508. {
  509.     my ($directory)  = @_;
  510.  
  511.     $directory =~ s:/$::;
  512.  
  513.     opendir DIR, $directory;
  514.         foreach (readdir DIR) {
  515.             next if ($_ eq '.' or $_ eq '..');
  516.  
  517.             # expand_glob() is going to be called until $ARGV[0] isn't a
  518.             # directory; so push directories, and unshift everything else.
  519.             if (-d "$directory/$_") { push    @ARGV, "$directory/$_" }
  520.             else                    { unshift @ARGV, "$directory/$_" }
  521.         }
  522.     closedir DIR;
  523. }
  524.  
  525.  
  526. # Given $file, a symbolic link to a directory in the C include directory,
  527. # make an equivalent symbolic link in $Dest_dir, if we can figure out how.
  528. # Otherwise, just duplicate the file or directory.
  529. sub link_if_possible
  530. {
  531.     my ($dirlink)  = @_;
  532.     my $target  = eval 'readlink($dirlink)';
  533.  
  534.     if ($target =~ m:^\.\./: or $target =~ m:^/:) {
  535.         # The target of a parent or absolute link could leave the $Dest_dir
  536.         # hierarchy, so let's put all of the contents of $dirlink (actually,
  537.         # the contents of $target) into @ARGV; as a side effect down the
  538.         # line, $dirlink will get created as an _actual_ directory.
  539.         expand_glob($dirlink);
  540.     } else {
  541.         if (-l "$Dest_dir/$dirlink") {
  542.             unlink "$Dest_dir/$dirlink" or
  543.                 print STDERR "Could not remove link $Dest_dir/$dirlink:  $!\n";
  544.         }
  545.  
  546.         if (eval 'symlink($target, "$Dest_dir/$dirlink")') {
  547.             print "Linking $target -> $Dest_dir/$dirlink\n";
  548.  
  549.             # Make sure that the link _links_ to something:
  550.             if (! -e "$Dest_dir/$target") {
  551.                 mkpath("$Dest_dir/$target", 0755) or
  552.                     print STDERR "Could not create $Dest_dir/$target/\n";
  553.             }
  554.         } else {
  555.             print STDERR "Could not symlink $target -> $Dest_dir/$dirlink:  $!\n";
  556.         }
  557.     }
  558. }
  559.  
  560.  
  561. # Push all #included files in $file onto our stack, except for STDIN
  562. # and files we've already processed.
  563. sub queue_includes_from
  564. {
  565.     my ($file)    = @_;
  566.     my $line;
  567.  
  568.     return if ($file eq "-");
  569.  
  570.     open HEADER, $file or return;
  571.         while (defined($line = <HEADER>)) {
  572.             while (/\\$/) { # Handle continuation lines
  573.                 chop $line;
  574.                 $line .= <HEADER>;
  575.             }
  576.  
  577.             if ($line =~ /^#\s*include\s+<(.*?)>/) {
  578.                 push(@ARGV, $1) unless $Is_converted{$1};
  579.             }
  580.         }
  581.     close HEADER;
  582. }
  583.  
  584.  
  585. # Determine include directories; $Config{usrinc} should be enough for (all
  586. # non-GCC?) C compilers, but gcc uses an additional include directory.
  587. sub inc_dirs
  588. {
  589.     my $from_gcc    = `$Config{cc} -v 2>&1`;
  590.     $from_gcc       =~ s:^Reading specs from (.*?)/specs\b.*:$1/include:s;
  591.  
  592.     length($from_gcc) ? ($from_gcc, $Config{usrinc}) : ($Config{usrinc});
  593. }
  594.  
  595.  
  596. # Create "_h2ph_pre.ph", if it doesn't exist or was built by a different
  597. # version of h2ph.
  598. sub build_preamble_if_necessary
  599. {
  600.     # Increment $VERSION every time this function is modified:
  601.     my $VERSION     = 2;
  602.     my $preamble    = "$Dest_dir/_h2ph_pre.ph";
  603.  
  604.     # Can we skip building the preamble file?
  605.     if (-r $preamble) {
  606.         # Extract version number from first line of preamble:
  607.         open  PREAMBLE, $preamble or die "Cannot open $preamble:  $!";
  608.             my $line = <PREAMBLE>;
  609.             $line =~ /(\b\d+\b)/;
  610.         close PREAMBLE            or die "Cannot close $preamble:  $!";
  611.  
  612.         # Don't build preamble if a compatible preamble exists:
  613.         return if $1 == $VERSION;
  614.     }
  615.  
  616.     my (%define) = _extract_cc_defines();
  617.  
  618.     open  PREAMBLE, ">$preamble" or die "Cannot open $preamble:  $!";
  619.         print PREAMBLE "# This file was created by h2ph version $VERSION\n";
  620.  
  621.         foreach (sort keys %define) {
  622.             if ($opt_D) {
  623.                 print PREAMBLE "# $_=$define{$_}\n";
  624.             }
  625.  
  626.             if ($define{$_} =~ /^(\d+)U?L{0,2}$/i) {
  627.                 print PREAMBLE
  628.                     "unless (defined &$_) { sub $_() { $1 } }\n\n";
  629.             } elsif ($define{$_} =~ /^\w+$/) {
  630.                 print PREAMBLE
  631.                     "unless (defined &$_) { sub $_() { &$define{$_} } }\n\n";
  632.             } else {
  633.                 print PREAMBLE
  634.                     "unless (defined &$_) { sub $_() { \"",
  635.                     quotemeta($define{$_}), "\" } }\n\n";
  636.             }
  637.         }
  638.     close PREAMBLE               or die "Cannot close $preamble:  $!";
  639. }
  640.  
  641.  
  642. # %Config contains information on macros that are pre-defined by the
  643. # system's compiler.  We need this information to make the .ph files
  644. # function with perl as the .h files do with cc.
  645. sub _extract_cc_defines
  646. {
  647.     my %define;
  648.     my $allsymbols  = join " ",
  649.         @Config{'ccsymbols', 'cppsymbols', 'cppccsymbols'};
  650.  
  651.     # Split compiler pre-definitions into `key=value' pairs:
  652.     foreach (split /\s+/, $allsymbols) {
  653.         /(.+?)=(.+)/ and $define{$1} = $2;
  654.  
  655.         if ($opt_D) {
  656.             print STDERR "$_:  $1 -> $2\n";
  657.         }
  658.     }
  659.  
  660.     return %define;
  661. }
  662.  
  663.  
  664. 1;
  665.  
  666. ##############################################################################
  667. __END__
  668.  
  669. =head1 NAME
  670.  
  671. h2ph - convert .h C header files to .ph Perl header files
  672.  
  673. =head1 SYNOPSIS
  674.  
  675. B<h2ph [-d destination directory] [-r | -a] [-l] [headerfiles]>
  676.  
  677. =head1 DESCRIPTION
  678.  
  679. I<h2ph>
  680. converts any C header files specified to the corresponding Perl header file
  681. format.
  682. It is most easily run while in /usr/include:
  683.  
  684.     cd /usr/include; h2ph * sys/*
  685.  
  686. or
  687.  
  688.     cd /usr/include; h2ph * sys/* arpa/* netinet/*
  689.  
  690. or
  691.  
  692.     cd /usr/include; h2ph -r -l .
  693.  
  694. The output files are placed in the hierarchy rooted at Perl's
  695. architecture dependent library directory.  You can specify a different
  696. hierarchy with a B<-d> switch.
  697.  
  698. If run with no arguments, filters standard input to standard output.
  699.  
  700. =head1 OPTIONS
  701.  
  702. =over 4
  703.  
  704. =item -d destination_dir
  705.  
  706. Put the resulting B<.ph> files beneath B<destination_dir>, instead of
  707. beneath the default Perl library location (C<$Config{'installsitsearch'}>).
  708.  
  709. =item -r
  710.  
  711. Run recursively; if any of B<headerfiles> are directories, then run I<h2ph>
  712. on all files in those directories (and their subdirectories, etc.).  B<-r>
  713. and B<-a> are mutually exclusive.
  714.  
  715. =item -a
  716.  
  717. Run automagically; convert B<headerfiles>, as well as any B<.h> files
  718. which they include.  This option will search for B<.h> files in all
  719. directories which your C compiler ordinarily uses.  B<-a> and B<-r> are
  720. mutually exclusive.
  721.  
  722. =item -l
  723.  
  724. Symbolic links will be replicated in the destination directory.  If B<-l>
  725. is not specified, then links are skipped over.
  726.  
  727. =item -h
  728.  
  729. Put ``hints'' in the .ph files which will help in locating problems with
  730. I<h2ph>.  In those cases when you B<require> a B<.ph> file containing syntax
  731. errors, instead of the cryptic
  732.  
  733.     [ some error condition ] at (eval mmm) line nnn
  734.  
  735. you will see the slightly more helpful
  736.  
  737.     [ some error condition ] at filename.ph line nnn
  738.  
  739. However, the B<.ph> files almost double in size when built using B<-h>.
  740.  
  741. =item -D
  742.  
  743. Include the code from the B<.h> file as a comment in the B<.ph> file.
  744. This is primarily used for debugging I<h2ph>.
  745.  
  746. =item -Q
  747.  
  748. ``Quiet'' mode; don't print out the names of the files being converted.
  749.  
  750. =back
  751.  
  752. =head1 ENVIRONMENT
  753.  
  754. No environment variables are used.
  755.  
  756. =head1 FILES
  757.  
  758.  /usr/include/*.h
  759.  /usr/include/sys/*.h
  760.  
  761. etc.
  762.  
  763. =head1 AUTHOR
  764.  
  765. Larry Wall
  766.  
  767. =head1 SEE ALSO
  768.  
  769. perl(1)
  770.  
  771. =head1 DIAGNOSTICS
  772.  
  773. The usual warnings if it can't read or write the files involved.
  774.  
  775. =head1 BUGS
  776.  
  777. Doesn't construct the %sizeof array for you.
  778.  
  779. It doesn't handle all C constructs, but it does attempt to isolate
  780. definitions inside evals so that you can get at the definitions
  781. that it can translate.
  782.  
  783. It's only intended as a rough tool.
  784. You may need to dicker with the files produced.
  785.  
  786. You have to run this program by hand; it's not run as part of the Perl
  787. installation.
  788.  
  789. Doesn't handle complicated expressions built piecemeal, a la:
  790.  
  791.     enum {
  792.         FIRST_VALUE,
  793.         SECOND_VALUE,
  794.     #ifdef ABC
  795.         THIRD_VALUE
  796.     #endif
  797.     };
  798.  
  799. Doesn't necessarily locate all of your C compiler's internally-defined
  800. symbols.
  801.  
  802. =cut
  803.  
  804.  
  805. __END__
  806. :endofperl
  807.