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