[project @ 1997-10-30 22:45:08 by sof]
[ghc-hetmet.git] / ghc / utils / mkdependHS / mkdependHS.prl
1 #
2 # perl script expect the following variables to be prepended:
3 #
4 #  RAWCPP TMPDIR TOP_PWD
5 #  libdir libexecdir datadir INSTALLING
6 #  PROJECTVERSION SED 
7 #
8 # tries to work like mkdependC - capable of dealing with:
9 #
10 #  -literate Haskell code (Bird tracks or Glasgow literate style) (.lhs)
11 #  -straight Haskell source (.hs)
12 #  -literate or straight Happy specs    (.ly)
13 #  
14 # ToDo: strip out all the .h junk
15 #
16 ($Pgm = $0) =~ s/.*\/([^\/]+)$/\1/;
17 $Usage  = <<EOUSAGE;
18 Usage: $Pgm [mkdependHS options] [-- GHC options --] srcfile1 [srcfile2 ...]
19
20 Options recognised wherever they occur (mkdependHS or GHC):
21
22     -D<blah>    A cpp #define; usual meaning
23     -i<dirs>    Add <dirs> (colon-separated) to list of directories
24                 to search for "import"ed modules
25     -I<dir>     Add <dir> to list of directories to search for
26                 .h files (i.e., usual meaning)
27     -syslib <blah> This program uses this GHC system library; take
28                 appropriate action (e.g., recognise when they are
29                 "import"ing a module from that library).
30
31 mkdependHS-specific options (not between --'s):
32
33     -v          Be verbose.
34     -v -v       Be very verbose.
35     -W          No warnings
36     -f blah     Use "blah" as the makefile, rather than "makefile"
37                 or "Makefile".
38     -o <osuf>   Use <osuf> as the "object file" suffix ( default: o)
39     -s <suf>    Make extra dependencies for files with
40                 suffix <suf><osuf>; thus, "-o hc -s _a" will
41                 make dependencies both for .hc files and for .a_hc
42                 files.  (Useful in conjunction with NoFib "ways".)
43     --exclude-module=<file> 
44                 Regard <file> as "stable"; i.e., eXclude it from having
45                 dependencies on it.
46     -x          same as --exclude-module
47     --exclude-directory=<dirs> 
48                 Regard : separated list of directories as containing stable,
49                 don't generate any dependencies on modules therein.
50     -Xdirs      same as --exclude-directory
51     --include-module=<file> 
52                 Regard <file> as not "stable"; i.e., generate dependencies
53                 on it (if any). This option is normally used in conjunction 
54                 with the --exclude-directory option.
55
56 EOUSAGE
57
58 $Status     = 0; # just used for exit() status
59 $Verbose    = 0; # 1 => verbose, 2 => very verbose
60 $Warnings   = 1; # 1 => warn about duplicate interface files
61 $Dashdashes_seen = 0;
62
63 # Try to guess how to run gcc's CPP directly -------------
64
65 $OrigCpp = ${RAWCPP};
66 if ( $OrigCpp !~ /(\S+)\s+(.*)/ ) {
67     $Cpp = $OrigCpp;
68 } else {
69     $cmd  = $1;
70     $rest = $2;
71     if ( -x $cmd ) { # cool
72         $Cpp = $OrigCpp;
73     } else { # oops; try to guess
74         $GccV = `gcc -v 2>&1`;
75         if ( $GccV =~ /Reading specs from (.*)\/specs/ ) {
76             $Cpp = "$1/cpp $rest";
77         } else {
78             die "mkdependHS: don't know how to run cpp: $OrigCpp\n";
79         }
80     }
81 }
82
83 if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
84     $Tmp_prefix = $ENV{'TMPDIR'} . "/mkdependHS$$";
85 } else {
86     $Tmp_prefix ="${TMPDIR}/mkdependHS$$";
87     $ENV{'TMPDIR'} = "${TMPDIR}"; # set the env var as well
88 }
89
90 $TopPwd            = "${TOP_PWD}";
91 $InstLibDirGhc     = "${libdir}";
92 $InstLibExecDirGhc = "${libexecdir}";
93 $InstHsLibDirGhc   = "${libdir}/hslibs";
94 $InstDataDirGhc    = "${datadir}";
95
96 $Unlit = ($INSTALLING) ? "${InstLibExecDirGhc}/unlit" 
97                        : "${TopPwd}/ghc/utils/unlit/unlit";
98
99 $Begin_magic_str = "# DO NOT DELETE: Beginning of Haskell dependencies\n";
100 $End_magic_str = "# DO NOT DELETE: End of Haskell dependencies\n";
101 @Obj_suffix =  ("o");
102 @File_suffix = ();
103 $ghc_version_info = int ( ${PROJECTVERSION} * 100 );
104
105 $Import_dirs = '.';
106 %Syslibs = ();
107 %LibIfaces  = ();  # known prelude/syslib ifaces; read from a file
108
109 %IgnoreMe = ();
110 # directories to considered stable.
111 @Ignore_dirs = ($INSTALLING) ? 
112                    ("$InstLibDirGhc/imports")
113                  : ("$TopPwd/ghc/lib/ghc",
114                     "$TopPwd/ghc/lib/required",
115                     "$TopPwd/ghc/lib/glaExts",
116                     "$TopPwd/ghc/lib/concurrent");
117
118 $Include_dirs = '-I.';
119 $Makefile = '';
120 @Src_files = ();
121
122 &mangle_command_line_args();
123
124 # set up array of ignored modules
125 foreach $lib ( @Syslibs ) {
126     local($dir) = 
127       ($INSTALLING) ? "${InstHsLibDirGhc}/${lib}/imports" 
128                     : "${TopPwd}/hslibs/${lib}/src";
129     push(@Ignore_dirs,$dir);
130 }
131
132 if ( $Status ) {
133     print stderr $Usage;
134     exit(1);
135 }
136
137 push(@Defines,
138      ( #OLD: "-D__HASKELL1__=$Haskell_1",
139       "-D__GLASGOW_HASKELL__=$ghc_version_info"));
140
141 @Import_dirs  = split(/:/,$Import_dirs);
142 @Include_dirs = split(/\s+/,$Include_dirs); # still has -I's in it
143 # NB: We keep the scalar-variable equivalents to use in error messages
144
145 if ( ! $Makefile && -f 'makefile' ) {
146     $Makefile = 'makefile';
147 } elsif ( ! $Makefile && -f 'Makefile') {
148     $Makefile = 'Makefile';
149 } elsif ( ! $Makefile) {
150     die "$Pgm: no makefile or Makefile found\n";
151 }
152
153 print STDERR "CPP defines=@Defines\n" if $Verbose;
154 print STDERR "Import_dirs=@Import_dirs\n" if $Verbose;
155 print STDERR "Include_dirs=@Include_dirs\n" if $Verbose;
156
157 &preprocess_import_dirs();
158
159 @Depend_lines = ();
160
161 # Delete temp. file if script is halted.
162 sub quit_upon_signal { print STDERR "Deleting $Tmp_prefix.hs .. \n"; unlink "$Tmp_prefix.hs"; }
163 $SIG{'INT'}  = 'quit_upon_signal';
164 $SIG{'QUIT'} = 'quit_upon_signal';
165
166 foreach $sf (@Src_files) {
167
168     # just like lit-inputter
169     # except it puts each file through CPP and
170     # a de-commenter (not implemented);
171     # builds up @Depend_lines
172     print STDERR "Here we go for source file: $sf\n" if $Verbose;
173     ($bf = $sf) =~ s/\.l?(hs|y)$//;
174
175     local($str)="";
176     foreach $obj  (@Obj_suffix) {
177         $str .= "$bf.$obj ";
178         foreach $suff (@File_suffix) {
179            $str .= "$bf.${suff}_$obj ";
180         }
181     }
182     push(@Depend_lines, "$str: $sf\n");
183     # if it's a literate file, .lhs or .ly? (happy specs), then we de-literatize it: 
184     if ( $sf !~ /\.l(hs|y)$/ ) {
185         $file_to_read = $sf;
186     } else {
187         $file_to_read = "$Tmp_prefix.hs";
188         local($to_do) = "$Unlit $sf $file_to_read";
189         &run_something($to_do, 'unlit');
190     }
191     &slurp_file_for_imports($file_to_read, $sf);
192
193     if ( $sf =~ /\.l(hs|y)$/ ) {
194         unlink "$Tmp_prefix.hs";
195     }
196 }
197
198
199 # OK, mangle the Makefile
200 unlink("$Makefile.bak");
201
202 #
203 # If no output file exist as yet, create one.
204
205 if ( ! -f $Makefile.bak ) {
206    system("touch $Makefile.bak");
207
208 if ( -f $Makefile ) {
209    rename($Makefile,"$Makefile.bak");
210 }
211 # now copy Makefile.bak into Makefile, rm'ing old dependencies
212 # and adding the new
213 open(OMKF,"< $Makefile.bak") || die "$Pgm: can't open $Makefile.bak: $!\n";
214 open(NMKF,"> $Makefile") || die "$Pgm: can't open $Makefile: $!\n";
215 select(NMKF);
216 $_ = <OMKF>;
217 while ($_ && $_ ne $Begin_magic_str) { # copy through, 'til Begin_magic_str
218     print $_;
219     $_ = <OMKF>;
220 }
221 while ($_ && $_ ne $End_magic_str) { # delete 'til End_magic_str
222     $_ = <OMKF>;
223 }
224 # insert dependencies
225 print $Begin_magic_str;
226 print @Depend_lines;
227 print $End_magic_str;
228 while (<OMKF>) { # copy the rest through
229     print $_;
230 }
231 close(NMKF) || exit(1);
232 close(OMKF) || exit(1);
233 exit 0;
234
235 sub mangle_command_line_args {
236     while($_ = $ARGV[0]) {
237         shift(@ARGV);
238
239         if ( /^--$/ ) {
240             $Dashdashes_seen++;
241
242         } elsif ( /^-D(.*)/ ) { # recognized wherever they occur
243             push(@Defines, $_);
244         } elsif ( /^-i(.*)/ ) { # ditto
245             $Import_dirs .= ":$1";
246         } elsif ( /^-I/ ) {
247             $Include_dirs .= " $_";
248         } elsif ( /^-syslib$/ ) {
249             push(@Syslibs, &grab_arg_arg($_,''));
250         } elsif ($Dashdashes_seen != 1) { # not between -- ... --
251             if ( /^-v$/ ) {
252                 $Verbose++;
253             } elsif ( /^-W$/ ) {
254                 $Warnings     = 0;
255             } elsif ( /^-f(.*)/ ) {
256                 $Makefile       = &grab_arg_arg('-f',$1);
257             } elsif ( /^-o(.*)/ ) {
258                 local($suff)    = &grab_arg_arg('-o',$1);
259                 # Weed out existing entry .. there must be a better way of doing this
260                 # with arrays (non-assoc) ! -- sof
261                 @Obj_suffix     = grep(!/$suff/,@Obj_suffix);
262                 push(@Obj_suffix, $suff);
263             #
264             # --exclude-module=mod => it's stable, trust me!
265             
266             } elsif ( /^-(x|-exclude-module=)(.*)/ ) { 
267                 local($thing) = &grab_arg_arg($1,$2);
268                 $IgnoreMe{$thing} = 'y';
269             } elsif ( /^-(X|-exclude-directory=)(.*)/ ) { 
270                 foreach $d ( split(/:/,&grab_arg_arg($1, $2)) ) {
271                    push(@Ignore_dirs,"$d");
272                 }
273             } elsif ( /^--include-module=(.*)/ ) { 
274                 local($thing) = &grab_arg_arg($1,$2);
275                 $IgnoreMe{$thing} = 'n';
276             } elsif ( /^-s(.*)/ ) {
277                 local($suff)    =  &grab_arg_arg('-s',$1);
278                 push(@File_suffix, $suff);
279             } elsif ( /^-/ ) {
280                 print STDERR "$Pgm: unknown option ignored: $_\n";
281                 $Status++;
282             } else {
283                 push(@Src_files, $_);
284             }
285
286         } elsif ($Dashdashes_seen == 1) { # where we ignore unknown options
287             push(@Src_files, $_) if ! /^-/;
288         }
289     }
290     @File_suffix = sort (@File_suffix);
291 }
292
293 sub grab_arg_arg {
294     local($option, $rest_of_arg) = @_;
295     
296     if ($rest_of_arg) {
297         return($rest_of_arg);
298     } elsif ($#ARGV >= 0) {
299         local($temp) = $ARGV[0]; shift(@ARGV); 
300         return($temp);
301     } else {
302         print STDERR "$Pgm: no argument following $option option\n";
303         $Status++;
304     }
305 }
306
307 sub preprocess_import_dirs {
308     # it's probably cheaper to find out what's in all
309     # the @Import_dirs before we start processing.
310     local($d, $thing);
311     local($_);
312     %ModuleIn = ();
313
314     foreach $d ( @Import_dirs ) {
315         # Check to see if it can be ignored
316         #print STDERR "Ignore imports from $d\n" if $Verbose && $Ignore_dirs{$d};
317         #next if $Ignore_dirs{$d};
318
319         opendir(DIR, $d) || die "$Pgm: can't open directory $d\n";
320
321         for ($_ = readdir(DIR); $_; $_ = readdir(DIR)) {
322             next unless /(.*)\.hi$/;
323             $thing = $1;
324             if ($ModuleIn{$thing} && $ModuleIn{$thing} ne $d) {
325                 print STDERR "$Pgm: warning: $thing.hi appears in both $ModuleIn{$thing} and $d!\n" if ($Warnings);
326             } else {
327                 $ModuleIn{$thing} = $d;
328             }
329         }
330         closedir(DIR); # No, don't check the error code
331     }
332
333     # Add all the modules
334     # to the IgnoreMe array before we start scanning for imports.
335     foreach $d (@Ignore_dirs) {
336
337         opendir(DIR, $d) || die "$Pgm: can't open directory $d\n";
338
339         for ($_ = readdir(DIR); $_; $_ = readdir(DIR)) {
340             next unless /(.*)\.(hi|l?hs|l?y)$/;
341             #don't tag it twice or overwrite it with a diff. value
342             next if $IgnoreMe{$1};
343             print STDERR "Module $d/$1.$2 will be ignored\n" if $Verbose;
344
345             $IgnoreMe{$1} = 'y';
346         }
347         closedir(DIR); # No, don't check the error code
348     }
349 }
350
351 sub slurp_file_for_imports {
352     local($file_to_read, $orig_src_file) = @_;
353     local($follow_file);
354
355     local($last_seen_dir) = $orig_src_file;
356     $last_seen_dir =~ s/\/[^\/]+$//; # strip to dir name
357     $last_seen_dir = '.' if ($last_seen_dir eq $orig_src_file);
358
359     # we mangle #include's so they will also leave something
360     # behind to indicate the dependency on _them_
361     
362     print STDERR "${SED} -e '/^# *include/{p;s/^# *include/!include/;};s/'\\''//g;s/\"//g' $file_to_read | $Cpp $Include_dirs -I$last_seen_dir @Defines |\n" if $Verbose;
363
364     open(SRCFILE, "${SED} -e '/^# *include/{p;s/^# *include/!include/;};s/'\\''//g;s/\"//g' $file_to_read | $Cpp $Include_dirs -I$last_seen_dir @Defines |")
365         || die "$Pgm: Can't open $file_to_read: $!\n";
366
367     while (<SRCFILE>) {
368         #
369         # import {-# SOURCE #-} Foo (bar) generates dependencies on the source file only,
370         # the compiler will deal with the absence of Foo.hi by consulting the
371         # source for Foo directly. (for dealing with recursive modules).
372         #
373         next unless (/^>?\s*(import)(\s+{-#\s*SOURCE\s*#-})?(\s+qualified)?\s+([A-Z][A-Za-z0-9_']*)/ || /^!(include)(\s+)"(\S+)"/);
374         $todo    = $1;
375         $source  = ( $2 ne '') ? 1 : 0;
376         $modname = $4;
377
378         next if $modname eq '';
379         if ($todo eq 'import') {
380             if ( $ModuleIn{$modname} ) {
381                    $follow_file = "$ModuleIn{$modname}/$modname.hi";
382             } else { # hard way
383                 $follow_file
384                   = &find_in_Import_dirs($orig_src_file, $modname, $last_seen_dir, $source );
385             }
386         } else {
387                 $follow_file
388                   = &find_in_Include_dirs($orig_src_file, $modname, $last_seen_dir);
389         }
390
391         if (! $follow_file) { # it didnae find anything
392             die "$orig_src_file: Couldn't handle: $_\n";
393
394         } else { # it found something
395             if ($follow_file ne '__ignore__') {
396                 local($int_file);
397                 $int_file = $follow_file;
398
399                 if ( $int_file !~ /\.(l?hs|hi|l?y)$/ ) {
400                     local($str) = "";
401                     foreach $obj  (@Obj_suffix) {
402                         $str .= "$bf.$obj ";
403                         foreach $suff (@File_suffix) {
404                            $str .= "$bf.${suff}_$obj ";
405                         }
406                     }
407                     push(@Depend_lines, "$str: $int_file\n");
408                 } else {
409                     $int_file =~ s/\.l?hs$//;
410                     $int_file =~ s/\.l?y$//;
411                     $int_file =~ s/\.hi$//;
412                     local($source_dep);
413
414                     if ( $source ) {
415                         $source_dep = "$int_file.hi-boot";
416                     } else {
417                         local($str)="";
418                         foreach $obj (@Obj_suffix) {
419                            $str .= "$bf.$obj ";
420                         }
421                         push(@Depend_lines, "$str: $int_file.hi\n");
422                     }
423
424                     if ( ! $source ) {
425                        foreach $suff  (@File_suffix) {
426                            local($str) = "";
427                            foreach $obj (@Obj_suffix) {
428                              $str .= "$bf.${suff}_$obj ";
429                            }
430                            push(@Depend_lines, "$str: $int_file.${suff}_hi\n");
431                        }
432                     } else {
433                        local($str) = "";
434                        foreach $obj  (@Obj_suffix) {
435                            $str .= "$bf.$obj ";
436                            foreach $suff (@File_suffix) {
437                              $str .= "$bf.${suff}_$obj ";
438                            }
439                        }
440                        push(@Depend_lines, "$str: $source_dep\n");
441                    }
442                 }
443             }
444         }
445     }
446     close(SRCFILE) || exit(1);
447 }
448
449 # when we see something, we cache that fact ('y').
450 # also, when we get a miss, we cache that (so we don't try later); ('n')
451 %FileExists = ();
452
453 sub find_in_Import_dirs {
454     local($orig_src_file, $modname, $last_seen_dir, $source) = @_;
455     local($import_dir);
456     local($do_magical_check) = 0;
457     local($name_to_check);
458
459     # do it the old hard way: hop along Import_dir list
460     foreach $import_dir (@Import_dirs) {
461         # handle . magically
462         if ($import_dir eq '.') {
463             # record that we should do a SPECIAL try for a file in last_seen_dir (LAST)
464             $do_magical_check = 1;
465         }
466
467         $name_to_check = "$import_dir/$modname.hi";
468         if ( $FileExists{$name_to_check} ne 'n' ) { # either 'y' or nothing
469             print STDERR "trying $name_to_check...\n" if $Verbose >= 2; # very verbose
470             return($name_to_check) if $FileExists{$name_to_check} eq 'y';
471             if (-f $name_to_check) {
472                 $FileExists{$name_to_check} = 'y';
473                 return($name_to_check) ;
474             } else {
475                 $FileExists{$name_to_check} = 'n';
476             }
477         }
478
479         for $suff ('hs', 'lhs', 'ly', 'y') {
480             $name_to_check = "$import_dir/$modname.$suff";
481             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
482             return($name_to_check) if -f $name_to_check;
483         }
484
485         if ( $source ) {
486             $name_to_check = "$import_dir/$modname.hi-boot";
487             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
488             return($name_to_check) if -f $name_to_check;
489         }               
490     }
491     if ($do_magical_check == 1) {
492         $name_to_check = "$last_seen_dir/$modname.hi";
493
494         if ( $FileExists{$name_to_check} ne 'n' ) { # either 'y' or nothing
495             print STDERR "trying $name_to_check...\n" if $Verbose >= 2; # very verbose
496             return($name_to_check) if $FileExists{$name_to_check} eq 'y';
497             if (-f $name_to_check) {
498                 $FileExists{$name_to_check} = 'y';
499                 return($name_to_check) ;
500             } else {
501                 $FileExists{$name_to_check} = 'n';
502             }
503         }
504
505         for $suff ('lhs', 'hs', 'ly', 'y') {
506             $name_to_check = "$last_seen_dir/$modname.$suff";
507             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
508             return($name_to_check) if -f $name_to_check;
509         }
510     }
511
512     # OK, maybe it's referring to something in a system library
513     #foreach $lib ( @Syslibs ) {
514     #   return('__ignore__') if $LibIfaces{"$lib:$modname"};
515     #}
516
517     # Last hope: referring to a Prelude interface
518     return('__ignore__') if ( $IgnoreMe{$modname} eq 'y' );
519
520     die "No file `$modname.hi', `$modname.lhs', `$modname.hs' (reqd from file `$orig_src_file')\namong import directories:\n\t$Import_dirs\n";
521 }
522
523 sub find_in_Include_dirs {
524     local($orig_src_file, $name, $last_seen_dir) = @_;
525     local($include_dir);
526     local($do_magical_check) = 0;
527
528     # no funny name guessing here
529
530     # hop along Include_dir list
531     foreach $include_dir (@Include_dirs) {
532         $include_dir =~ s/^-I//;
533
534         # handle . magically
535         if ($include_dir eq '.') {
536             # record that we should do a SPECIAL try for a file in last_seen_dir (LAST)
537             $do_magical_check = 1;
538         }
539         print STDERR "trying $include_dir/$name...\n" if $Verbose >= 2; # very verbose
540         if (-f "$include_dir/$name") {
541             return("$include_dir/$name");
542         }
543     }
544     if ($do_magical_check == 1) {
545         print STDERR "trying $last_seen_dir/$name...\n" if $Verbose >= 2; # very verbose
546         if (-f "$last_seen_dir/$name") {
547             return("$last_seen_dir/$name");
548         }
549     }
550     die "No file `$name' (reqd from file `$orig_src_file') among include directories: $Include_dirs\n";
551 }
552
553 # out of the driver, actually
554 sub run_something {
555     local($str_to_do, $tidy_name) = @_;
556
557     print STDERR "\n$tidy_name:\n\t" if $Verbose;
558     print STDERR "$str_to_do\n" if $Verbose;
559
560     local($return_val) = system($str_to_do) >> 8;
561
562     if ($return_val != 0) {
563         local($die_msg) = "$Pgm: execution of the $tidy_name had trouble";
564         $die_msg .= " (program not found)" if $return_val == 255;
565         $die_msg .= " ($!)" if $Verbose && $! != 0;
566         $die_msg .= "\n";
567         print STDERR $die_msg;
568         exit $return_val;
569     }
570 }