This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add Ryan Voots to AUTHORS file
[perl5.git] / utils / h2ph.PL
CommitLineData
4633a7c4
LW
1#!/usr/local/bin/perl
2
3use Config;
ee580363 4use File::Basename qw(basename dirname);
8a5546a1 5use Cwd;
4633a7c4
LW
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
1ae6ead9 22open OUT, '>', $file or die "Can't create $file: $!";
4633a7c4
LW
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
LW
33!GROK!THIS!
34
4633a7c4
LW
35# In the following, perl variables are not expanded during extraction.
36
37print OUT <<'!NO!SUBS!';
154e51a4 38
cee96d52
TC
39BEGIN { pop @INC if $INC[-1] eq '.' }
40
fc865b05
JH
41use strict;
42
2c2acf7e 43use Config;
b306bf39 44use File::Path qw(mkpath);
50f6e060
KS
45use Getopt::Std;
46
80d6dabb
SR
47# Make sure read permissions for all are set:
48if (defined umask && (umask() & 0444)) {
49 umask (umask() & ~0444);
50}
51
917244ce
AS
52getopts('Dd:rlhaQe');
53use vars qw($opt_D $opt_d $opt_r $opt_l $opt_h $opt_a $opt_Q $opt_e);
1d3434b8 54die "-r and -a options are mutually exclusive\n" if ($opt_r and $opt_a);
fc865b05 55my @inc_dirs = inc_dirs() if $opt_a;
2c2acf7e 56
b306bf39
RS
57my $Exit = 0;
58
50f6e060 59my $Dest_dir = $opt_d || $Config{installsitearch};
b306bf39
RS
60die "Destination directory $Dest_dir doesn't exist or isn't a directory\n"
61 unless -d $Dest_dir;
154e51a4 62
e77cf69f 63my @isatype = qw(
fe14fcc3
LW
64 char uchar u_char
65 short ushort u_short
66 int uint u_int
67 long ulong u_long
fb73857a 68 FILE key_t caddr_t
e77cf69f
RGS
69 float double size_t
70);
fe14fcc3 71
fc865b05 72my %isatype;
55204971 73@isatype{@isatype} = (1) x @isatype;
fc865b05
JH
74my $inif = 0;
75my %Is_converted;
917244ce 76my %bad_file = ();
fe14fcc3
LW
77
78@ARGV = ('-') unless @ARGV;
154e51a4 79
7f04632d
GS
80build_preamble_if_necessary();
81
917244ce
AS
82sub reindent($) {
83 my($text) = shift;
84 $text =~ s/\n/\n /g;
85 $text =~ s/ /\t/g;
86 $text;
87}
88
fc865b05 89my ($t, $tab, %curargs, $new, $eval_index, $dir, $name, $args, $outfile);
5668511f 90my ($incl, $incl_type, $incl_quote, $next);
fc865b05 91while (defined (my $file = next_file())) {
50f6e060
KS
92 if (-l $file and -d $file) {
93 link_if_possible($file) if ($opt_l);
94 next;
95 }
96
5f05dabc 97 # Recover from header files with unbalanced cpp directives
98 $t = '';
99 $tab = 0;
100
28fb188d 101 # $eval_index goes into '#line' directives, to help locate syntax errors:
50f6e060
KS
102 $eval_index = 1;
103
fe14fcc3
LW
104 if ($file eq '-') {
105 open(IN, "-");
106 open(OUT, ">-");
ee580363 107 } else {
fe14fcc3 108 ($outfile = $file) =~ s/\.h$/.ph/ || next;
625ca0ef 109 print "$file -> $outfile\n" unless $opt_Q;
fe14fcc3
LW
110 if ($file =~ m|^(.*)/|) {
111 $dir = $1;
b306bf39 112 mkpath "$Dest_dir/$dir";
154e51a4 113 }
1d3434b8
GS
114
115 if ($opt_a) { # automagic mode: locate header file in @inc_dirs
116 foreach (@inc_dirs) {
117 chdir $_;
118 last if -f $file;
119 }
120 }
121
1ae6ead9
JL
122 open(IN, "<", "$file") || (($Exit = 1),(warn "Can't open $file: $!\n"),next);
123 open(OUT, ">", "$Dest_dir/$outfile") || die "Can't create $outfile: $!\n";
154e51a4 124 }
7f04632d 125
ccfcdfed
JH
126 print OUT
127 "require '_h2ph_pre.ph';\n\n",
c0cc52e9 128 "no warnings qw(redefine misc);\n\n";
dccff43d
JH
129
130 while (defined (local $_ = next_line($file))) {
1d2dff63 131 if (s/^\s*\#\s*//) {
154e51a4
LW
132 if (s/^define\s+(\w+)//) {
133 $name = $1;
134 $new = '';
135 s/\s+$//;
1be505aa 136 s/\(\w+\s*\(\*\)\s*\(\w*\)\)\s*(-?\d+)/$1/; # (int (*)(foo_t))0
154e51a4
LW
137 if (s/^\(([\w,\s]*)\)//) {
138 $args = $1;
09f42789 139 my $proto = '() ';
154e51a4 140 if ($args ne '') {
09f42789 141 $proto = '';
fc865b05 142 foreach my $arg (split(/,\s*/,$args)) {
55204971 143 $arg =~ s/^\s*([^\s].*[^\s])\s*$/$1/;
154e51a4
LW
144 $curargs{$arg} = 1;
145 }
146 $args =~ s/\b(\w)/\$$1/g;
d02b64de 147 $args = "my($args) = \@_;\n$t ";
154e51a4
LW
148 }
149 s/^\s+//;
5f05dabc 150 expr();
ee580363 151 $new =~ s/(["\\])/\\$1/g; #"]);
f178b03b 152 EMIT($proto);
ee580363 153 } else {
154e51a4 154 s/^\s+//;
5f05dabc 155 expr();
5a677310 156
154e51a4 157 $new = 1 if $new eq '';
5a677310 158
28fb188d 159 # Shunt around such directives as '#define FOO FOO':
5a677310
LM
160 next if $new =~ /^\s*&\Q$name\E\s*\z/;
161
ee580363
GS
162 $new = reindent($new);
163 $args = reindent($args);
5a677310 164 $new =~ s/(['\\])/\\$1/g; #']);
7f04632d 165
5a677310
LM
166 print OUT $t, 'eval ';
167 if ($opt_h) {
168 print OUT "\"\\n#line $eval_index $outfile\\n\" . ";
169 $eval_index++;
154e51a4 170 }
5a677310 171 print OUT "'sub $name () {$new;}' unless defined(&$name);\n";
154e51a4 172 }
5668511f 173 } elsif (/^(include|import|include_next)\s*([<\"])(.*)[>\"]/) {
917244ce 174 $incl_type = $1;
5668511f
NT
175 $incl_quote = $2;
176 $incl = $3;
917244ce
AS
177 if (($incl_type eq 'include_next') ||
178 ($opt_e && exists($bad_file{$incl}))) {
179 $incl =~ s/\.h$/.ph/;
ee580363 180 print OUT ($t,
1d2dff63
GS
181 "eval {\n");
182 $tab += 4;
183 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
917244ce
AS
184 print OUT ($t, "my(\@REM);\n");
185 if ($incl_type eq 'include_next') {
1d2dff63
GS
186 print OUT ($t,
187 "my(\%INCD) = map { \$INC{\$_} => 1 } ",
917244ce
AS
188 "(grep { \$_ eq \"$incl\" } ",
189 "keys(\%INC));\n");
1d2dff63 190 print OUT ($t,
917244ce 191 "\@REM = map { \"\$_/$incl\" } ",
1d2dff63 192 "(grep { not exists(\$INCD{\"\$_/$incl\"})",
917244ce
AS
193 " and -f \"\$_/$incl\" } \@INC);\n");
194 } else {
195 print OUT ($t,
196 "\@REM = map { \"\$_/$incl\" } ",
197 "(grep {-r \"\$_/$incl\" } \@INC);\n");
198 }
1d2dff63
GS
199 print OUT ($t,
200 "require \"\$REM[0]\" if \@REM;\n");
201 $tab -= 4;
202 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
203 print OUT ($t,
204 "};\n");
205 print OUT ($t,
206 "warn(\$\@) if \$\@;\n");
917244ce
AS
207 } else {
208 $incl =~ s/\.h$/.ph/;
5668511f
NT
209 # copy the prefix in the quote syntax (#include "x.h") case
210 if ($incl !~ m|/| && $incl_quote eq q{"} && $file =~ m|^(.*)/|) {
211 $incl = "$1/$incl";
212 }
917244ce
AS
213 print OUT $t,"require '$incl';\n";
214 }
ee580363
GS
215 } elsif (/^ifdef\s+(\w+)/) {
216 print OUT $t,"if(defined(&$1)) {\n";
154e51a4
LW
217 $tab += 4;
218 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
ee580363
GS
219 } elsif (/^ifndef\s+(\w+)/) {
220 print OUT $t,"unless(defined(&$1)) {\n";
221 $tab += 4;
222 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
223 } elsif (s/^if\s+//) {
154e51a4 224 $new = '';
748a9306 225 $inif = 1;
5f05dabc 226 expr();
748a9306 227 $inif = 0;
ee580363 228 print OUT $t,"if($new) {\n";
154e51a4
LW
229 $tab += 4;
230 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
ee580363 231 } elsif (s/^elif\s+//) {
154e51a4 232 $new = '';
748a9306 233 $inif = 1;
5f05dabc 234 expr();
748a9306 235 $inif = 0;
154e51a4
LW
236 $tab -= 4;
237 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
ee580363 238 print OUT $t,"}\n elsif($new) {\n";
154e51a4
LW
239 $tab += 4;
240 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
ee580363 241 } elsif (/^else/) {
154e51a4
LW
242 $tab -= 4;
243 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
ee580363 244 print OUT $t,"} else {\n";
154e51a4
LW
245 $tab += 4;
246 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
ee580363 247 } elsif (/^endif/) {
154e51a4
LW
248 $tab -= 4;
249 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
250 print OUT $t,"}\n";
ee580363
GS
251 } elsif(/^undef\s+(\w+)/) {
252 print OUT $t, "undef(&$1) if defined(&$1);\n";
d3e00f1c
KS
253 } elsif(/^error\s+(".*")/) {
254 print OUT $t, "die($1);\n";
ee580363 255 } elsif(/^error\s+(.*)/) {
5d42aa7b 256 print OUT $t, "die(\"", quotemeta($1), "\");\n";
ee580363 257 } elsif(/^warning\s+(.*)/) {
5d42aa7b 258 print OUT $t, "warn(\"", quotemeta($1), "\");\n";
ee580363
GS
259 } elsif(/^ident\s+(.*)/) {
260 print OUT $t, "# $1\n";
154e51a4 261 }
09f42789 262 } elsif (/^\s*(typedef\s*)?enum\s*(\s+[a-zA-Z_]\w*\s*)?/) { # { for vi
e7cba2ba 263 until(/\{[^}]*\}.*;/ || /;/) {
dccff43d 264 last unless defined ($next = next_line($file));
e7cba2ba
JH
265 chomp $next;
266 # drop "#define FOO FOO" in enums
267 $next =~ s/^\s*#\s*define\s+(\w+)\s+\1\s*$//;
9e3b9e5a
OT
268 # #defines in enums (aliases)
269 $next =~ s/^\s*#\s*define\s+(\w+)\s+(\w+)\s*$/$1 = $2,/;
1d2dff63
GS
270 $_ .= $next;
271 print OUT "# $next\n" if $opt_D;
272 }
e7cba2ba 273 s/#\s*if.*?#\s*endif//g; # drop #ifdefs
1d2dff63
GS
274 s@/\*.*?\*/@@g;
275 s/\s+/ /g;
e7cba2ba 276 next unless /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/;
fc865b05
JH
277 (my $enum_subs = $3) =~ s/\s//g;
278 my @enum_subs = split(/,/, $enum_subs);
279 my $enum_val = -1;
280 foreach my $enum (@enum_subs) {
281 my ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/;
9e3b9e5a 282 $enum_name or next;
1d2dff63
GS
283 $enum_value =~ s/^=//;
284 $enum_val = (length($enum_value) ? $enum_value : $enum_val + 1);
285 if ($opt_h) {
286 print OUT ($t,
287 "eval(\"\\n#line $eval_index $outfile\\n",
288 "sub $enum_name () \{ $enum_val; \}\") ",
289 "unless defined(\&$enum_name);\n");
290 ++ $eval_index;
291 } else {
292 print OUT ($t,
293 "eval(\"sub $enum_name () \{ $enum_val; \}\") ",
294 "unless defined(\&$enum_name);\n");
295 }
296 }
5fff27bd
RGS
297 } elsif (/^(?:__extension__\s+)?(?:extern|static)\s+(?:__)?inline(?:__)?\s+/
298 and !/;\s*$/ and !/{\s*}\s*$/)
299 { # { for vi
09f42789 300 # This is a hack to parse the inline functions in the glibc headers.
5fff27bd
RGS
301 # Warning: massive kludge ahead. We suppose inline functions
302 # are mainly constructed like macros.
09f42789
RGS
303 while (1) {
304 last unless defined ($next = next_line($file));
305 chomp $next;
5fff27bd
RGS
306 undef $_, last if $next =~ /__THROW\s*;/
307 or $next =~ /^(__extension__|extern|static)\b/;
09f42789
RGS
308 $_ .= " $next";
309 print OUT "# $next\n" if $opt_D;
310 last if $next =~ /^}|^{.*}\s*$/;
311 }
312 next if not defined; # because it's only a prototype
0e885527
RGS
313 s/\b(__extension__|extern|static|(?:__)?inline(?:__)?)\b//g;
314 # violently drop #ifdefs
315 s/#\s*if.*?#\s*endif//g
316 and print OUT "# some #ifdef were dropped here -- fill in the blanks\n";
09f42789
RGS
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
d02b64de 333 ? "my(" . (join ',', map "\$$_", @args) . ") = \@_;\n$t "
09f42789
RGS
334 : ""
335 );
336 my $proto = @args ? '' : '() ';
337 $new = '';
338 s/\breturn\b//g; # "return" doesn't occur in macros usually...
339 expr();
0e885527
RGS
340 # try to find and perlify local C variables
341 our @local_variables = (); # needs to be a our(): (?{...}) bug workaround
e77cf69f
RGS
342 {
343 use re "eval";
344 my $typelist = join '|', keys %isatype;
345 $new =~ s['
90851df9 346 (?:(?:__)?const(?:__)?\s+)?
e77cf69f
RGS
347 (?:(?:un)?signed\s+)?
348 (?:long\s+)?
349 (?:$typelist)\s+
350 (\w+)
351 (?{ push @local_variables, $1 })
352 ']
353 [my \$$1]gx;
354 $new =~ s['
90851df9 355 (?:(?:__)?const(?:__)?\s+)?
e77cf69f
RGS
356 (?:(?:un)?signed\s+)?
357 (?:long\s+)?
358 (?:$typelist)\s+
359 ' \s+ &(\w+) \s* ;
360 (?{ push @local_variables, $1 })
361 ]
362 [my \$$1;]gx;
363 }
0e885527 364 $new =~ s/&$_\b/\$$_/g for @local_variables;
09f42789 365 $new =~ s/(["\\])/\\$1/g; #"]);
0e885527 366 # now that's almost like a macro (we hope)
f178b03b 367 EMIT($proto);
154e51a4
LW
368 }
369 }
fc865b05 370 $Is_converted{$file} = 1;
917244ce
AS
371 if ($opt_e && exists($bad_file{$file})) {
372 unlink($Dest_dir . '/' . $outfile);
373 $next = '';
374 } else {
375 print OUT "1;\n";
09f42789 376 queue_includes_from($file) if $opt_a;
917244ce 377 }
154e51a4
LW
378}
379
917244ce
AS
380if ($opt_e && (scalar(keys %bad_file) > 0)) {
381 warn "Was unable to convert the following files:\n";
382 warn "\t" . join("\n\t",sort(keys %bad_file)) . "\n";
ee580363
GS
383}
384
917244ce 385exit $Exit;
fc865b05 386
f178b03b
TR
387sub EMIT {
388 my $proto = shift;
389
390 $new = reindent($new);
391 $args = reindent($args);
392 if ($t ne '') {
393 $new =~ s/(['\\])/\\$1/g; #']);
394 if ($opt_h) {
395 print OUT $t,
396 "eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
397 $eval_index++;
398 } else {
399 print OUT $t,
400 "eval 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
401 }
402 } else {
403 print OUT "unless(defined(\&$name)) {\n sub $name $proto\{\n\t${args}eval q($new);\n }\n}\n";
404 }
405 %curargs = ();
406 return;
407}
408
154e51a4 409sub expr {
8d66b3f9
RB
410 if (/\b__asm__\b/) { # freak out
411 $new = '"(assembly code)"';
412 return
413 }
fc865b05 414 my $joined_args;
ee580363 415 if(keys(%curargs)) {
fc865b05 416 $joined_args = join('|', keys(%curargs));
ee580363 417 }
154e51a4 418 while ($_ ne '') {
ee580363
GS
419 s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator
420 s/^\&([\(a-z\)]+)/$1/i; # hack for things that take the address of
154e51a4 421 s/^(\s+)// && do {$new .= ' '; next;};
bf076876 422 s/^0X([0-9A-F]+)[UL]*//i
25146a1a
JH
423 && do {my $hex = $1;
424 $hex =~ s/^0+//;
425 if (length $hex > 8 && !$Config{use64bitint}) {
426 # Croak if nv_preserves_uv_bits < 64 ?
427 $new .= hex(substr($hex, -8)) +
428 2**32 * hex(substr($hex, 0, -8));
5538372e 429 # The above will produce "erroneous" code
25146a1a
JH
430 # if the hex constant was e.g. inside UINT64_C
431 # macro, but then again, h2ph is an approximation.
432 } else {
433 $new .= lc("0x$hex");
434 }
435 next;};
fd3f0aff 436 s/^(-?\d+\.\d+E[-+]?\d+)[FL]?//i && do {$new .= $1; next;};
50f6e060 437 s/^(\d+)\s*[LU]*//i && do {$new .= $1; next;};
154e51a4
LW
438 s/^("(\\"|[^"])*")// && do {$new .= $1; next;};
439 s/^'((\\"|[^"])*)'// && do {
440 if ($curargs{$1}) {
441 $new .= "ord('\$$1')";
ee580363 442 } else {
154e51a4
LW
443 $new .= "ord('$1')";
444 }
445 next;
446 };
5f05dabc 447 # replace "sizeof(foo)" with "{foo}"
448 # also, remove * (C dereference operator) to avoid perl syntax
449 # problems. Where the %sizeof array comes from is anyone's
450 # guess (c2ph?), but this at least avoids fatal syntax errors.
451 # Behavior is undefined if sizeof() delimiters are unbalanced.
452 # This code was modified to able to handle constructs like this:
453 # sizeof(*(p)), which appear in the HP-UX 10.01 header files.
454 s/^sizeof\s*\(// && do {
455 $new .= '$sizeof';
456 my $lvl = 1; # already saw one open paren
457 # tack { on the front, and skip it in the loop
458 $_ = "{" . "$_";
459 my $index = 1;
460 # find balanced closing paren
461 while ($index <= length($_) && $lvl > 0) {
462 $lvl++ if substr($_, $index, 1) eq "(";
463 $lvl-- if substr($_, $index, 1) eq ")";
464 $index++;
465 }
466 # tack } on the end, replacing )
467 substr($_, $index - 1, 1) = "}";
468 # remove pesky * operators within the sizeof argument
469 substr($_, 0, $index - 1) =~ s/\*//g;
470 next;
471 };
50f6e060
KS
472 # Eliminate typedefs
473 /\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do {
55c8af0d 474 my $doit = 1;
50f6e060 475 foreach (split /\s+/, $1) { # Make sure all the words are types,
55c8af0d
WL
476 unless($isatype{$_} or $_ eq 'struct' or $_ eq 'union'){
477 $doit = 0;
478 last;
479 }
480 }
481 if( $doit ){
482 s/\([\w\s]+[\*\s]*\)// && next; # then eliminate them.
50f6e060 483 }
50f6e060 484 };
ee580363
GS
485 # struct/union member, including arrays:
486 s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do {
fc865b05 487 my $id = $1;
ee580363
GS
488 $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g;
489 $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args);
490 while($id =~ /\[\s*([^\$\&\d\]]+)\]/) {
491 my($index) = $1;
492 $index =~ s/\s//g;
493 if(exists($curargs{$index})) {
494 $index = "\$$index";
495 } else {
496 $index = "&$index";
497 }
498 $id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/;
499 }
500 $new .= " (\$$id)";
50f6e060 501 };
154e51a4 502 s/^([_a-zA-Z]\w*)// && do {
fc865b05 503 my $id = $1;
99ed927b 504 if ($id eq 'struct' || $id eq 'union') {
fe14fcc3
LW
505 s/^\s+(\w+)//;
506 $id .= ' ' . $1;
507 $isatype{$id} = 1;
ee580363 508 } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) {
50f6e060 509 while (s/^\s+(\w+)//) { $id .= ' ' . $1; }
fe14fcc3
LW
510 $isatype{$id} = 1;
511 }
154e51a4 512 if ($curargs{$id}) {
ee580363
GS
513 $new .= "\$$id";
514 $new .= '->' if /^[\[\{]/;
515 } elsif ($id eq 'defined') {
154e51a4 516 $new .= 'defined';
cd4e1efa
MS
517 } elsif (/^\s*\(/) {
518 s/^\s*\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i; # cheat
154e51a4 519 $new .= " &$id";
ee580363 520 } elsif ($isatype{$id}) {
9a108c6c 521 if ($new =~ /\{\s*$/) {
fe14fcc3 522 $new .= "'$id'";
ee580363 523 } elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) {
fe14fcc3
LW
524 $new =~ s/\(\s*$//;
525 s/^[\s*]*\)//;
ee580363 526 } else {
b276c83d 527 $new .= q(').$id.q(');
fe14fcc3 528 }
ee580363 529 } else {
3983eafb
SK
530 if ($inif) {
531 if ($new =~ /defined\s*$/) {
532 $new .= '(&' . $id . ')';
533 } elsif ($new =~ /defined\s*\($/) {
534 $new .= '&' . $id;
535 } else {
536 $new .= '(defined(&' . $id . ') ? &' . $id . ' : undef)';
537 }
ee580363
GS
538 } elsif (/^\[/) {
539 $new .= " \$$id";
540 } else {
748a9306
LW
541 $new .= ' &' . $id;
542 }
154e51a4
LW
543 }
544 next;
545 };
fb21d8eb 546 s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;};
154e51a4
LW
547 }
548}
50f6e060
KS
549
550
79c1b905
KS
551sub next_line
552{
dccff43d 553 my $file = shift;
79c1b905 554 my ($in, $out);
b7bcf494 555 my $pre_sub_tri_graphs = 1;
79c1b905
KS
556
557 READ: while (not eof IN) {
558 $in .= <IN>;
559 chomp $in;
560 next unless length $in;
561
562 while (length $in) {
b7bcf494 563 if ($pre_sub_tri_graphs) {
bf076876 564 # Preprocess all tri-graphs
b7bcf494
PP
565 # including things stuck in quoted string constants.
566 $in =~ s/\?\?=/#/g; # | ??=| #|
567 $in =~ s/\?\?\!/|/g; # | ??!| ||
568 $in =~ s/\?\?'/^/g; # | ??'| ^|
569 $in =~ s/\?\?\(/[/g; # | ??(| [|
570 $in =~ s/\?\?\)/]/g; # | ??)| ]|
571 $in =~ s/\?\?\-/~/g; # | ??-| ~|
572 $in =~ s/\?\?\//\\/g; # | ??/| \|
573 $in =~ s/\?\?</{/g; # | ??<| {|
574 $in =~ s/\?\?>/}/g; # | ??>| }|
575 }
9efe82d3 576 if ($in =~ /^\#ifdef __LANGUAGE_PASCAL__/) {
bf076876 577 # Tru64 disassembler.h evilness: mixed C and Pascal.
9efe82d3 578 while (<IN>) {
bf076876 579 last if /^\#endif/;
9efe82d3 580 }
bf076876 581 $in = "";
9efe82d3
JH
582 next READ;
583 }
37723803 584 if ($in =~ /^extern inline / && # Inlined assembler.
dccff43d 585 $^O eq 'linux' && $file =~ m!(?:^|/)asm/[^/]+\.h$!) {
bf076876
AT
586 while (<IN>) {
587 last if /^}/;
dccff43d 588 }
bf076876 589 $in = "";
dccff43d
JH
590 next READ;
591 }
79c1b905
KS
592 if ($in =~ s/\\$//) { # \-newline
593 $out .= ' ';
594 next READ;
595 } elsif ($in =~ s/^([^"'\\\/]+)//) { # Passthrough
596 $out .= $1;
597 } elsif ($in =~ s/^(\\.)//) { # \...
598 $out .= $1;
ab5fe4d6
KS
599 } elsif ($in =~ /^'/) { # '...
600 if ($in =~ s/^('(\\.|[^'\\])*')//) {
601 $out .= $1;
602 } else {
603 next READ;
604 }
605 } elsif ($in =~ /^"/) { # "...
606 if ($in =~ s/^("(\\.|[^"\\])*")//) {
607 $out .= $1;
608 } else {
609 next READ;
610 }
79c1b905 611 } elsif ($in =~ s/^\/\/.*//) { # //...
edf6e4ec 612 # fall through
79c1b905
KS
613 } elsif ($in =~ m/^\/\*/) { # /*...
614 # C comment removal adapted from perlfaq6:
615 if ($in =~ s/^\/\*[^*]*\*+([^\/*][^*]*\*+)*\///) {
616 $out .= ' ';
617 } else { # Incomplete /* */
618 next READ;
619 }
620 } elsif ($in =~ s/^(\/)//) { # /...
621 $out .= $1;
622 } elsif ($in =~ s/^([^\'\"\\\/]+)//) {
623 $out .= $1;
889e303a
JH
624 } elsif ($^O eq 'linux' &&
625 $file =~ m!(?:^|/)linux/byteorder/pdp_endian\.h$! &&
626 $in =~ s!\'T KNOW!!) {
627 $out =~ s!I DON$!I_DO_NOT_KNOW!;
79c1b905 628 } else {
917244ce
AS
629 if ($opt_e) {
630 warn "Cannot parse $file:\n$in\n";
631 $bad_file{$file} = 1;
632 $in = '';
633 $out = undef;
634 last READ;
635 } else {
dccff43d 636 die "Cannot parse:\n$in\n";
917244ce 637 }
79c1b905
KS
638 }
639 }
640
edf6e4ec 641 last READ if $out =~ /\S/;
79c1b905
KS
642 }
643
644 return $out;
645}
646
647
50f6e060
KS
648# Handle recursive subdirectories without getting a grotesquely big stack.
649# Could this be implemented using File::Find?
650sub next_file
651{
652 my $file;
653
654 while (@ARGV) {
655 $file = shift @ARGV;
656
657 if ($file eq '-' or -f $file or -l $file) {
658 return $file;
659 } elsif (-d $file) {
660 if ($opt_r) {
661 expand_glob($file);
662 } else {
28fb188d 663 print STDERR "Skipping directory '$file'\n";
50f6e060 664 }
1d3434b8
GS
665 } elsif ($opt_a) {
666 return $file;
667 } else {
28fb188d 668 print STDERR "Skipping '$file': not a file or directory\n";
50f6e060
KS
669 }
670 }
671
672 return undef;
673}
674
675
676# Put all the files in $directory into @ARGV for processing.
677sub expand_glob
678{
679 my ($directory) = @_;
680
681 $directory =~ s:/$::;
682
683 opendir DIR, $directory;
684 foreach (readdir DIR) {
685 next if ($_ eq '.' or $_ eq '..');
686
687 # expand_glob() is going to be called until $ARGV[0] isn't a
688 # directory; so push directories, and unshift everything else.
1d3434b8
GS
689 if (-d "$directory/$_") { push @ARGV, "$directory/$_" }
690 else { unshift @ARGV, "$directory/$_" }
50f6e060
KS
691 }
692 closedir DIR;
693}
694
695
696# Given $file, a symbolic link to a directory in the C include directory,
697# make an equivalent symbolic link in $Dest_dir, if we can figure out how.
698# Otherwise, just duplicate the file or directory.
699sub link_if_possible
700{
701 my ($dirlink) = @_;
702 my $target = eval 'readlink($dirlink)';
703
704 if ($target =~ m:^\.\./: or $target =~ m:^/:) {
705 # The target of a parent or absolute link could leave the $Dest_dir
706 # hierarchy, so let's put all of the contents of $dirlink (actually,
707 # the contents of $target) into @ARGV; as a side effect down the
708 # line, $dirlink will get created as an _actual_ directory.
709 expand_glob($dirlink);
710 } else {
711 if (-l "$Dest_dir/$dirlink") {
712 unlink "$Dest_dir/$dirlink" or
713 print STDERR "Could not remove link $Dest_dir/$dirlink: $!\n";
714 }
1d3434b8 715
50f6e060
KS
716 if (eval 'symlink($target, "$Dest_dir/$dirlink")') {
717 print "Linking $target -> $Dest_dir/$dirlink\n";
718
719 # Make sure that the link _links_ to something:
720 if (! -e "$Dest_dir/$target") {
1d3434b8 721 mkpath("$Dest_dir/$target", 0755) or
50f6e060
KS
722 print STDERR "Could not create $Dest_dir/$target/\n";
723 }
724 } else {
725 print STDERR "Could not symlink $target -> $Dest_dir/$dirlink: $!\n";
726 }
727 }
728}
729
730
1d3434b8
GS
731# Push all #included files in $file onto our stack, except for STDIN
732# and files we've already processed.
733sub queue_includes_from
734{
735 my ($file) = @_;
736 my $line;
737
738 return if ($file eq "-");
739
1ae6ead9 740 open HEADER, "<", $file or return;
1d3434b8
GS
741 while (defined($line = <HEADER>)) {
742 while (/\\$/) { # Handle continuation lines
743 chop $line;
744 $line .= <HEADER>;
745 }
746
5668511f
NT
747 if ($line =~ /^#\s*include\s+([<"])(.*?)[>"]/) {
748 my ($delimiter, $new_file) = ($1, $2);
749 # copy the prefix in the quote syntax (#include "x.h") case
750 if ($delimiter eq q{"} && $file =~ m|^(.*)/|) {
751 $new_file = "$1/$new_file";
752 }
753 push(@ARGV, $new_file) unless $Is_converted{$new_file};
1d3434b8
GS
754 }
755 }
756 close HEADER;
757}
758
759
760# Determine include directories; $Config{usrinc} should be enough for (all
05d7b09c 761# non-GCC?) C compilers, but gcc uses additional include directories.
1d3434b8
GS
762sub inc_dirs
763{
e7ec705d
NT
764 my $from_gcc = `LC_ALL=C $Config{cc} -v -E - < /dev/null 2>&1 | awk '/^#include/, /^End of search list/' | grep '^ '`;
765 length($from_gcc) ? (split(' ', $from_gcc), $Config{usrinc}) : ($Config{usrinc});
1d3434b8
GS
766}
767
768
7f04632d
GS
769# Create "_h2ph_pre.ph", if it doesn't exist or was built by a different
770# version of h2ph.
771sub build_preamble_if_necessary
772{
773 # Increment $VERSION every time this function is modified:
3bea78d2 774 my $VERSION = 4;
7f04632d
GS
775 my $preamble = "$Dest_dir/_h2ph_pre.ph";
776
777 # Can we skip building the preamble file?
778 if (-r $preamble) {
779 # Extract version number from first line of preamble:
1ae6ead9 780 open PREAMBLE, "<", $preamble or die "Cannot open $preamble: $!";
7f04632d
GS
781 my $line = <PREAMBLE>;
782 $line =~ /(\b\d+\b)/;
783 close PREAMBLE or die "Cannot close $preamble: $!";
784
785 # Don't build preamble if a compatible preamble exists:
786 return if $1 == $VERSION;
787 }
788
789 my (%define) = _extract_cc_defines();
790
1ae6ead9 791 open PREAMBLE, ">", $preamble or die "Cannot open $preamble: $!";
ddfca5da 792 print PREAMBLE "# This file was created by h2ph version $VERSION\n";
3bea78d2
TC
793 # Prevent non-portable hex constants from warning.
794 #
795 # We still produce an overflow warning if we can't represent
796 # a hex constant as an integer.
797 print PREAMBLE "no warnings qw(portable);\n";
7f04632d 798
ddfca5da
JVD
799 foreach (sort keys %define) {
800 if ($opt_D) {
801 print PREAMBLE "# $_=$define{$_}\n";
802 }
803 if ($define{$_} =~ /^\((.*)\)$/) {
804 # parenthesized value: d=(v)
805 $define{$_} = $1;
806 }
8d66b3f9
RB
807 if (/^(\w+)\((\w)\)$/) {
808 my($macro, $arg) = ($1, $2);
809 my $def = $define{$_};
810 $def =~ s/$arg/\$\{$arg\}/g;
811 print PREAMBLE <<DEFINE;
812unless (defined &$macro) { sub $macro(\$) { my (\$$arg) = \@_; \"$def\" } }
813
814DEFINE
815 } elsif
816 ($define{$_} =~ /^([+-]?(\d+)?\.\d+([eE][+-]?\d+)?)[FL]?$/) {
ddfca5da
JVD
817 # float:
818 print PREAMBLE
819 "unless (defined &$_) { sub $_() { $1 } }\n\n";
820 } elsif ($define{$_} =~ /^([+-]?\d+)U?L{0,2}$/i) {
821 # integer:
822 print PREAMBLE
823 "unless (defined &$_) { sub $_() { $1 } }\n\n";
3bea78d2
TC
824 } elsif ($define{$_} =~ /^([+-]?0x[\da-f]+)U?L{0,2}$/i) {
825 # hex integer
826 # Special cased, since perl warns on hex integers
827 # that can't be represented in a UV.
828 #
829 # This way we get the warning at time of use, so the user
830 # only gets the warning if they happen to use this
831 # platform-specific definition.
832 my $code = $1;
833 $code = "hex('$code')" if length $code > 10;
834 print PREAMBLE
835 "unless (defined &$_) { sub $_() { $code } }\n\n";
ddfca5da 836 } elsif ($define{$_} =~ /^\w+$/) {
8d66b3f9
RB
837 my $def = $define{$_};
838 if ($isatype{$def}) {
839 print PREAMBLE
840 "unless (defined &$_) { sub $_() { \"$def\" } }\n\n";
841 } else {
842 print PREAMBLE
843 "unless (defined &$_) { sub $_() { &$def } }\n\n";
844 }
ddfca5da
JVD
845 } else {
846 print PREAMBLE
847 "unless (defined &$_) { sub $_() { \"",
848 quotemeta($define{$_}), "\" } }\n\n";
849 }
850 }
25436194 851 print PREAMBLE "\n1;\n"; # avoid 'did not return a true value' when empty
7f04632d
GS
852 close PREAMBLE or die "Cannot close $preamble: $!";
853}
854
855
856# %Config contains information on macros that are pre-defined by the
857# system's compiler. We need this information to make the .ph files
858# function with perl as the .h files do with cc.
859sub _extract_cc_defines
860{
861 my %define;
fc865b05 862 my $allsymbols = join " ",
ddfca5da 863 @Config{'ccsymbols', 'cppsymbols', 'cppccsymbols'};
7f04632d 864
28fb188d 865 # Split compiler pre-definitions into 'key=value' pairs:
ddfca5da
JVD
866 while ($allsymbols =~ /([^\s]+)=((\\\s|[^\s])+)/g) {
867 $define{$1} = $2;
868 if ($opt_D) {
869 print STDERR "$_: $1 -> $2\n";
870 }
7f04632d
GS
871 }
872
873 return %define;
874}
875
876
50f6e060
KS
8771;
878
154e51a4 879##############################################################################
1fef88e7
JM
880__END__
881
882=head1 NAME
883
884h2ph - convert .h C header files to .ph Perl header files
885
886=head1 SYNOPSIS
887
fe89bf70
P
888B<h2ph [-d destination directory] [-r | -a] [-l] [-h] [-e] [-D] [-Q]
889[headerfiles]>
1fef88e7
JM
890
891=head1 DESCRIPTION
154e51a4 892
1fef88e7 893I<h2ph>
154e51a4
LW
894converts any C header files specified to the corresponding Perl header file
895format.
896It is most easily run while in /usr/include:
154e51a4
LW
897
898 cd /usr/include; h2ph * sys/*
899
50f6e060
KS
900or
901
ef0ae776
JH
902 cd /usr/include; h2ph * sys/* arpa/* netinet/*
903
904or
905
50f6e060
KS
906 cd /usr/include; h2ph -r -l .
907
b306bf39
RS
908The output files are placed in the hierarchy rooted at Perl's
909architecture dependent library directory. You can specify a different
910hierarchy with a B<-d> switch.
911
fe14fcc3 912If run with no arguments, filters standard input to standard output.
1fef88e7 913
50f6e060
KS
914=head1 OPTIONS
915
916=over 4
917
918=item -d destination_dir
919
920Put the resulting B<.ph> files beneath B<destination_dir>, instead of
c561b895 921beneath the default Perl library location (C<$Config{'installsitearch'}>).
50f6e060
KS
922
923=item -r
924
925Run recursively; if any of B<headerfiles> are directories, then run I<h2ph>
1d3434b8
GS
926on all files in those directories (and their subdirectories, etc.). B<-r>
927and B<-a> are mutually exclusive.
928
929=item -a
930
931Run automagically; convert B<headerfiles>, as well as any B<.h> files
932which they include. This option will search for B<.h> files in all
933directories which your C compiler ordinarily uses. B<-a> and B<-r> are
934mutually exclusive.
50f6e060
KS
935
936=item -l
937
938Symbolic links will be replicated in the destination directory. If B<-l>
939is not specified, then links are skipped over.
940
941=item -h
942
28fb188d 943Put 'hints' in the .ph files which will help in locating problems with
50f6e060
KS
944I<h2ph>. In those cases when you B<require> a B<.ph> file containing syntax
945errors, instead of the cryptic
946
947 [ some error condition ] at (eval mmm) line nnn
948
949you will see the slightly more helpful
950
951 [ some error condition ] at filename.ph line nnn
952
953However, the B<.ph> files almost double in size when built using B<-h>.
954
fe89bf70
P
955=item -e
956
957If an error is encountered during conversion, output file will be removed and
958a warning emitted instead of terminating the conversion immediately.
959
1d3434b8
GS
960=item -D
961
962Include the code from the B<.h> file as a comment in the B<.ph> file.
963This is primarily used for debugging I<h2ph>.
964
7f04632d
GS
965=item -Q
966
28fb188d 967'Quiet' mode; don't print out the names of the files being converted.
7f04632d 968
50f6e060
KS
969=back
970
1fef88e7
JM
971=head1 ENVIRONMENT
972
154e51a4 973No environment variables are used.
1fef88e7
JM
974
975=head1 FILES
976
977 /usr/include/*.h
978 /usr/include/sys/*.h
979
154e51a4 980etc.
1fef88e7
JM
981
982=head1 AUTHOR
983
154e51a4 984Larry Wall
1fef88e7
JM
985
986=head1 SEE ALSO
987
154e51a4 988perl(1)
1fef88e7
JM
989
990=head1 DIAGNOSTICS
991
154e51a4 992The usual warnings if it can't read or write the files involved.
1fef88e7
JM
993
994=head1 BUGS
995
154e51a4 996Doesn't construct the %sizeof array for you.
1fef88e7 997
154e51a4
LW
998It doesn't handle all C constructs, but it does attempt to isolate
999definitions inside evals so that you can get at the definitions
1000that it can translate.
1fef88e7 1001
154e51a4
LW
1002It's only intended as a rough tool.
1003You may need to dicker with the files produced.
1fef88e7 1004
7f04632d
GS
1005You have to run this program by hand; it's not run as part of the Perl
1006installation.
1007
1008Doesn't handle complicated expressions built piecemeal, a la:
1009
1010 enum {
ddfca5da
JVD
1011 FIRST_VALUE,
1012 SECOND_VALUE,
7f04632d 1013 #ifdef ABC
ddfca5da 1014 THIRD_VALUE
7f04632d
GS
1015 #endif
1016 };
1017
1018Doesn't necessarily locate all of your C compiler's internally-defined
1019symbols.
1020
1fef88e7
JM
1021=cut
1022
154e51a4 1023!NO!SUBS!
4633a7c4
LW
1024
1025close OUT or die "Can't close $file: $!";
1026chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
1027exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
8a5546a1 1028chdir $origdir;