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