source: other-projects/trunk/realistic-books/bin/windows/perl/bin/h2ph.bat@ 19631

Last change on this file since 19631 was 19631, checked in by davidb, 15 years ago

addition of bin directory

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