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