This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Re: perlbug doesn't check that save succeeded
[perl5.git] / utils / h2ph.PL
1 #!/usr/local/bin/perl
2
3 use Config;
4 use File::Basename qw(basename dirname);
5 use Cwd;
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.
17 $origdir = cwd;
18 chdir dirname($0);
19 $file = basename($0, '.PL');
20 $file .= '.com' if $^O eq 'VMS';
21
22 open OUT,">$file" or die "Can't create $file: $!";
23
24 print "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
29 print OUT <<"!GROK!THIS!";
30 $Config{startperl}
31     eval 'exec $Config{perlpath} -S \$0 \${1+"\$@"}'
32         if \$running_under_some_shell;
33 !GROK!THIS!
34
35 # In the following, perl variables are not expanded during extraction.
36
37 print OUT <<'!NO!SUBS!';
38
39 use Config;
40 use File::Path qw(mkpath);
41 use Getopt::Std;
42
43 getopts('Dd:rlhaQ');
44 die "-r and -a options are mutually exclusive\n" if ($opt_r and $opt_a);
45 @inc_dirs = inc_dirs() if $opt_a;
46
47 my $Exit = 0;
48
49 my $Dest_dir = $opt_d || $Config{installsitearch};
50 die "Destination directory $Dest_dir doesn't exist or isn't a directory\n"
51     unless -d $Dest_dir;
52
53 @isatype = split(' ',<<END);
54         char    uchar   u_char
55         short   ushort  u_short
56         int     uint    u_int
57         long    ulong   u_long
58         FILE    key_t   caddr_t
59 END
60
61 @isatype{@isatype} = (1) x @isatype;
62 $inif = 0;
63
64 @ARGV = ('-') unless @ARGV;
65
66 while (defined ($file = next_file())) {
67     if (-l $file and -d $file) {
68         link_if_possible($file) if ($opt_l);
69         next;
70     }
71
72     # Recover from header files with unbalanced cpp directives
73     $t = '';
74     $tab = 0;
75
76     # $eval_index goes into ``#line'' directives, to help locate syntax errors:
77     $eval_index = 1;
78
79     if ($file eq '-') {
80         open(IN, "-");
81         open(OUT, ">-");
82     } else {
83         ($outfile = $file) =~ s/\.h$/.ph/ || next;
84         print "$file -> $outfile\n" unless $opt_Q;
85         if ($file =~ m|^(.*)/|) {
86             $dir = $1;
87             mkpath "$Dest_dir/$dir";
88         }
89
90         if ($opt_a) { # automagic mode:  locate header file in @inc_dirs
91             foreach (@inc_dirs) {
92                 chdir $_;
93                 last if -f $file;
94             }
95         }
96
97         open(IN,"$file") || (($Exit = 1),(warn "Can't open $file: $!\n"),next);
98         open(OUT,">$Dest_dir/$outfile") || die "Can't create $outfile: $!\n";
99     }
100     while (<IN>) {
101         chop;
102         while (/\\$/) {
103             chop;
104             $_ .= <IN>;
105             chop;
106         }
107         print OUT "# $_\n" if $opt_D;
108         if (s:/\*:\200:g) {
109             s:\*/:\201:g;
110             s/\200[^\201]*\201//g;      # delete single line comments
111             if (s/\200.*//) {           # begin multi-line comment?
112                 $_ .= '/*';
113                 $_ .= <IN>;
114                 redo;
115             }
116         }
117         if (s/^\s*\#\s*//) {
118             if (s/^define\s+(\w+)//) {
119                 $name = $1;
120                 $new = '';
121                 s/\s+$//;
122                 if (s/^\(([\w,\s]*)\)//) {
123                     $args = $1;
124                     my $proto = '() ';
125                     if ($args ne '') {
126                         $proto = '';
127                         foreach $arg (split(/,\s*/,$args)) {
128                             $arg =~ s/^\s*([^\s].*[^\s])\s*$/$1/;
129                             $curargs{$arg} = 1;
130                         }
131                         $args =~ s/\b(\w)/\$$1/g;
132                         $args = "local($args) = \@_;\n$t    ";
133                     }
134                     s/^\s+//;
135                     expr();
136                     $new =~ s/(["\\])/\\$1/g;       #"]);
137                     $new = reindent($new);
138                     $args = reindent($args);
139                     if ($t ne '') {
140                         $new =~ s/(['\\])/\\$1/g;   #']);
141                         if ($opt_h) {
142                             print OUT $t,
143                             "eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name $proto\{\n$t    ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
144                             $eval_index++;
145                         } else {
146                             print OUT $t,
147                             "eval 'sub $name $proto\{\n$t    ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
148                         }
149                     } else {
150                       print OUT "unless(defined(\&$name)) {\n    sub $name $proto\{\n\t${args}eval q($new);\n    }\n}\n";
151                     }
152                     %curargs = ();
153                 } else {
154                     s/^\s+//;
155                     expr();
156                     $new = 1 if $new eq '';
157                     $new = reindent($new);
158                     $args = reindent($args);
159                     if ($t ne '') {
160                         $new =~ s/(['\\])/\\$1/g;        #']);
161                         if ($opt_h) {
162                             print OUT $t,"eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name () {",$new,";}' unless defined(\&$name);\n";
163                             $eval_index++;
164                         } else {
165                             print OUT $t,"eval 'sub $name () {",$new,";}' unless defined(\&$name);\n";
166                         }
167                     } else {
168                       print OUT $t,"unless(defined(\&$name)) {\n    sub $name () {\t",$new,";}\n}\n";
169                     }
170                 }
171             } elsif (/^(include|import)\s*[<"](.*)[>"]/) {
172                 ($incl = $2) =~ s/\.h$/.ph/;
173                 print OUT $t,"require '$incl';\n";
174             } elsif(/^include_next\s*[<"](.*)[>"]/) {
175                 ($incl = $1) =~ s/\.h$/.ph/;
176                 print OUT ($t,
177                            "eval {\n");
178                 $tab += 4;
179                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
180                 print OUT ($t,
181                            "my(\%INCD) = map { \$INC{\$_} => 1 } ",
182                            "(grep { \$_ eq \"$incl\" } keys(\%INC));\n");
183                 print OUT ($t,
184                            "my(\@REM) = map { \"\$_/$incl\" } ",
185                            "(grep { not exists(\$INCD{\"\$_/$incl\"})",
186                            "and -f \"\$_/$incl\" } \@INC);\n");
187                 print OUT ($t,
188                            "require \"\$REM[0]\" if \@REM;\n");
189                 $tab -= 4;
190                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
191                 print OUT ($t,
192                            "};\n");
193                 print OUT ($t,
194                            "warn(\$\@) if \$\@;\n");
195             } elsif (/^ifdef\s+(\w+)/) {
196                 print OUT $t,"if(defined(&$1)) {\n";
197                 $tab += 4;
198                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
199             } elsif (/^ifndef\s+(\w+)/) {
200                 print OUT $t,"unless(defined(&$1)) {\n";
201                 $tab += 4;
202                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
203             } elsif (s/^if\s+//) {
204                 $new = '';
205                 $inif = 1;
206                 expr();
207                 $inif = 0;
208                 print OUT $t,"if($new) {\n";
209                 $tab += 4;
210                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
211             } elsif (s/^elif\s+//) {
212                 $new = '';
213                 $inif = 1;
214                 expr();
215                 $inif = 0;
216                 $tab -= 4;
217                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
218                 print OUT $t,"}\n elsif($new) {\n";
219                 $tab += 4;
220                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
221             } elsif (/^else/) {
222                 $tab -= 4;
223                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
224                 print OUT $t,"} else {\n";
225                 $tab += 4;
226                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
227             } elsif (/^endif/) {
228                 $tab -= 4;
229                 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
230                 print OUT $t,"}\n";
231             } elsif(/^undef\s+(\w+)/) {
232                 print OUT $t, "undef(&$1) if defined(&$1);\n";
233             } elsif(/^error\s+(.*)/) {
234                 print OUT $t, "die(\"$1\");\n";
235             } elsif(/^warning\s+(.*)/) {
236                 print OUT $t, "warn(\"$1\");\n";
237             } elsif(/^ident\s+(.*)/) {
238                 print OUT $t, "# $1\n";
239             }
240         } elsif(/^\s*(typedef\s*)?enum\s*(\s+[a-zA-Z_]\w*\s*)?\{/) {
241             until(/\}.*?;/) {
242                 chomp($next = <IN>);
243                 $_ .= $next;
244                 print OUT "# $next\n" if $opt_D;
245             }
246             s@/\*.*?\*/@@g;
247             s/\s+/ /g;
248             /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/;
249             ($enum_subs = $3) =~ s/\s//g;
250             @enum_subs = split(/,/, $enum_subs);
251             $enum_val = -1;
252             for $enum (@enum_subs) {
253                 ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/;
254                 $enum_value =~ s/^=//;
255                 $enum_val = (length($enum_value) ? $enum_value : $enum_val + 1);
256                 if ($opt_h) {
257                     print OUT ($t,
258                                "eval(\"\\n#line $eval_index $outfile\\n",
259                                "sub $enum_name () \{ $enum_val; \}\") ",
260                                "unless defined(\&$enum_name);\n");
261                     ++ $eval_index;
262                 } else {
263                     print OUT ($t,
264                                "eval(\"sub $enum_name () \{ $enum_val; \}\") ",
265                                "unless defined(\&$enum_name);\n");
266                 }
267             }
268         }
269     }
270     print OUT "1;\n";
271
272     $is_converted{$file} = 1;
273     queue_includes_from($file) if ($opt_a);
274 }
275
276 exit $Exit;
277
278 sub reindent($) {
279     my($text) = shift;
280     $text =~ s/\n/\n    /g;
281     $text =~ s/        /\t/g;
282     $text;
283 }
284
285 sub expr {
286     if(keys(%curargs)) {
287         my($joined_args) = join('|', keys(%curargs));
288     }
289     while ($_ ne '') {
290         s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator
291         s/^\&([\(a-z\)]+)/$1/i; # hack for things that take the address of
292         s/^(\s+)//              && do {$new .= ' '; next;};
293         s/^(0X[0-9A-F]+)[UL]*//i        && do {$new .= lc($1); next;};
294         s/^(-?\d+\.\d+E[-+]\d+)F?//i    && do {$new .= $1; next;};
295         s/^(\d+)\s*[LU]*//i     && do {$new .= $1; next;};
296         s/^("(\\"|[^"])*")//    && do {$new .= $1; next;};
297         s/^'((\\"|[^"])*)'//    && do {
298             if ($curargs{$1}) {
299                 $new .= "ord('\$$1')";
300             } else {
301                 $new .= "ord('$1')";
302             }
303             next;
304         };
305         # replace "sizeof(foo)" with "{foo}"
306         # also, remove * (C dereference operator) to avoid perl syntax
307         # problems.  Where the %sizeof array comes from is anyone's
308         # guess (c2ph?), but this at least avoids fatal syntax errors.
309         # Behavior is undefined if sizeof() delimiters are unbalanced.
310         # This code was modified to able to handle constructs like this:
311         #   sizeof(*(p)), which appear in the HP-UX 10.01 header files.
312         s/^sizeof\s*\(// && do {
313             $new .= '$sizeof';
314             my $lvl = 1;  # already saw one open paren
315             # tack { on the front, and skip it in the loop
316             $_ = "{" . "$_";
317             my $index = 1;
318             # find balanced closing paren
319             while ($index <= length($_) && $lvl > 0) {
320                 $lvl++ if substr($_, $index, 1) eq "(";
321                 $lvl-- if substr($_, $index, 1) eq ")";
322                 $index++;
323             }
324             # tack } on the end, replacing )
325             substr($_, $index - 1, 1) = "}";
326             # remove pesky * operators within the sizeof argument
327             substr($_, 0, $index - 1) =~ s/\*//g;
328             next;
329         };
330         # Eliminate typedefs
331         /\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do {
332             foreach (split /\s+/, $1) {  # Make sure all the words are types,
333                 last unless ($isatype{$_} or $_ eq 'struct');
334             }
335             s/\([\w\s]+[\*\s]*\)// && next;      # then eliminate them.
336         };
337         # struct/union member, including arrays:
338         s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do {
339             $id = $1;
340             $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g;
341             $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args);
342             while($id =~ /\[\s*([^\$\&\d\]]+)\]/) {
343                 my($index) = $1;
344                 $index =~ s/\s//g;
345                 if(exists($curargs{$index})) {
346                     $index = "\$$index";
347                 } else {
348                     $index = "&$index";
349                 }
350                 $id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/;
351             }
352             $new .= " (\$$id)";
353         };
354         s/^([_a-zA-Z]\w*)//     && do {
355             $id = $1;
356             if ($id eq 'struct') {
357                 s/^\s+(\w+)//;
358                 $id .= ' ' . $1;
359                 $isatype{$id} = 1;
360             } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) {
361                 while (s/^\s+(\w+)//) { $id .= ' ' . $1; }
362                 $isatype{$id} = 1;
363             }
364             if ($curargs{$id}) {
365                 $new .= "\$$id";
366                 $new .= '->' if /^[\[\{]/;
367             } elsif ($id eq 'defined') {
368                 $new .= 'defined';
369             } elsif (/^\(/) {
370                 s/^\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i;     # cheat
371                 $new .= " &$id";
372             } elsif ($isatype{$id}) {
373                 if ($new =~ /{\s*$/) {
374                     $new .= "'$id'";
375                 } elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) {
376                     $new =~ s/\(\s*$//;
377                     s/^[\s*]*\)//;
378                 } else {
379                     $new .= q(').$id.q(');
380                 }
381             } else {
382                 if ($inif && $new !~ /defined\s*\($/) {
383                     $new .= '(defined(&' . $id . ') ? &' . $id . ' : 0)';
384                 } elsif (/^\[/) {
385                     $new .= " \$$id";
386                 } else {
387                     $new .= ' &' . $id;
388                 }
389             }
390             next;
391         };
392         s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;};
393     }
394 }
395
396
397 # Handle recursive subdirectories without getting a grotesquely big stack.
398 # Could this be implemented using File::Find?
399 sub next_file
400 {
401     my $file;
402
403     while (@ARGV) {
404         $file = shift @ARGV;
405
406         if ($file eq '-' or -f $file or -l $file) {
407             return $file;
408         } elsif (-d $file) {
409             if ($opt_r) {
410                 expand_glob($file);
411             } else {
412                 print STDERR "Skipping directory `$file'\n";
413             }
414         } elsif ($opt_a) {
415             return $file;
416         } else {
417             print STDERR "Skipping `$file':  not a file or directory\n";
418         }
419     }
420
421     return undef;
422 }
423
424
425 # Put all the files in $directory into @ARGV for processing.
426 sub expand_glob
427 {
428     my ($directory)  = @_;
429
430     $directory =~ s:/$::;
431
432     opendir DIR, $directory;
433         foreach (readdir DIR) {
434             next if ($_ eq '.' or $_ eq '..');
435
436             # expand_glob() is going to be called until $ARGV[0] isn't a
437             # directory; so push directories, and unshift everything else.
438             if (-d "$directory/$_") { push    @ARGV, "$directory/$_" }
439             else                    { unshift @ARGV, "$directory/$_" }
440         }
441     closedir DIR;
442 }
443
444
445 # Given $file, a symbolic link to a directory in the C include directory,
446 # make an equivalent symbolic link in $Dest_dir, if we can figure out how.
447 # Otherwise, just duplicate the file or directory.
448 sub link_if_possible
449 {
450     my ($dirlink)  = @_;
451     my $target  = eval 'readlink($dirlink)';
452
453     if ($target =~ m:^\.\./: or $target =~ m:^/:) {
454         # The target of a parent or absolute link could leave the $Dest_dir
455         # hierarchy, so let's put all of the contents of $dirlink (actually,
456         # the contents of $target) into @ARGV; as a side effect down the
457         # line, $dirlink will get created as an _actual_ directory.
458         expand_glob($dirlink);
459     } else {
460         if (-l "$Dest_dir/$dirlink") {
461             unlink "$Dest_dir/$dirlink" or
462                 print STDERR "Could not remove link $Dest_dir/$dirlink:  $!\n";
463         }
464
465         if (eval 'symlink($target, "$Dest_dir/$dirlink")') {
466             print "Linking $target -> $Dest_dir/$dirlink\n";
467
468             # Make sure that the link _links_ to something:
469             if (! -e "$Dest_dir/$target") {
470                 mkpath("$Dest_dir/$target", 0755) or
471                     print STDERR "Could not create $Dest_dir/$target/\n";
472             }
473         } else {
474             print STDERR "Could not symlink $target -> $Dest_dir/$dirlink:  $!\n";
475         }
476     }
477 }
478
479
480 # Push all #included files in $file onto our stack, except for STDIN
481 # and files we've already processed.
482 sub queue_includes_from
483 {
484     my ($file)    = @_;
485     my $line;
486
487     return if ($file eq "-");
488
489     open HEADER, $file or return;
490         while (defined($line = <HEADER>)) {
491             while (/\\$/) { # Handle continuation lines
492                 chop $line;
493                 $line .= <HEADER>;
494             }
495
496             if ($line =~ /^#\s*include\s+<(.*?)>/) {
497                 push(@ARGV, $1) unless $is_converted{$1};
498             }
499         }
500     close HEADER;
501 }
502
503
504 # Determine include directories; $Config{usrinc} should be enough for (all
505 # non-GCC?) C compilers, but gcc uses an additional include directory.
506 sub inc_dirs
507 {
508     my $from_gcc    = `$Config{cc} -v 2>&1`;
509     $from_gcc       =~ s:^Reading specs from (.*?)/specs\b.*:$1/include:s;
510
511     length($from_gcc) ? ($from_gcc, $Config{usrinc}) : ($Config{usrinc});
512 }
513
514
515 1;
516
517 ##############################################################################
518 __END__
519
520 =head1 NAME
521
522 h2ph - convert .h C header files to .ph Perl header files
523
524 =head1 SYNOPSIS
525
526 B<h2ph [-d destination directory] [-r | -a] [-l] [headerfiles]>
527
528 =head1 DESCRIPTION
529
530 I<h2ph>
531 converts any C header files specified to the corresponding Perl header file
532 format.
533 It is most easily run while in /usr/include:
534
535         cd /usr/include; h2ph * sys/*
536
537 or
538
539         cd /usr/include; h2ph -r -l .
540
541 The output files are placed in the hierarchy rooted at Perl's
542 architecture dependent library directory.  You can specify a different
543 hierarchy with a B<-d> switch.
544
545 If run with no arguments, filters standard input to standard output.
546
547 =head1 OPTIONS
548
549 =over 4
550
551 =item -d destination_dir
552
553 Put the resulting B<.ph> files beneath B<destination_dir>, instead of
554 beneath the default Perl library location (C<$Config{'installsitsearch'}>).
555
556 =item -r
557
558 Run recursively; if any of B<headerfiles> are directories, then run I<h2ph>
559 on all files in those directories (and their subdirectories, etc.).  B<-r>
560 and B<-a> are mutually exclusive.
561
562 =item -a
563
564 Run automagically; convert B<headerfiles>, as well as any B<.h> files
565 which they include.  This option will search for B<.h> files in all
566 directories which your C compiler ordinarily uses.  B<-a> and B<-r> are
567 mutually exclusive.
568
569 =item -l
570
571 Symbolic links will be replicated in the destination directory.  If B<-l>
572 is not specified, then links are skipped over.
573
574 =item -h
575
576 Put ``hints'' in the .ph files which will help in locating problems with
577 I<h2ph>.  In those cases when you B<require> a B<.ph> file containing syntax
578 errors, instead of the cryptic
579
580         [ some error condition ] at (eval mmm) line nnn
581
582 you will see the slightly more helpful
583
584         [ some error condition ] at filename.ph line nnn
585
586 However, the B<.ph> files almost double in size when built using B<-h>.
587
588 =item -D
589
590 Include the code from the B<.h> file as a comment in the B<.ph> file.
591 This is primarily used for debugging I<h2ph>.
592
593 =back
594
595 =head1 ENVIRONMENT
596
597 No environment variables are used.
598
599 =head1 FILES
600
601  /usr/include/*.h
602  /usr/include/sys/*.h
603
604 etc.
605
606 =head1 AUTHOR
607
608 Larry Wall
609
610 =head1 SEE ALSO
611
612 perl(1)
613
614 =head1 DIAGNOSTICS
615
616 The usual warnings if it can't read or write the files involved.
617
618 =head1 BUGS
619
620 Doesn't construct the %sizeof array for you.
621
622 It doesn't handle all C constructs, but it does attempt to isolate
623 definitions inside evals so that you can get at the definitions
624 that it can translate.
625
626 It's only intended as a rough tool.
627 You may need to dicker with the files produced.
628
629 =cut
630
631 !NO!SUBS!
632
633 close OUT or die "Can't close $file: $!";
634 chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
635 exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
636 chdir $origdir;