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