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