[project @ 1997-03-24 04:27:16 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 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     -fhaskell1.[2-9] Deal with the oddities associated with a
31                 particular version of Haskell 1.
32
33 mkdependHS-specific options (not between --'s):
34
35     -v          Be verbose.
36     -v -v       Be very verbose.
37     -f blah     Use "blah" as the makefile, rather than "makefile"
38                 or "Makefile".
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-module=<file> 
53                 Regard <file> as not "stable"; i.e., generate dependencies
54                 on it (if any). This option is normally used in conjunction 
55                 with the --exclude-directory option.
56
57 EOUSAGE
58
59 $Status  = 0; # just used for exit() status
60 $Verbose = 0; # 1 => verbose, 2 => very verbose
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 "hscpp: 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 $InstHsLibDirGhc = "${libdir}/hslibs";
93 $InstDataDirGhc  = "${datadir}";
94
95 $Unlit = ($INSTALLING) ? "${InstLibDirGhc}/unlit" : "${TopPwd}/ghc/utils/unlit/unlit";
96
97 $Begin_magic_str = "# DO NOT DELETE: Beginning of Haskell dependencies\n";
98 $End_magic_str = "# DO NOT DELETE: End of Haskell dependencies\n";
99 $Obj_suffix = 'o';
100 $ghc_version_info = int ( ${PROJECTVERSION} * 100 );
101
102 $Import_dirs = '.';
103 %Syslibs = ();
104 %LibIfaces  = ();  # known prelude/syslib ifaces; read from a file
105
106 %IgnoreMe = ();
107 # directories to considered stable.
108 @Ignore_dirs = ($INSTALLING) ? 
109                    ("$InstLibDirGhc/imports")
110                  : ("$TopPwd/ghc/lib/ghc",
111                     "$TopPwd/ghc/lib/required",
112                     "$TopPwd/ghc/lib/glaExts",
113                     "$TopPwd/ghc/lib/concurrent");
114
115 $Haskell_1 = 3; # assume Haskell 1.3. Changed by -fhaskell-1.?
116 $Include_dirs = '-I.';
117 $Makefile = '';
118 @Src_files = ();
119
120 &mangle_command_line_args();
121
122 # set up array of ignored modules
123 foreach $lib ( @Syslibs ) {
124     local($dir) = 
125       ($INSTALLING) ? "${InstHsLibDirGhc}/${lib}/imports" 
126                     : "${TopPwd}/hslibs/${lib}/src";
127     push(@Ignore_dirs,$dir);
128 }
129
130 if ( $Status ) {
131     print stderr $Usage;
132     exit(1);
133 }
134
135 push(@Defines,
136      ("-D__HASKELL1__=$Haskell_1",
137       "-D__GLASGOW_HASKELL__=$ghc_version_info"));
138
139 @Import_dirs  = split(/:/,$Import_dirs);
140 @Include_dirs = split(/\s+/,$Include_dirs); # still has -I's in it
141 # NB: We keep the scalar-variable equivalents to use in error messages
142
143 if ( ! $Makefile && -f 'makefile' ) {
144     $Makefile = 'makefile';
145 } elsif ( ! $Makefile && -f 'Makefile') {
146     $Makefile = 'Makefile';
147 } elsif ( ! $Makefile) {
148     die "$Pgm: no makefile or Makefile found\n";
149 }
150
151 print STDERR "CPP defines=@Defines\n" if $Verbose;
152 print STDERR "Import_dirs=@Import_dirs\n" if $Verbose;
153 print STDERR "Include_dirs=@Include_dirs\n" if $Verbose;
154
155 &preprocess_import_dirs();
156
157 @Depend_lines = ();
158
159 foreach $sf (@Src_files) {
160     # just like lit-inputter
161     # except it puts each file through CPP and
162     # a de-commenter (not implemented);
163     # builds up @Depend_lines
164     print STDERR "Here we go for source file: $sf\n" if $Verbose;
165     ($bf = $sf) =~ s/\.l?(hs|y)$//;
166     #push(@Depend_lines, "$bf.$Obj_suffix $bf.hi : $sf\n");
167     push(@Depend_lines, "$bf.$Obj_suffix : $sf\n");
168     foreach $suff (@File_suffix) {
169         push(@Depend_lines, "$bf.${suff}_$Obj_suffix : $sf\n");
170     }
171
172     # if it's a literate file, .lhs or .ly? (happy specs), then we de-literatize it: 
173     if ( $sf !~ /\.l(hs|y)$/ ) {
174         $file_to_read = $sf;
175     } else {
176         $file_to_read = "$Tmp_prefix.hs";
177         local($to_do) = "$Unlit $sf $file_to_read";
178         &run_something($to_do, 'unlit');
179     }
180     &slurp_file_for_imports($file_to_read, $sf);
181
182     if ( $sf =~ /\.l(hs|y)$/ ) {
183         unlink "$Tmp_prefix.hs";
184     }
185 }
186
187 # OK, mangle the Makefile
188 unlink("$Makefile.bak");
189
190 #
191 # If no output file exist as yet, create one.
192
193 if ( ! -f $Makefile.bak ) {
194    system("touch $Makefile.bak");
195
196 if ( -f $Makefile ) {
197    rename($Makefile,"$Makefile.bak");
198 }
199 # now copy Makefile.bak into Makefile, rm'ing old dependencies
200 # and adding the new
201 open(OMKF,"< $Makefile.bak") || die "$Pgm: can't open $Makefile.bak: $!\n";
202 open(NMKF,"> $Makefile") || die "$Pgm: can't open $Makefile: $!\n";
203 select(NMKF);
204 $_ = <OMKF>;
205 while ($_ && $_ ne $Begin_magic_str) { # copy through, 'til Begin_magic_str
206     print $_;
207     $_ = <OMKF>;
208 }
209 while ($_ && $_ ne $End_magic_str) { # delete 'til End_magic_str
210     $_ = <OMKF>;
211 }
212 # insert dependencies
213 print $Begin_magic_str;
214 print @Depend_lines;
215 print $End_magic_str;
216 while (<OMKF>) { # copy the rest through
217     print $_;
218 }
219 close(NMKF) || exit(1);
220 close(OMKF) || exit(1);
221 exit 0;
222
223 sub mangle_command_line_args {
224     while($_ = $ARGV[0]) {
225         shift(@ARGV);
226
227         if ( /^--$/ ) {
228             $Dashdashes_seen++;
229
230         } elsif ( /^-D(.*)/ ) { # recognized wherever they occur
231             push(@Defines, $_);
232         } elsif ( /^-i(.*)/ ) {
233             $Import_dirs .= ":$1";
234         } elsif ( /^-I/ ) {
235             $Include_dirs .= " $_";
236         } elsif ( /^-syslib$/ ) {
237             push(@Syslibs, &grab_arg_arg($_,''));
238         } elsif ( /^-fhaskell-1\.([2-9])/ ) {
239             $Haskell_1 = $1;
240         } elsif ($Dashdashes_seen != 1) { # not between -- ... --
241             if ( /^-v$/ ) {
242                 $Verbose++;
243             } elsif ( /^-f(.*)/ ) {
244                 $Makefile       = &grab_arg_arg('-f',$1);
245             } elsif ( /^-o(.*)/ ) {
246                 $Obj_suffix     = &grab_arg_arg('-o',$1);
247             #
248             # --exclude-module=mod => it's stable, trust me!
249             
250             } elsif ( /^-(x|-exclude-module=)(.*)/ ) { 
251                 local($thing) = &grab_arg_arg($1,$2);
252                 $IgnoreMe{$thing} = 'y';
253             } elsif ( /^-(X|-exclude-directory=)(.*)/ ) { 
254                 foreach $d ( split(/:/,&grab_arg_arg($1, $2)) ) {
255                    push(@Ignore_dirs,"$d");
256                 }
257             } elsif ( /^--include-module=(.*)/ ) { 
258                 local($thing) = &grab_arg_arg($1,$2);
259                 $IgnoreMe{$thing} = 'n';
260             } elsif ( /^-s(.*)/ ) {
261                 local($suff)    =  &grab_arg_arg('-s',$1);
262                 push(@File_suffix, $suff);
263             } elsif ( /^-/ ) {
264                 print STDERR "$Pgm: unknown option ignored: $_\n";
265                 $Status++;
266             } else {
267                 push(@Src_files, $_);
268             }
269
270         } elsif ($Dashdashes_seen == 1) { # where we ignore unknown options
271             push(@Src_files, $_) if ! /^-/;
272         }
273     }
274     @File_suffix = sort (@File_suffix);
275 }
276
277 sub grab_arg_arg {
278     local($option, $rest_of_arg) = @_;
279     
280     if ($rest_of_arg) {
281         return($rest_of_arg);
282     } elsif ($#ARGV >= 0) {
283         local($temp) = $ARGV[0]; shift(@ARGV); 
284         return($temp);
285     } else {
286         print STDERR "$Pgm: no argument following $option option\n";
287         $Status++;
288     }
289 }
290
291 sub preprocess_import_dirs {
292     # it's probably cheaper to find out what's in all
293     # the @Import_dirs before we start processing.
294     local($d, $thing);
295     local($_);
296     %ModuleIn = ();
297
298     foreach $d ( @Import_dirs ) {
299         # Check to see if it can be ignored
300         #print STDERR "Ignore imports from $d\n" if $Verbose && $Ignore_dirs{$d};
301         #next if $Ignore_dirs{$d};
302
303         opendir(DIR, $d) || die "$Pgm: can't open directory $d\n";
304
305         for ($_ = readdir(DIR); $_; $_ = readdir(DIR)) {
306             next unless /(.*)\.hi$/;
307             $thing = $1;
308             if ($ModuleIn{$thing} && $ModuleIn{$thing} ne $d) {
309                 print STDERR "$Pgm: warning: $thing.hi appears in both $ModuleIn{$thing} and $d!\n";
310             } else {
311                 $ModuleIn{$thing} = $d;
312             }
313         }
314         closedir(DIR); # No, don't check the error code
315     }
316
317     # Add all the modules
318     # to the IgnoreMe array before we start scanning for imports.
319     foreach $d (@Ignore_dirs) {
320
321         opendir(DIR, $d) || die "$Pgm: can't open directory $d\n";
322
323         for ($_ = readdir(DIR); $_; $_ = readdir(DIR)) {
324             next unless /(.*)\.(hi|l?hs|l?y)$/;
325             #don't tag it twice or overwrite it with a diff. value
326             next if $IgnoreMe{$1};
327             print STDERR "Module $d/$1.$2 will be ignored\n" if $Verbose;
328
329             $IgnoreMe{$1} = 'y';
330         }
331         closedir(DIR); # No, don't check the error code
332     }
333 }
334
335 sub slurp_file_for_imports {
336     local($file_to_read, $orig_src_file) = @_;
337     local($follow_file);
338
339     local($last_seen_dir) = $orig_src_file;
340     $last_seen_dir =~ s/\/[^\/]+$//; # strip to dir name
341     $last_seen_dir = '.' if ($last_seen_dir eq $orig_src_file);
342
343     # we mangle #include's so they will also leave something
344     # behind to indicate the dependency on _them_
345     
346     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;
347
348     open(SRCFILE, "${SED} -e '/^# *include/{p;s/^# *include/!include/;};s/'\\''//g;s/\"//g' $file_to_read | $Cpp $Include_dirs -I$last_seen_dir @Defines |")
349         || die "$Pgm: Can't open $file_to_read: $!\n";
350
351     while (<SRCFILE>) {
352         #
353         # import {-# SOURCE #-} Foo (bar) generates dependencies on the source file only,
354         # the compiler will deal with the absence of Foo.hi by consulting the
355         # source for Foo directly. (for dealing with recursive modules).
356         #
357         next unless (/^>?\s*(import)(\s+{-#\s*SOURCE\s*#-})?(\s+qualified)?\s+([A-Z][A-Za-z0-9_']*)/ || /^!(include)(\s+)"(\S+)"/);
358         $todo    = $1;
359         $source  = ( $2 ne '') ? 1 : 0;
360         $modname = $4;
361
362         next if $modname eq '';
363         if ($todo eq 'import') {
364             if ( $ModuleIn{$modname} ) {
365                    $follow_file = "$ModuleIn{$modname}/$modname.hi";
366             } else { # hard way
367                 $follow_file
368                   = &find_in_Import_dirs($orig_src_file, $modname, $last_seen_dir );
369             }
370         } else {
371                 $follow_file
372                   = &find_in_Include_dirs($orig_src_file, $modname, $last_seen_dir);
373         }
374
375         if (! $follow_file) { # it didnae find anything
376             die "$orig_src_file: Couldn't handle: $_\n";
377
378         } else { # it found something
379             if ($follow_file ne '__ignore__') {
380                 local($int_file);
381                 $int_file = $follow_file;
382
383                 if ( $int_file !~ /\.(l?hs|hi|l?y)$/ ) {
384                     push(@Depend_lines, "$bf.$Obj_suffix : $int_file\n");
385                     foreach $suff (@File_suffix) {
386                         push(@Depend_lines, "$bf.${suff}_$Obj_suffix : $int_file\n");
387                     }
388
389                 } else {
390                     $int_file =~ s/\.l?hs$//;
391                     $int_file =~ s/\.l?y$//;
392                     $int_file =~ s/\.hi$//;
393                     local($source_dep);
394
395                     if ( $source && -f "$int_file.hs" ) {
396                         $source_dep = "$int_file.hs";
397                         push(@Depend_lines, "$bf.$Obj_suffix : $source_dep\n");
398                     } elsif ( $source && -f "$int_file.lhs" ) {
399                         $source_dep = "$int_file.lhs";
400                         push(@Depend_lines, "$bf.$Obj_suffix : $source_dep\n");
401                     } elsif ( $source && ( -f "$int_file.ly" || -f "$int_file.y" ) ) {
402                         $source_dep = "$int_file.hs";
403                         push(@Depend_lines, "$bf.$Obj_suffix : $source_dep\n");
404                     } else {
405                         if ( $source ) {
406                            print STDERR "Warning: could not find source file dependency $int_file.(hs|lhs|y|ly)\n";
407                         }
408                         push(@Depend_lines, "$bf.$Obj_suffix : $int_file.hi\n");
409                     }
410
411                     if ( ! $source ) {
412                        foreach $suff (@File_suffix) {
413                           push(@Depend_lines, "$bf.${suff}_$Obj_suffix : $int_file.${suff}_hi\n");
414                        }
415                     } else {
416                        foreach $suff (@File_suffix) {
417                           push(@Depend_lines, "$bf.${suff}_$Obj_suffix : $source_dep\n");
418                        }
419                    }
420                 }
421             }
422         }
423     }
424     close(SRCFILE) || exit(1);
425 }
426
427 # when we see something, we cache that fact ('y').
428 # also, when we get a miss, we cache that (so we don't try later); ('n')
429 %FileExists = ();
430
431 sub find_in_Import_dirs {
432     local($orig_src_file, $modname, $last_seen_dir, $source) = @_;
433     local($import_dir);
434     local($do_magical_check) = 0;
435     local($name_to_check);
436
437     # do it the old hard way: hop along Import_dir list
438     foreach $import_dir (@Import_dirs) {
439         # handle . magically
440         if ($import_dir eq '.') {
441             # record that we should do a SPECIAL try for a file in last_seen_dir (LAST)
442             $do_magical_check = 1;
443         }
444
445         $name_to_check = "$import_dir/$modname.hi";
446         if ( $FileExists{$name_to_check} ne 'n' ) { # either 'y' or nothing
447             print STDERR "trying $name_to_check...\n" if $Verbose >= 2; # very verbose
448             return($name_to_check) if $FileExists{$name_to_check} eq 'y';
449             if (-f $name_to_check) {
450                 $FileExists{$name_to_check} = 'y';
451                 return($name_to_check) ;
452             } else {
453                 $FileExists{$name_to_check} = 'n';
454             }
455         }
456
457         for $suff ('hs', 'lhs', 'ly', 'y') {
458             $name_to_check = "$import_dir/$modname.$suff";
459             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
460             return($name_to_check) if -f $name_to_check;
461         }
462     }
463     if ($do_magical_check == 1) {
464         $name_to_check = "$last_seen_dir/$modname.hi";
465
466         if ( $FileExists{$name_to_check} ne 'n' ) { # either 'y' or nothing
467             print STDERR "trying $name_to_check...\n" if $Verbose >= 2; # very verbose
468             return($name_to_check) if $FileExists{$name_to_check} eq 'y';
469             if (-f $name_to_check) {
470                 $FileExists{$name_to_check} = 'y';
471                 return($name_to_check) ;
472             } else {
473                 $FileExists{$name_to_check} = 'n';
474             }
475         }
476
477         for $suff ('lhs', 'hs', 'ly', 'y') {
478             $name_to_check = "$last_seen_dir/$modname.$suff";
479             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
480             return($name_to_check) if -f $name_to_check;
481         }
482     }
483
484     # OK, maybe it's referring to something in a system library
485     #foreach $lib ( @Syslibs ) {
486     #   return('__ignore__') if $LibIfaces{"$lib:$modname"};
487     #}
488
489     # Last hope: referring to a Prelude interface
490     return('__ignore__') if ( $IgnoreMe{$modname} eq 'y' );
491
492     die "No file `$modname.hi', `$modname.lhs', `$modname.hs' (reqd from file `$orig_src_file')\namong import directories:\n\t$Import_dirs\n";
493 }
494
495 sub find_in_Include_dirs {
496     local($orig_src_file, $name, $last_seen_dir) = @_;
497     local($include_dir);
498     local($do_magical_check) = 0;
499
500     # no funny name guessing here
501
502     # hop along Include_dir list
503     foreach $include_dir (@Include_dirs) {
504         $include_dir =~ s/^-I//;
505
506         # handle . magically
507         if ($include_dir eq '.') {
508             # record that we should do a SPECIAL try for a file in last_seen_dir (LAST)
509             $do_magical_check = 1;
510         }
511         print STDERR "trying $include_dir/$name...\n" if $Verbose >= 2; # very verbose
512         if (-f "$include_dir/$name") {
513             return("$include_dir/$name");
514         }
515     }
516     if ($do_magical_check == 1) {
517         print STDERR "trying $last_seen_dir/$name...\n" if $Verbose >= 2; # very verbose
518         if (-f "$last_seen_dir/$name") {
519             return("$last_seen_dir/$name");
520         }
521     }
522     die "No file `$name' (reqd from file `$orig_src_file') among include directories: $Include_dirs\n";
523 }
524
525 # out of the driver, actually
526 sub run_something {
527     local($str_to_do, $tidy_name) = @_;
528
529     print STDERR "\n$tidy_name:\n\t" if $Verbose;
530     print STDERR "$str_to_do\n" if $Verbose;
531
532     local($return_val) = system($str_to_do) >> 8;
533
534     if ($return_val != 0) {
535         local($die_msg) = "$Pgm: execution of the $tidy_name had trouble";
536         $die_msg .= " (program not found)" if $return_val == 255;
537         $die_msg .= " ($!)" if $Verbose && $! != 0;
538         $die_msg .= "\n";
539         print STDERR $die_msg;
540         exit $return_val;
541     }
542 }