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