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