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