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