5e05bac71d5c05837f1fe7309743d001c66167e7
[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 HscIfaceFileVersion
5 #  libdir libexecdir datadir INSTALLING
6 #  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 $HiBootVersion = $HscIfaceFileVersion;
88 $hi_boot_with_version = 0;
89
90 $Begin_magic_str = "# DO NOT DELETE: Beginning of Haskell dependencies\n";
91 $End_magic_str = "# DO NOT DELETE: End of Haskell dependencies\n";
92 @Obj_suffix =  ("o");
93 @File_suffix = ();
94
95 $Import_dirs = '.';
96 %Syslibs = ();
97 %LibIfaces  = ();  # known prelude/syslib ifaces; read from a file
98 %IgnoreMe = ();
99 # directories to considered stable.
100 @Ignore_dirs = ();
101
102 %ModuleIn = ();
103
104 $Include_dirs = '-I.';
105 $Makefile = '';
106 @Src_files = ();
107 $Include_prelude = 0;
108 @Defines = ();
109 $ProcessingOptions=0;
110
111 # Delete temp. file if script is halted.
112 sub quit_upon_signal { print STDERR "Deleting $Tmp_prefix.hs .. \n"; unlink "$Tmp_prefix.hs"; }
113 $SIG{'INT'}  = 'quit_upon_signal';
114 $SIG{'QUIT'} = 'quit_upon_signal';
115
116 &mangle_command_line_args(@ARGV);
117
118 if ( $Status ) {
119     print stderr $Usage;
120     exit(1);
121 }
122
123 @Import_dirs  = split(/:/,$Import_dirs);
124 @Include_dirs = split(/\s+/,$Include_dirs); # still has -I's in it
125
126 # NB: We keep the scalar-variable equivalents to use in error messages
127
128 &gather_import_dirs();
129
130 if ( ! $Makefile && -f 'makefile' ) {
131     $Makefile = 'makefile';
132 } elsif ( ! $Makefile && -f 'Makefile') {
133     $Makefile = 'Makefile';
134 } elsif ( ! $Makefile) {
135     die "$Pgm: no makefile or Makefile found\n";
136 }
137
138 print STDERR "CPP defines=@Defines\n" if $Verbose;
139 print STDERR "Import_dirs=@Import_dirs\n" if $Verbose;
140 print STDERR "Include_dirs=@Include_dirs\n" if $Verbose;
141
142 &preprocess_import_dirs();
143
144 @Depend_lines = ();
145
146 foreach $sf (@Src_files) {
147
148     # just like lit-inputter
149     # except it puts each file through CPP and
150     # a de-commenter (not implemented);
151     # builds up @Depend_lines
152     print STDERR "Here we go for source file: $sf\n" if $Verbose;
153     ($bf = $sf) =~ s/\.l?(hs|y)$//;
154
155     local($str)="";
156     foreach $obj  (@Obj_suffix) {
157         $str .= "$bf.$obj ";
158         foreach $suff (@File_suffix) {
159            $str .= "$bf.${suff}_$obj ";
160         }
161     }
162     push(@Depend_lines, "$str: $sf\n");
163     # if it's a literate file, .lhs or .ly? (happy specs), then we de-literatize it: 
164     if ( $sf !~ /\.l(hs|y)$/ ) {
165         $file_to_read = $sf;
166     } else {
167         $file_to_read = "$Tmp_prefix.hs";
168         local($to_do) = "$Unlit $sf $file_to_read";
169         &run_something($to_do, $sf, 'unlit');
170     }
171     &slurp_file_for_imports($file_to_read, $sf);
172
173     # Delete the temporary.
174     if ( $sf =~ /\.l(hs|y)$/ ) {
175         unlink "$Tmp_prefix.hs";
176     }
177 }
178
179
180 #
181 # Create backup version of output file.
182
183 if ( ! -f $Makefile ) {
184    # truncate() may not be implemented, so we
185    # play it safe here.
186    local(*TRUNC);
187    open(TRUNC,"> $Makefile.bak") && close(TRUNC);
188 } else {
189    rename($Makefile,"$Makefile.bak");
190 }
191 # now copy Makefile.bak into Makefile, rm'ing old dependencies
192 # and adding the new
193 open(OMKF,"< $Makefile.bak") || die "$Pgm: can't open $Makefile.bak: $!\n";
194 open(NMKF,"> $Makefile") || die "$Pgm: can't open $Makefile: $!\n";
195 select(NMKF);
196 $_ = <OMKF>;
197 while ($_ && $_ ne $Begin_magic_str) { # copy through, 'til Begin_magic_str
198     print $_;
199     $_ = <OMKF>;
200 }
201 while ($_ && $_ ne $End_magic_str) { # delete 'til End_magic_str
202     $_ = <OMKF>;
203 }
204 # insert dependencies
205 print "$Begin_magic_str", @Depend_lines, $End_magic_str || die "Failed to write out dependencies ($!)";
206
207 while (<OMKF>) { # copy the rest through
208     print $_ || die "Failed to write out dependencies ($!)";
209 }
210 close(NMKF) || exit(1);
211 close(OMKF) || exit(1);
212 exit 0;
213
214 sub mangle_command_line_args {
215     local(@Args) = @_;
216         
217     while($_ = $Args[0]) {
218         shift(@Args);
219
220         if ( /^--$/ ) {
221             $Dashdashes_seen++;
222
223         } elsif ( /^-D(.*)/ ) { # recognized wherever they occur
224             push(@Defines, $_);
225         } elsif ( /^-cpp$/ ) { # recognized wherever they occur
226             $Cpp_flag_set =1; 
227         } elsif ( /^-i$/ ) {
228             $Import_dirs = ''; # import path cleared!
229         } elsif ( /^-i(.*)/ ) {
230             $Import_dirs = "$1:$Import_dirs";
231         } elsif ( /^-I/ ) {
232             $Include_dirs .= " $_";
233         } elsif ( /^-syslib$/ ) {
234             push(@Syslibs, &grab_arg_arg(*Args,$_,''));
235         } elsif ( /^-fglasgow-exts$/ ) {
236             push(@Syslibs, 'lang');
237         } elsif ( /^-concurrent$/ ) {
238             push(@Syslibs, 'concurrent');
239         } elsif (/^-#include(.*)/) {
240             &grab_arg_arg(*Args,$_,'');
241         } elsif ($Dashdashes_seen != 1) { # not between -- ... --
242             if ( /^-v$/ ) {
243                 $Verbose++;
244             } elsif ( /^-w$/ ) {
245                 $Warnings     = 0;
246             } elsif ( /^-f(.*)/ && !$ProcessingOptions ) {
247                 $Makefile       = &grab_arg_arg(*Args,'-f',$1);
248             } elsif ( /^-o(.*)/ ) {
249                 local($suff)    = &grab_arg_arg(*Args,'-o',$1);
250                 # Weed out existing entry .. there must be a better way of doing this
251                 # with arrays (non-assoc) ! -- sof
252                 @Obj_suffix     = grep(!/$suff/,@Obj_suffix);
253                 push(@Obj_suffix, $suff);
254             #
255             # --exclude-module=mod => it's stable, trust me!
256             
257             } elsif ( /^-(x|-exclude-module=)(.*)/ ) { 
258                 local($thing) = &grab_arg_arg(*Args,$1,$2);
259                 $IgnoreMe{$thing} = 'Y';
260             } elsif ( /^-(X|-exclude-directory=)(.*)/ ) { 
261                 foreach $d ( split(/:/,&grab_arg_arg(*Args,$1, $2)) ) {
262                    push(@Ignore_dirs,"$d");
263                 }
264             } elsif ( /^--include-module=(.*)/ ) { 
265                 local($thing) = &grab_arg_arg(*Args,$1,$2);
266                 $IgnoreMe{$thing} = 'n';
267             } elsif ( /^--include-prelude$/ ) { 
268                 $Include_prelude = 1;
269             } elsif ( /^-s(.*)/ ) {
270                 local($suff)    =  &grab_arg_arg(*Args,'-s',$1);
271                 push(@File_suffix, $suff);
272             } elsif ( /^-/ ) {
273                 if (!$ProcessingOptions) {
274                    print STDERR "$Pgm: unknown option ignored: $_\n";
275                    $Status++;
276                 }
277             } else {
278                 push(@Src_files, $_);
279             }
280         }
281         # Removed support for picking up plausible source file 
282         # names inside the ghc options chunk of the command
283         # line. It failed to deal with `option-value' stuff present
284         # on some invocations of ghc (e.g., "-ohi foo.baz").
285         #  -- sof 12/97
286         #
287         # } elsif ($Dashdashes_seen == 1) {
288         #     push(@Src_files, $_) if ! /^-/;
289         # }
290     }
291     @File_suffix = sort (@File_suffix);
292 }
293
294 sub grab_arg_arg {
295     local(*Args, $option, $rest_of_arg) = @_;
296     
297     if ($rest_of_arg) {
298         return($rest_of_arg);
299     } elsif ($#Args >= 0) {
300         local($temp) = $Args[0]; shift(@Args); 
301         return($temp);
302     } else {
303         print STDERR "$Pgm: no argument following $option option\n";
304         $Status++;
305     }
306 }
307
308 sub gather_import_dirs {
309
310         # set up array of ignored modules
311         local(@dirs) = ($INSTALLING) ? 
312                        ("$InstLibDirGhc/imports/std")
313                      : ("$TopPwd/ghc/lib/std");
314
315         if (!$Include_prelude) {
316            push(@Ignore_dirs, @dirs);
317         } else {
318            push(@Import_dirs, @dirs);
319         }
320
321         foreach $lib ( @Syslibs ) {
322            local($dir);
323
324            # Yuck ^ 2
325            if ( $lib eq 'lang' && ! $INSTALLING ) {
326               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/monads");
327            }
328            if ( $lib eq 'text' && ! $INSTALLING ) {
329               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/html");
330               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/haxml/lib");
331            }
332            if ( $lib eq 'data' && ! $INSTALLING ) {
333               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/edison");
334               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/edison/Assoc");
335               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/edison/Coll");
336               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/edison/Seq");
337            }
338            if ( $lib eq 'util' && ! $INSTALLING ) {
339               push(@Import_dirs, "${TopPwd}/hslibs/${lib}/check");
340            }
341
342            # Yuck ^ 3
343            if ( $lib eq 'win32' && ! $INSTALLING ) {
344               $dir = "${TopPwd}/hslibs/${lib}/src";
345            } elsif ( $lib eq 'com' && ! $INSTALLING ) {
346               $dir = "${TopPwd}/hdirect/lib";
347            } else {
348               $dir = ($INSTALLING) ? "${InstLibDirGhc}/imports/${lib}" 
349                                    : "${TopPwd}/hslibs/${lib}";
350            }
351            if (!$Include_prelude) {
352               push(@Ignore_dirs,$dir);
353            } else {
354               push(@Import_dirs, $dir);
355            }
356         }
357 }
358
359
360
361 sub preprocess_import_dirs {
362     # it's probably cheaper to find out what's in all
363     # the @Import_dirs before we start processing.
364     local($d, $thing);
365     local($_);
366
367     foreach $d ( @Import_dirs ) {
368         # Check to see if it can be ignored
369         #print STDERR "Ignore imports from $d\n" if $Verbose && $Ignore_dirs{$d};
370         #next if $Ignore_dirs{$d};
371
372         opendir(DIR, $d) || die "$Pgm: can't open directory $d\n";
373
374         for ($_ = readdir(DIR); $_; $_ = readdir(DIR)) {
375             next unless /(.*)\.hi$/;
376             $thing = $1;
377             # 
378             # dLL_ifs.hi is used to indicate whether a directory
379             # contains interface files whose object codes reside in a Win32 DLL.
380             # 
381             if ($ModuleIn{$thing} && $ModuleIn{$thing} ne $d && $thing ne 'dLL_ifs') {
382                 print STDERR "$Pgm: warning: $thing.hi appears in both $ModuleIn{$thing} and $d!\n" if ($Warnings);
383             } else {
384                 $ModuleIn{$thing} = $d;
385             }
386         }
387         closedir(DIR); # No, don't check the error code
388     }
389
390     # Add all the modules
391     # to the IgnoreMe array before we start scanning for imports.
392     foreach $d (@Ignore_dirs) {
393
394         opendir(DIR, $d) || die "$Pgm: can't open directory $d\n";
395
396         for ($_ = readdir(DIR); $_; $_ = readdir(DIR)) {
397             next unless /(.*)\.(hi|l?hs|l?y)$/;
398             #don't tag it twice or overwrite it with a diff. value
399             next if $IgnoreMe{$1};
400             print STDERR "Module $d will be ignored\n" if $Verbose;
401
402             $IgnoreMe{$1} = 'y';
403         }
404         closedir(DIR); # No, don't check the error code
405     }
406 }
407
408 sub slurp_file_for_imports {
409     local($file_to_read, $orig_src_file) = @_;
410     local($follow_file,$read_from_file);
411     local($cleanup)=0;
412
413     local(@Old_Syslibs, $options);
414     local(@Old_Ignore_dirs);
415     local($found_options)=0;
416
417     local($last_seen_dir) = $orig_src_file;
418     $last_seen_dir =~ s/\/[^\/]+$//; # strip to dir name
419     $last_seen_dir = '.' if ($last_seen_dir eq $orig_src_file);
420
421     local($mod_name) = $orig_src_file;
422
423     $mod_name =~ s/.*\/([^\/]+)$/$1/g;
424     $mod_name =~ s/^([^.]+)\.(.*)$/$1/;
425
426     print STDERR "Warning: processing module $mod_name, which I was supposed to ignore.\n"
427         if ( $IgnoreMe{$mod_name} eq 'Y' && $Warnings );
428
429     &process_dependency('import',0,'Prelude') if ($Include_prelude);
430
431     #
432     # Check for {-# OPTIONS in the file-to-be-processed. If any syslib related options
433     # *only* are found, add them to the module search list (and take them off once
434     # we're through with this module.)
435     #
436
437     $options = &check_for_source_options($file_to_read);
438     if ($options ne "") {
439       @Old_Syslibs=@Syslibs;
440       $ProcessingOptions=1;
441       &mangle_command_line_args(split(/\s+/,$options));
442       if (@Old_Syslibs ne @Syslibs) {
443         $found_options=1;
444         @Old_Ignore_dirs = @Ignore_dirs;
445         &gather_import_dirs();
446         &preprocess_import_dirs();
447       }
448     }
449     
450     # we mangle #include's so they will also leave something
451     # behind to indicate the dependency on _them_
452     
453     local ($open_cmd);
454     if ($Cpp_flag_set) {
455        &run_something("${SED} -e '/^# *include/{p;s/^# *include/!include/;}' $file_to_read | $Cpp $Include_dirs -I$last_seen_dir @Defines - 2>&1 > ${file_to_read}.i", $orig_src_file, 'cpp');
456        $read_from_file="${file_to_read}.i";
457        $cleanup=1;
458     } else {
459        $read_from_file="${file_to_read}";
460        $open_cmd = $file_to_read;
461     }
462     print STDERR "$open_cmd\n" if $Verbose;
463
464     open(SRCFILE, $read_from_file) || die "$Pgm: Can't open $file_to_read: $!\n";
465
466     while (<SRCFILE>) {
467         #
468         # import {-# SOURCE #-} Foo (bar) generates dependencies on the source file only,
469         # the compiler will deal with the absence of Foo.hi by consulting the
470         # source for Foo directly. (for dealing with recursive modules).
471         #
472         next unless (/^>?\s*(import)(\s+{-#\s*SOURCE\s*#-})?(\s+qualified)?\s+([A-Z][A-Za-z0-9_']*)/ || /^!(include)(\s+)"(\S+)"/);
473         $todo    = $1;
474         $source  = ( $2 ne '') ? 1 : 0;
475         $modname = $4;
476
477         next if $modname eq '';
478         &process_dependency($todo,$source,$modname);
479     }
480
481     if ($found_options) {
482       @Ignore_dirs = @Old_Ignore_dirs;
483     }
484
485     close(SRCFILE) || exit(1);
486     # remove temporary file, if any.
487     if ($cleanup) {
488            unlink("$read_from_file");
489     }
490 }
491
492 #
493 # Handle
494 sub process_dependency {
495   local($todo,$source,$modname) = @_;
496
497   if ($todo eq 'import') {
498     if ( $IgnoreMe{$modname} eq 'Y' ) {
499          # user specifically asked for this module
500          # to be ignored.
501          $follow_file = '__ignore__';
502     } elsif ( $ModuleIn{$modname} ) {
503         $follow_file = "$ModuleIn{$modname}/$modname.hi";
504     } else { # hard way
505         $follow_file =
506           &find_in_Import_dirs($orig_src_file, $modname, $last_seen_dir, $source );
507     }
508   } else {
509         $follow_file
510           = &find_in_Include_dirs($orig_src_file, $modname, $last_seen_dir);
511   }
512
513   if (! $follow_file) { # it didnae find anything
514       die "$orig_src_file: Couldn't handle: $_\n";
515
516   } else { # it found something
517     if ($follow_file ne '__ignore__') {
518         local($int_file) = $follow_file;
519
520         if ( $int_file !~ /\.(l?hs|hi|l?y)$/ ) {
521             local($str) = "";
522             foreach $obj  (@Obj_suffix) {
523                 $str .= "$bf.$obj ";
524                 foreach $suff (@File_suffix) {
525                    $str .= "$bf.${suff}_$obj ";
526                 }
527             }
528             push(@Depend_lines, "$str: $int_file\n");
529         } else {
530             $int_file =~ s/\.l?hs$//;
531             $int_file =~ s/\.l?y$//;
532             $int_file =~ s/\.hi$//;
533             local($source_dep);
534
535             if ( $source ) {
536                 # if a version specific .hi-boot file exist, use it.
537                 if ( -f "$int_file.hi-boot-${HiBootVersion}" ) {
538                    $source_dep = "$int_file.hi-boot-${HiBootVersion}";
539                 } else {
540                    $source_dep = "$int_file.hi-boot";
541                 }
542             } else {
543                 local($str)="";
544                 foreach $obj (@Obj_suffix) {
545                    $str .= "$bf.$obj ";
546                 }
547                 push(@Depend_lines, "$str: $int_file.hi\n");
548             }
549
550             if ( ! $source ) {
551                foreach $suff  (@File_suffix) {
552                   local($str) = "";
553                   foreach $obj (@Obj_suffix) {
554                     $str .= "$bf.${suff}_$obj ";
555                   }
556                   push(@Depend_lines, "$str: $int_file.${suff}_hi\n");
557                }
558             } else {
559                local($str) = "";
560                foreach $obj  (@Obj_suffix) {
561                    $str .= "$bf.$obj ";
562                    foreach $suff (@File_suffix) {
563                      $str .= "$bf.${suff}_$obj ";
564                    }
565                }
566                push(@Depend_lines, "$str: $source_dep\n");
567             }
568         }
569      }
570    }
571 }
572
573 # when we see something, we cache that fact ('y').
574 # also, when we get a miss, we cache that (so we don't try later); ('n')
575 %FileExists = ();
576
577 sub find_in_Import_dirs {
578     local($orig_src_file, $modname, $last_seen_dir, $source) = @_;
579     local($import_dir);
580     local($do_magical_check) = 0;
581     local($name_to_check);
582
583     # do it the old hard way: hop along Import_dir list
584     foreach $import_dir (@Import_dirs) {
585         # handle . magically
586         if ($import_dir eq '.') {
587             # record that we should do a SPECIAL try for a file in last_seen_dir (LAST)
588             $do_magical_check = 1;
589         }
590
591         $name_to_check = "$import_dir/$modname.hi";
592         if ( $FileExists{$name_to_check} ne 'n' ) { # either 'y' or nothing
593             print STDERR "trying $name_to_check...\n" if $Verbose >= 2; # very verbose
594             return($name_to_check) if $FileExists{$name_to_check} eq 'y';
595             if (-f $name_to_check) {
596                 $FileExists{$name_to_check} = 'y';
597                 return($name_to_check) ;
598             } else {
599                 $FileExists{$name_to_check} = 'n';
600             }
601         }
602
603         for $suff ('hs', 'lhs', 'ly', 'y') {
604             $name_to_check = "$import_dir/$modname.$suff";
605             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
606             return($name_to_check) if -f $name_to_check;
607         }
608
609         if ( $source ) {
610             $name_to_check = "$import_dir/$modname.hi-boot-${HiBootVersion}";
611             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
612             return($name_to_check) if -f $name_to_check;
613
614             $name_to_check = "$import_dir/$modname.hi-boot";
615             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
616             return($name_to_check) if -f $name_to_check;
617         }               
618     }
619     if ($do_magical_check == 1) {
620         $name_to_check = "$last_seen_dir/$modname.hi";
621
622         if ( $FileExists{$name_to_check} ne 'n' ) { # either 'y' or nothing
623             print STDERR "trying $name_to_check...\n" if $Verbose >= 2; # very verbose
624             return($name_to_check) if $FileExists{$name_to_check} eq 'y';
625             if (-f $name_to_check) {
626                 $FileExists{$name_to_check} = 'y';
627                 return($name_to_check) ;
628             } else {
629                 $FileExists{$name_to_check} = 'n';
630             }
631         }
632
633         for $suff ('lhs', 'hs', 'ly', 'y') {
634             $name_to_check = "$last_seen_dir/$modname.$suff";
635             print STDERR "trying... $name_to_check\n" if $Verbose >= 2; # very verbose
636             return($name_to_check) if -f $name_to_check;
637         }
638     }
639
640     # OK, maybe it's referring to something in a system library
641     #foreach $lib ( @Syslibs ) {
642     #   return('__ignore__') if $LibIfaces{"$lib:$modname"};
643     #}
644
645     # Last hope: referring to a Prelude interface
646     return('__ignore__') if ( $IgnoreMe{$modname} eq 'y' );
647
648     die "No file `$modname.hi', `$modname.lhs', `$modname.hs' (reqd from file `$orig_src_file')\namong import directories:\n\t$Import_dirs\n";
649 }
650
651 sub find_in_Include_dirs {
652     local($orig_src_file, $name, $last_seen_dir) = @_;
653     local($include_dir);
654     local($do_magical_check) = 0;
655
656     # no funny name guessing here
657
658     # hop along Include_dir list
659     foreach $include_dir (@Include_dirs) {
660         $include_dir =~ s/^-I//;
661
662         # handle . magically
663         if ($include_dir eq '.') {
664             # record that we should do a SPECIAL try for a file in last_seen_dir (LAST)
665             $do_magical_check = 1;
666         }
667         print STDERR "trying $include_dir/$name...\n" if $Verbose >= 2; # very verbose
668         if (-f "$include_dir/$name") {
669             return("$include_dir/$name");
670         }
671     }
672     if ($do_magical_check == 1) {
673         print STDERR "trying $last_seen_dir/$name...\n" if $Verbose >= 2; # very verbose
674         if (-f "$last_seen_dir/$name") {
675             return("$last_seen_dir/$name");
676         }
677     }
678     die "No file `$name' (reqd from file `$orig_src_file') among include directories: $Include_dirs\n";
679 }
680
681 # out of the driver, actually
682 sub run_something {
683     local($str_to_do, $file_to_read, $tidy_name) = @_;
684
685     print STDERR "\n$tidy_name:\n\t" if $Verbose;
686     print STDERR "$str_to_do\n" if $Verbose;
687
688     local($return_val) = system($str_to_do) >> 8;
689
690     if ($return_val != 0) {
691         local($die_msg) = "$Pgm: Running $tidy_name ( on $file_to_read ) failed";
692         $die_msg .= " program not found: $str_to_do " if $return_val == 255;
693         $die_msg .= " ($!)" if $Verbose && $! != 0;
694         $die_msg .= "\n";
695         print STDERR $die_msg;
696         exit $return_val;
697     }
698 }
699
700 # out of the driver too.
701 sub check_for_source_options {
702     local($file) = @_;
703     local($comment_start,$comment_end);
704
705     # Assume it is a file containing Haskell source
706     $comment_start = "{-#";
707     $comment_end   = "#-}";
708
709     open(FILE,$file) || return ""; # No big loss
710     
711     while (<FILE>) {
712         if ( /^${comment_start} OPTIONS (.*)${comment_end}/ ) {
713            # return the options.
714            local($stuff) = $1;
715            print STDERR "Found OPTIONS $stuff in $file\n" if $Verbose;
716            close(FILE);
717            return $stuff;
718         }
719         elsif ( /^$/ ) { # ignore empty lines
720            ;
721         }
722         elsif ( /^#line.+$/ ) { # ignore comment lines (unused..ToDo: rm )
723            ;
724         }
725         elsif ( /^{-# LINE.+$/ ) { # ignore line pragmas
726            ;
727         }
728         else { # stop looking, something non-empty / not
729                # ${comment_start} OPTIONS .. ${comment_end} encountered.
730             close(FILE);return "";
731         }
732     }
733     close(FILE);
734     return "";
735 }