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