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