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