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