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