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