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