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