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