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