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