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