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