[project @ 2005-08-03 10:42:53 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / DriverPipeline.hs
1 -----------------------------------------------------------------------------
2 --
3 -- GHC Driver
4 --
5 -- (c) The University of Glasgow 2005
6 --
7 -----------------------------------------------------------------------------
8
9 module DriverPipeline (
10         -- Run a series of compilation steps in a pipeline, for a
11         -- collection of source files.
12    oneShot, compileFile,
13
14         -- Interfaces for the batch-mode driver
15    staticLink,
16
17         -- Interfaces for the compilation manager (interpreted/batch-mode)
18    preprocess, 
19    compile, CompResult(..), 
20    link, 
21
22         -- DLL building
23    doMkDLL,
24
25    getOptionsFromStringBuffer,  -- used in module GHC
26    optionsErrorMsgs,            -- ditto
27   ) where
28
29 #include "HsVersions.h"
30
31 import Packages
32 import GetImports
33 import DriverPhases
34 import SysTools         ( newTempName, addFilesToClean, getSysMan, copy )
35 import qualified SysTools       
36 import HscMain
37 import Finder
38 import HscTypes
39 import Outputable
40 import Module
41 import ErrUtils
42 import DynFlags
43 import StaticFlags      ( v_Ld_inputs, opt_Static, WayName(..) )
44 import Config
45 import Panic
46 import Util
47 import StringBuffer     ( hGetStringBuffer )
48 import BasicTypes       ( SuccessFlag(..) )
49 import Maybes           ( expectJust )
50 import Ctype            ( is_ident )
51 import StringBuffer     ( StringBuffer(..), lexemeToString )
52 import ParserCoreUtils  ( getCoreModuleName )
53 import SrcLoc           ( srcLocSpan, mkSrcLoc )
54 import FastString       ( mkFastString )
55 import Bag              ( listToBag, emptyBag )
56 import SrcLoc           ( Located(..) )
57
58 import EXCEPTION
59 import DATA_IOREF       ( readIORef, writeIORef, IORef )
60 import GLAEXTS          ( Int(..) )
61
62 import Directory
63 import System
64 import IO
65 import Monad
66 import Maybe
67
68
69 -- ---------------------------------------------------------------------------
70 -- Pre-process
71
72 -- Just preprocess a file, put the result in a temp. file (used by the
73 -- compilation manager during the summary phase).
74 --
75 -- We return the augmented DynFlags, because they contain the result
76 -- of slurping in the OPTIONS pragmas
77
78 preprocess :: DynFlags -> (FilePath, Maybe Phase) -> IO (DynFlags, FilePath)
79 preprocess dflags (filename, mb_phase) =
80   ASSERT2(isJust mb_phase || isHaskellSrcFilename filename, text filename) 
81   runPipeline anyHsc dflags (filename, mb_phase) Temporary Nothing{-no ModLocation-}
82
83 -- ---------------------------------------------------------------------------
84 -- Compile
85
86 -- Compile a single module, under the control of the compilation manager.
87 --
88 -- This is the interface between the compilation manager and the
89 -- compiler proper (hsc), where we deal with tedious details like
90 -- reading the OPTIONS pragma from the source file, and passing the
91 -- output of hsc through the C compiler.
92
93 -- NB.  No old interface can also mean that the source has changed.
94
95 compile :: HscEnv
96         -> (Messages -> IO ())  -- error message callback
97         -> ModSummary
98         -> Maybe Linkable       -- Just linkable <=> source unchanged
99         -> Maybe ModIface       -- Old interface, if available
100         -> Int -> Int
101         -> IO CompResult
102
103 data CompResult
104    = CompOK   ModDetails        -- New details
105               ModIface          -- New iface
106               (Maybe Linkable)  -- a Maybe, for the same reasons as hm_linkable
107
108    | CompErrs 
109
110
111 compile hsc_env msg_act mod_summary maybe_old_linkable old_iface mod_index nmods = do 
112
113    let dflags0     = hsc_dflags hsc_env
114        this_mod    = ms_mod mod_summary
115        src_flavour = ms_hsc_src mod_summary
116
117        have_object 
118                | Just l <- maybe_old_linkable, isObjectLinkable l = True
119                | otherwise = False
120
121    showPass dflags0 ("Compiling " ++ showModMsg have_object mod_summary)
122
123    let location   = ms_location mod_summary
124    let input_fn   = expectJust "compile:hs" (ml_hs_file location) 
125    let input_fnpp = expectJust "compile:hspp" (ms_hspp_file mod_summary)
126
127    debugTraceMsg dflags0 2 ("compile: input file " ++ input_fnpp)
128
129    -- Add in the OPTIONS from the source file
130    -- This is nasty: we've done this once already, in the compilation manager
131    -- It might be better to cache the flags in the ml_hspp_file field,say
132    let hspp_buf = expectJust "compile:hspp_buf" (ms_hspp_buf mod_summary)
133        opts = getOptionsFromStringBuffer hspp_buf
134    (dflags1,unhandled_flags) <- parseDynamicFlags dflags0 (map snd opts)
135    if (not (null unhandled_flags))
136         then do msg_act (optionsErrorMsgs unhandled_flags opts input_fn)
137                 return CompErrs
138         else do
139
140    let (basename, _) = splitFilename input_fn
141
142   -- We add the directory in which the .hs files resides) to the import path.
143   -- This is needed when we try to compile the .hc file later, if it
144   -- imports a _stub.h file that we created here.
145    let current_dir = directoryOf basename
146        old_paths   = includePaths dflags1
147        dflags      = dflags1 { includePaths = current_dir : old_paths }
148
149    -- Figure out what lang we're generating
150    let hsc_lang = hscMaybeAdjustTarget dflags StopLn src_flavour (hscTarget dflags)
151    -- ... and what the next phase should be
152    let next_phase = hscNextPhase dflags src_flavour hsc_lang
153    -- ... and what file to generate the output into
154    output_fn <- getOutputFilename dflags next_phase 
155                         Temporary basename next_phase (Just location)
156
157    let dflags' = dflags { hscTarget = hsc_lang,
158                                 hscOutName = output_fn,
159                                 hscStubCOutName = basename ++ "_stub.c",
160                                 hscStubHOutName = basename ++ "_stub.h",
161                                 extCoreName = basename ++ ".hcr" }
162
163    -- -no-recomp should also work with --make
164    let do_recomp = dopt Opt_RecompChecking dflags
165        source_unchanged = isJust maybe_old_linkable && do_recomp
166        hsc_env' = hsc_env { hsc_dflags = dflags' }
167        object_filename = ml_obj_file location
168
169    -- run the compiler
170    hsc_result <- hscMain hsc_env' msg_act mod_summary
171                          source_unchanged have_object old_iface
172                          (Just (mod_index, nmods))
173
174    case hsc_result of
175       HscFail -> return CompErrs
176
177       HscNoRecomp details iface -> 
178           ASSERT(isJust maybe_old_linkable)
179           return (CompOK details iface maybe_old_linkable)
180
181       HscRecomp details iface stub_h_exists stub_c_exists maybe_interpreted_code 
182
183         | isHsBoot src_flavour  -- No further compilation to do
184         -> do   case hsc_lang of
185                    HscInterpreted -> return ()
186                    _other -> SysTools.touch dflags' "Touching object file" 
187                                             object_filename
188                 return (CompOK details iface Nothing)
189
190         | otherwise     -- Normal source file
191         -> do
192            stub_unlinked <-
193              if stub_c_exists then do
194                 stub_o <- compileStub dflags' object_filename
195                 return [ DotO stub_o ]
196              else
197                 return []
198
199            (hs_unlinked, unlinked_time) <-
200              case hsc_lang of
201
202                 -- in interpreted mode, just return the compiled code
203                 -- as our "unlinked" object.
204                 HscInterpreted
205                   -> case maybe_interpreted_code of
206 #ifdef GHCI
207                        Just comp_bc -> return ([BCOs comp_bc], ms_hs_date mod_summary)
208                         -- Why do we use the timestamp of the source file here,
209                         -- rather than the current time?  This works better in
210                         -- the case where the local clock is out of sync
211                         -- with the filesystem's clock.  It's just as accurate:
212                         -- if the source is modified, then the linkable will
213                         -- be out of date.
214 #endif
215                        Nothing -> panic "compile: no interpreted code"
216
217                 HscNothing
218                   -> return ([], ms_hs_date mod_summary)
219
220                 -- We're in --make mode: finish the compilation pipeline.
221                 _other
222                   -> do runPipeline StopLn dflags (output_fn,Nothing) Persistent
223                                     (Just location)
224                                 -- The object filename comes from the ModLocation
225
226                         o_time <- getModificationTime object_filename
227                         return ([DotO object_filename], o_time)
228
229            let linkable = LM unlinked_time this_mod
230                              (hs_unlinked ++ stub_unlinked)
231
232            return (CompOK details iface (Just linkable))
233
234 -----------------------------------------------------------------------------
235 -- stub .h and .c files (for foreign export support)
236
237 -- The _stub.c file is derived from the haskell source file (but stored
238 -- in hscStubCOutName in the dflags for some reason, probably historical).
239 -- Consequently, we derive the _stub.o filename from the haskell object
240 -- filename.  
241 --
242 -- This isn't necessarily the same as the object filename we
243 -- would get if we just compiled the _stub.c file using the pipeline.
244 -- For example:
245 --
246 --    ghc src/A.hs -odir obj
247 -- 
248 -- results in obj/A.o, and src/A_stub.c.  If we compile src/A_stub.c with
249 -- -odir obj, we would get obj/src/A_stub.o, which is wrong; we want
250 -- obj/A_stub.o.
251
252 compileStub dflags object_filename = do
253         let (o_base, o_ext) = splitFilename object_filename
254             stub_o = o_base ++ "_stub" `joinFileExt` o_ext
255
256         -- compile the _stub.c file w/ gcc
257         let stub_c = hscStubCOutName dflags
258         runPipeline StopLn dflags (stub_c,Nothing) 
259                 (SpecificFile stub_o) Nothing{-no ModLocation-}
260
261         return stub_o
262
263
264 -- ---------------------------------------------------------------------------
265 -- Link
266
267 link :: GhcMode                 -- interactive or batch
268      -> DynFlags                -- dynamic flags
269      -> Bool                    -- attempt linking in batch mode?
270      -> HomePackageTable        -- what to link
271      -> IO SuccessFlag
272
273 -- For the moment, in the batch linker, we don't bother to tell doLink
274 -- which packages to link -- it just tries all that are available.
275 -- batch_attempt_linking should only be *looked at* in batch mode.  It
276 -- should only be True if the upsweep was successful and someone
277 -- exports main, i.e., we have good reason to believe that linking
278 -- will succeed.
279
280 #ifdef GHCI
281 link Interactive dflags batch_attempt_linking hpt
282     = do -- Not Linking...(demand linker will do the job)
283          return Succeeded
284 #endif
285
286 link JustTypecheck dflags batch_attempt_linking hpt
287    = return Succeeded
288
289 link BatchCompile dflags batch_attempt_linking hpt
290    | batch_attempt_linking
291    = do 
292         let 
293             home_mod_infos = moduleEnvElts hpt
294
295             -- the packages we depend on
296             pkg_deps  = concatMap (dep_pkgs . mi_deps . hm_iface) home_mod_infos
297
298             -- the linkables to link
299             linkables = map (fromJust.hm_linkable) home_mod_infos
300
301         debugTraceMsg dflags 3 "link: linkables are ..."
302         debugTraceMsg dflags 3 (showSDoc (vcat (map ppr linkables)))
303
304         -- check for the -no-link flag
305         if isNoLink (ghcLink dflags)
306           then do debugTraceMsg dflags 3 "link(batch): linking omitted (-c flag given)."
307                   return Succeeded
308           else do
309
310         debugTraceMsg dflags 1 "Linking ..."
311
312         let getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
313             obj_files = concatMap getOfiles linkables
314
315         -- Don't showPass in Batch mode; doLink will do that for us.
316         staticLink dflags obj_files pkg_deps
317
318         debugTraceMsg dflags 3 "link: done"
319
320         -- staticLink only returns if it succeeds
321         return Succeeded
322
323    | otherwise
324    = do debugTraceMsg dflags 3 "link(batch): upsweep (partially) failed OR"
325         debugTraceMsg dflags 3 "   Main.main not exported; not linking."
326         return Succeeded
327       
328
329 -- -----------------------------------------------------------------------------
330 -- Compile files in one-shot mode.
331
332 oneShot :: DynFlags -> Phase -> [(String, Maybe Phase)] -> IO ()
333 oneShot dflags stop_phase srcs = do
334   o_files <- mapM (compileFile dflags stop_phase) srcs
335   doLink dflags stop_phase o_files
336
337 compileFile :: DynFlags -> Phase -> (FilePath, Maybe Phase) -> IO FilePath
338 compileFile dflags stop_phase (src, mb_phase) = do
339    exists <- doesFileExist src
340    when (not exists) $ 
341         throwDyn (CmdLineError ("does not exist: " ++ src))
342    
343    let
344         split     = dopt Opt_SplitObjs dflags
345         mb_o_file = outputFile dflags
346         ghc_link  = ghcLink dflags      -- Set by -c or -no-link
347
348         -- When linking, the -o argument refers to the linker's output. 
349         -- otherwise, we use it as the name for the pipeline's output.
350         output
351          | StopLn <- stop_phase, not (isNoLink ghc_link) = Persistent
352                 -- -o foo applies to linker
353          | Just o_file <- mb_o_file = SpecificFile o_file
354                 -- -o foo applies to the file we are compiling now
355          | otherwise = Persistent
356
357         stop_phase' = case stop_phase of 
358                         As | split -> SplitAs
359                         other      -> stop_phase
360
361    (_, out_file) <- runPipeline stop_phase' dflags
362                           (src, mb_phase) output Nothing{-no ModLocation-}
363    return out_file
364
365
366 doLink :: DynFlags -> Phase -> [FilePath] -> IO ()
367 doLink dflags stop_phase o_files
368   | not (isStopLn stop_phase)
369   = return ()           -- We stopped before the linking phase
370
371   | otherwise
372   = case ghcLink dflags of
373         NoLink     -> return ()
374         StaticLink -> staticLink dflags o_files link_pkgs
375         MkDLL      -> doMkDLL dflags o_files link_pkgs
376   where
377    -- Always link in the haskell98 package for static linking.  Other
378    -- packages have to be specified via the -package flag.
379     link_pkgs
380           | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
381           | otherwise = []
382
383
384 -- ---------------------------------------------------------------------------
385 -- Run a compilation pipeline, consisting of multiple phases.
386
387 -- This is the interface to the compilation pipeline, which runs
388 -- a series of compilation steps on a single source file, specifying
389 -- at which stage to stop.
390
391 -- The DynFlags can be modified by phases in the pipeline (eg. by
392 -- GHC_OPTIONS pragmas), and the changes affect later phases in the
393 -- pipeline.
394
395 data PipelineOutput 
396   = Temporary
397         -- output should be to a temporary file: we're going to
398         -- run more compilation steps on this output later
399   | Persistent
400         -- we want a persistent file, i.e. a file in the current directory
401         -- derived from the input filename, but with the appropriate extension.
402         -- eg. in "ghc -c Foo.hs" the output goes into ./Foo.o.
403   | SpecificFile FilePath
404         -- the output must go into the specified file.
405
406 runPipeline
407   :: Phase                      -- When to stop
408   -> DynFlags                   -- Dynamic flags
409   -> (FilePath,Maybe Phase)     -- Input filename (and maybe -x suffix)
410   -> PipelineOutput             -- Output filename
411   -> Maybe ModLocation          -- A ModLocation, if this is a Haskell module
412   -> IO (DynFlags, FilePath)    -- (final flags, output filename)
413
414 runPipeline stop_phase dflags (input_fn, mb_phase) output maybe_loc
415   = do
416   let (basename, suffix) = splitFilename input_fn
417
418         -- If we were given a -x flag, then use that phase to start from
419       start_phase
420         | Just x_phase <- mb_phase = x_phase
421         | otherwise                = startPhase suffix
422
423   -- We want to catch cases of "you can't get there from here" before
424   -- we start the pipeline, because otherwise it will just run off the
425   -- end.
426   --
427   -- There is a partial ordering on phases, where A < B iff A occurs
428   -- before B in a normal compilation pipeline.
429
430   when (not (start_phase `happensBefore` stop_phase)) $
431         throwDyn (UsageError 
432                     ("cannot compile this file to desired target: "
433                        ++ input_fn))
434
435   -- this is a function which will be used to calculate output file names
436   -- as we go along (we partially apply it to some of its inputs here)
437   let get_output_fn = getOutputFilename dflags stop_phase output basename
438
439   -- Execute the pipeline...
440   (dflags', output_fn, maybe_loc) <- 
441         pipeLoop dflags start_phase stop_phase input_fn 
442                  basename suffix get_output_fn maybe_loc
443
444   -- Sometimes, a compilation phase doesn't actually generate any output
445   -- (eg. the CPP phase when -fcpp is not turned on).  If we end on this
446   -- stage, but we wanted to keep the output, then we have to explicitly
447   -- copy the file.
448   case output of
449     Temporary -> 
450         return (dflags', output_fn)
451     _other ->
452         do final_fn <- get_output_fn stop_phase maybe_loc
453            when (final_fn /= output_fn) $
454                   copy dflags ("Copying `" ++ output_fn ++ "' to `" ++ final_fn
455                         ++ "'") output_fn final_fn
456            return (dflags', final_fn)
457                 
458
459
460 pipeLoop :: DynFlags -> Phase -> Phase 
461          -> FilePath  -> String -> Suffix
462          -> (Phase -> Maybe ModLocation -> IO FilePath)
463          -> Maybe ModLocation
464          -> IO (DynFlags, FilePath, Maybe ModLocation)
465
466 pipeLoop dflags phase stop_phase 
467          input_fn orig_basename orig_suff 
468          orig_get_output_fn maybe_loc
469
470   | phase `eqPhase` stop_phase            -- All done
471   = return (dflags, input_fn, maybe_loc)
472
473   | not (phase `happensBefore` stop_phase)
474         -- Something has gone wrong.  We'll try to cover all the cases when
475         -- this could happen, so if we reach here it is a panic.
476         -- eg. it might happen if the -C flag is used on a source file that
477         -- has {-# OPTIONS -fasm #-}.
478   = panic ("pipeLoop: at phase " ++ show phase ++ 
479            " but I wanted to stop at phase " ++ show stop_phase)
480
481   | otherwise 
482   = do  { (next_phase, dflags', maybe_loc, output_fn)
483                 <- runPhase phase stop_phase dflags orig_basename 
484                             orig_suff input_fn orig_get_output_fn maybe_loc
485         ; pipeLoop dflags' next_phase stop_phase output_fn
486                    orig_basename orig_suff orig_get_output_fn maybe_loc }
487
488 getOutputFilename
489   :: DynFlags -> Phase -> PipelineOutput -> String
490   -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath
491 getOutputFilename dflags stop_phase output basename
492  = func
493  where
494         hcsuf      = hcSuf dflags
495         odir       = outputDir dflags
496         osuf       = objectSuf dflags
497         keep_hc    = dopt Opt_KeepHcFiles dflags
498         keep_raw_s = dopt Opt_KeepRawSFiles dflags
499         keep_s     = dopt Opt_KeepSFiles dflags
500
501         myPhaseInputExt HCc    = hcsuf
502         myPhaseInputExt StopLn = osuf
503         myPhaseInputExt other  = phaseInputExt other
504
505         func next_phase maybe_location
506            | is_last_phase, Persistent <- output     = persistent_fn
507            | is_last_phase, SpecificFile f <- output = return f
508            | keep_this_output                        = persistent_fn
509            | otherwise                               = newTempName dflags suffix
510            where
511                 is_last_phase = next_phase `eqPhase` stop_phase
512
513                 -- sometimes, we keep output from intermediate stages
514                 keep_this_output = 
515                      case next_phase of
516                              StopLn              -> True
517                              Mangle | keep_raw_s -> True
518                              As     | keep_s     -> True
519                              HCc    | keep_hc    -> True
520                              _other              -> False
521
522                 suffix = myPhaseInputExt next_phase
523
524                 -- persistent object files get put in odir
525                 persistent_fn 
526                    | StopLn <- next_phase = return odir_persistent
527                    | otherwise            = return persistent
528
529                 persistent = basename `joinFileExt` suffix
530
531                 odir_persistent
532                    | Just loc <- maybe_location = ml_obj_file loc
533                    | Just d <- odir = d `joinFileName` persistent
534                    | otherwise      = persistent
535
536
537 -- -----------------------------------------------------------------------------
538 -- Each phase in the pipeline returns the next phase to execute, and the
539 -- name of the file in which the output was placed.
540 --
541 -- We must do things dynamically this way, because we often don't know
542 -- what the rest of the phases will be until part-way through the
543 -- compilation: for example, an {-# OPTIONS -fasm #-} at the beginning
544 -- of a source file can change the latter stages of the pipeline from
545 -- taking the via-C route to using the native code generator.
546
547 runPhase :: Phase       -- Do this phase first
548          -> Phase       -- Stop just before this phase
549          -> DynFlags
550          -> String      -- basename of original input source
551          -> String      -- its extension
552          -> FilePath    -- name of file which contains the input to this phase.
553          -> (Phase -> Maybe ModLocation -> IO FilePath)
554                         -- how to calculate the output filename
555          -> Maybe ModLocation           -- the ModLocation, if we have one
556          -> IO (Phase,                  -- next phase
557                 DynFlags,               -- new dynamic flags
558                 Maybe ModLocation,      -- the ModLocation, if we have one
559                 FilePath)               -- output filename
560
561         -- Invariant: the output filename always contains the output
562         -- Interesting case: Hsc when there is no recompilation to do
563         --                   Then the output filename is still a .o file 
564
565 -------------------------------------------------------------------------------
566 -- Unlit phase 
567
568 runPhase (Unlit sf) _stop dflags _basename _suff input_fn get_output_fn maybe_loc
569   = do let unlit_flags = getOpts dflags opt_L
570        -- The -h option passes the file name for unlit to put in a #line directive
571        output_fn <- get_output_fn (Cpp sf) maybe_loc
572
573        SysTools.runUnlit dflags 
574                 (map SysTools.Option unlit_flags ++
575                           [ SysTools.Option     "-h"
576                           , SysTools.Option     input_fn
577                           , SysTools.FileOption "" input_fn
578                           , SysTools.FileOption "" output_fn
579                           ])
580
581        return (Cpp sf, dflags, maybe_loc, output_fn)
582
583 -------------------------------------------------------------------------------
584 -- Cpp phase : (a) gets OPTIONS out of file
585 --             (b) runs cpp if necessary
586
587 runPhase (Cpp sf) _stop dflags0 basename suff input_fn get_output_fn maybe_loc
588   = do src_opts <- getOptionsFromSource input_fn
589        (dflags,unhandled_flags) <- parseDynamicFlags dflags0 src_opts
590        checkProcessArgsResult unhandled_flags (basename `joinFileExt` suff)
591
592        if not (dopt Opt_Cpp dflags) then
593            -- no need to preprocess CPP, just pass input file along
594            -- to the next phase of the pipeline.
595           return (HsPp sf, dflags, maybe_loc, input_fn)
596         else do
597             output_fn <- get_output_fn (HsPp sf) maybe_loc
598             doCpp dflags True{-raw-} False{-no CC opts-} input_fn output_fn
599             return (HsPp sf, dflags, maybe_loc, output_fn)
600
601 -------------------------------------------------------------------------------
602 -- HsPp phase 
603
604 runPhase (HsPp sf) _stop dflags basename suff input_fn get_output_fn maybe_loc
605   = do if not (dopt Opt_Pp dflags) then
606            -- no need to preprocess, just pass input file along
607            -- to the next phase of the pipeline.
608           return (Hsc sf, dflags, maybe_loc, input_fn)
609         else do
610             let hspp_opts = getOpts dflags opt_F
611             let orig_fn = basename `joinFileExt` suff
612             output_fn <- get_output_fn (Hsc sf) maybe_loc
613             SysTools.runPp dflags
614                            ( [ SysTools.Option     orig_fn
615                              , SysTools.Option     input_fn
616                              , SysTools.FileOption "" output_fn
617                              ] ++
618                              map SysTools.Option hspp_opts
619                            )
620             return (Hsc sf, dflags, maybe_loc, output_fn)
621
622 -----------------------------------------------------------------------------
623 -- Hsc phase
624
625 -- Compilation of a single module, in "legacy" mode (_not_ under
626 -- the direction of the compilation manager).
627 runPhase (Hsc src_flavour) stop dflags0 basename suff input_fn get_output_fn _maybe_loc 
628  = do   -- normal Hsc mode, not mkdependHS
629
630   -- we add the current directory (i.e. the directory in which
631   -- the .hs files resides) to the import path, since this is
632   -- what gcc does, and it's probably what you want.
633         let current_dir = directoryOf basename
634         
635             paths = includePaths dflags0
636             dflags = dflags0 { includePaths = current_dir : paths }
637         
638   -- gather the imports and module name
639         (hspp_buf,mod_name) <- 
640             case src_flavour of
641                 ExtCoreFile -> do {  -- no explicit imports in ExtCore input.
642                                   ; m <- getCoreModuleName input_fn
643                                   ; return (Nothing, mkModule m) }
644
645                 other -> do { buf <- hGetStringBuffer input_fn
646                             ; (_,_,L _ mod_name) <- getImports dflags buf input_fn
647                             ; return (Just buf, mod_name) }
648
649   -- Build a ModLocation to pass to hscMain.
650   -- The source filename is rather irrelevant by now, but it's used
651   -- by hscMain for messages.  hscMain also needs 
652   -- the .hi and .o filenames, and this is as good a way
653   -- as any to generate them, and better than most. (e.g. takes 
654   -- into accout the -osuf flags)
655         location1 <- mkHomeModLocation2 dflags mod_name basename suff
656
657   -- Boot-ify it if necessary
658         let location2 | isHsBoot src_flavour = addBootSuffixLocn location1
659                       | otherwise            = location1 
660                                         
661
662   -- Take -ohi into account if present
663   -- This can't be done in mkHomeModuleLocation because
664   -- it only applies to the module being compiles
665         let ohi = outputHi dflags
666             location3 | Just fn <- ohi = location2{ ml_hi_file = fn }
667                       | otherwise      = location2
668
669   -- Take -o into account if present
670   -- Very like -ohi, but we must *only* do this if we aren't linking
671   -- (If we're linking then the -o applies to the linked thing, not to
672   -- the object file for one module.)
673   -- Note the nasty duplication with the same computation in compileFile above
674         let expl_o_file = outputFile dflags
675             location4 | Just ofile <- expl_o_file
676                       , isNoLink (ghcLink dflags)
677                       = location3 { ml_obj_file = ofile }
678                       | otherwise = location3
679
680   -- Make the ModSummary to hand to hscMain
681         src_timestamp <- getModificationTime (basename `joinFileExt` suff)
682         let
683             unused_field = panic "runPhase:ModSummary field"
684                 -- Some fields are not looked at by hscMain
685             mod_summary = ModSummary {  ms_mod       = mod_name, 
686                                         ms_hsc_src   = src_flavour,
687                                         ms_hspp_file = Just input_fn,
688                                         ms_hspp_buf  = hspp_buf,
689                                         ms_location  = location4,
690                                         ms_hs_date   = src_timestamp,
691                                         ms_obj_date  = Nothing,
692                                         ms_imps      = unused_field,
693                                         ms_srcimps   = unused_field }
694
695             o_file = ml_obj_file location4      -- The real object file
696
697
698   -- Figure out if the source has changed, for recompilation avoidance.
699   --
700   -- Setting source_unchanged to True means that M.o seems
701   -- to be up to date wrt M.hs; so no need to recompile unless imports have
702   -- changed (which the compiler itself figures out).
703   -- Setting source_unchanged to False tells the compiler that M.o is out of
704   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
705         let do_recomp = dopt Opt_RecompChecking dflags
706         source_unchanged <- 
707           if not do_recomp || not (isStopLn stop)
708                 -- Set source_unchanged to False unconditionally if
709                 --      (a) recompilation checker is off, or
710                 --      (b) we aren't going all the way to .o file (e.g. ghc -S)
711              then return False  
712                 -- Otherwise look at file modification dates
713              else do o_file_exists <- doesFileExist o_file
714                      if not o_file_exists
715                         then return False       -- Need to recompile
716                         else do t2 <- getModificationTime o_file
717                                 if t2 > src_timestamp
718                                   then return True
719                                   else return False
720
721   -- get the DynFlags
722         let hsc_lang = hscMaybeAdjustTarget dflags stop src_flavour (hscTarget dflags)
723         let next_phase = hscNextPhase dflags src_flavour hsc_lang
724         output_fn  <- get_output_fn next_phase (Just location4)
725
726         let dflags' = dflags { hscTarget = hsc_lang,
727                                hscOutName = output_fn,
728                                hscStubCOutName = basename ++ "_stub.c",
729                                hscStubHOutName = basename ++ "_stub.h",
730                                extCoreName = basename ++ ".hcr" }
731
732         hsc_env <- newHscEnv dflags'
733
734   -- Tell the finder cache about this module
735         addHomeModuleToFinder hsc_env mod_name location4
736
737   -- run the compiler!
738         result <- hscMain hsc_env printErrorsAndWarnings
739                           mod_summary source_unchanged 
740                           False         -- No object file
741                           Nothing       -- No iface
742                           Nothing       -- No "module i of n" progress info
743
744         case result of
745
746             HscFail -> throwDyn (PhaseFailed "hsc" (ExitFailure 1))
747
748             HscNoRecomp details iface -> do
749                 SysTools.touch dflags' "Touching object file" o_file
750                         -- The .o file must have a later modification date
751                         -- than the source file (else we wouldn't be in HscNoRecomp)
752                         -- but we touch it anyway, to keep 'make' happy (we think).
753                 return (StopLn, dflags', Just location4, o_file)
754
755             HscRecomp _details _iface 
756                       stub_h_exists stub_c_exists
757                       _maybe_interpreted_code -> do
758
759                 when stub_c_exists $ do
760                         stub_o <- compileStub dflags' o_file
761                         consIORef v_Ld_inputs stub_o
762
763                 -- In the case of hs-boot files, generate a dummy .o-boot 
764                 -- stamp file for the benefit of Make
765                 case src_flavour of
766                   HsBootFile -> SysTools.touch dflags' "Touching object file" o_file
767                   other      -> return ()
768
769                 return (next_phase, dflags', Just location4, output_fn)
770
771 -----------------------------------------------------------------------------
772 -- Cmm phase
773
774 runPhase CmmCpp stop dflags basename suff input_fn get_output_fn maybe_loc
775   = do
776        output_fn <- get_output_fn Cmm maybe_loc
777        doCpp dflags False{-not raw-} True{-include CC opts-} input_fn output_fn 
778        return (Cmm, dflags, maybe_loc, output_fn)
779
780 runPhase Cmm stop dflags basename suff input_fn get_output_fn maybe_loc
781   = do
782         let hsc_lang = hscMaybeAdjustTarget dflags stop HsSrcFile (hscTarget dflags)
783         let next_phase = hscNextPhase dflags HsSrcFile hsc_lang
784         output_fn <- get_output_fn next_phase maybe_loc
785
786         let dflags' = dflags { hscTarget = hsc_lang,
787                                hscOutName = output_fn,
788                                hscStubCOutName = basename ++ "_stub.c",
789                                hscStubHOutName = basename ++ "_stub.h",
790                                extCoreName = basename ++ ".hcr" }
791
792         ok <- hscCmmFile dflags' input_fn
793
794         when (not ok) $ throwDyn (PhaseFailed "cmm" (ExitFailure 1))
795
796         return (next_phase, dflags, maybe_loc, output_fn)
797
798 -----------------------------------------------------------------------------
799 -- Cc phase
800
801 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
802 -- way too many hacks, and I can't say I've ever used it anyway.
803
804 runPhase cc_phase stop dflags basename suff input_fn get_output_fn maybe_loc
805    | cc_phase `eqPhase` Cc || cc_phase `eqPhase` HCc
806    = do let cc_opts = getOpts dflags opt_c
807             hcc = cc_phase `eqPhase` HCc
808
809         let cmdline_include_paths = includePaths dflags
810
811         -- HC files have the dependent packages stamped into them
812         pkgs <- if hcc then getHCFilePackages input_fn else return []
813
814         -- add package include paths even if we're just compiling .c
815         -- files; this is the Value Add(TM) that using ghc instead of
816         -- gcc gives you :)
817         pkg_include_dirs <- getPackageIncludePath dflags pkgs
818         let include_paths = foldr (\ x xs -> "-I" : x : xs) []
819                               (cmdline_include_paths ++ pkg_include_dirs)
820
821         let (md_c_flags, md_regd_c_flags) = machdepCCOpts dflags
822         let pic_c_flags = picCCOpts dflags
823
824         let verb = getVerbFlag dflags
825
826         pkg_extra_cc_opts <- getPackageExtraCcOpts dflags pkgs
827
828         let split_objs = dopt Opt_SplitObjs dflags
829             split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
830                       | otherwise         = [ ]
831
832         let excessPrecision = dopt Opt_ExcessPrecision dflags
833
834         -- Decide next phase
835         
836         let mangle = dopt Opt_DoAsmMangling dflags
837             next_phase
838                 | hcc && mangle     = Mangle
839                 | otherwise         = As
840         output_fn <- get_output_fn next_phase maybe_loc
841
842         SysTools.runCc dflags (
843                 -- force the C compiler to interpret this file as C when
844                 -- compiling .hc files, by adding the -x c option.
845                 -- Also useful for plain .c files, just in case GHC saw a 
846                 -- -x c option.
847                         [ SysTools.Option "-x", SysTools.Option "c"] ++
848                         [ SysTools.FileOption "" input_fn
849                         , SysTools.Option "-o"
850                         , SysTools.FileOption "" output_fn
851                         ]
852                        ++ map SysTools.Option (
853                           md_c_flags
854                        ++ pic_c_flags
855                        ++ (if hcc && mangle
856                              then md_regd_c_flags
857                              else [])
858                        ++ [ verb, "-S", "-Wimplicit", "-O" ]
859                        ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
860                        ++ cc_opts
861                        ++ split_opt
862                        ++ (if excessPrecision then [] else [ "-ffloat-store" ])
863                        ++ include_paths
864                        ++ pkg_extra_cc_opts
865                        ))
866
867         return (next_phase, dflags, maybe_loc, output_fn)
868
869         -- ToDo: postprocess the output from gcc
870
871 -----------------------------------------------------------------------------
872 -- Mangle phase
873
874 runPhase Mangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
875    = do let mangler_opts = getOpts dflags opt_m
876
877 #if i386_TARGET_ARCH
878         machdep_opts <- return [ show (stolen_x86_regs dflags) ]
879 #else
880         machdep_opts <- return []
881 #endif
882
883         let split = dopt Opt_SplitObjs dflags
884             next_phase
885                 | split = SplitMangle
886                 | otherwise = As
887         output_fn <- get_output_fn next_phase maybe_loc
888
889         SysTools.runMangle dflags (map SysTools.Option mangler_opts
890                           ++ [ SysTools.FileOption "" input_fn
891                              , SysTools.FileOption "" output_fn
892                              ]
893                           ++ map SysTools.Option machdep_opts)
894
895         return (next_phase, dflags, maybe_loc, output_fn)
896
897 -----------------------------------------------------------------------------
898 -- Splitting phase
899
900 runPhase SplitMangle stop dflags _basename _suff input_fn get_output_fn maybe_loc
901   = do  -- tmp_pfx is the prefix used for the split .s files
902         -- We also use it as the file to contain the no. of split .s files (sigh)
903         split_s_prefix <- SysTools.newTempName dflags "split"
904         let n_files_fn = split_s_prefix
905
906         SysTools.runSplit dflags
907                           [ SysTools.FileOption "" input_fn
908                           , SysTools.FileOption "" split_s_prefix
909                           , SysTools.FileOption "" n_files_fn
910                           ]
911
912         -- Save the number of split files for future references
913         s <- readFile n_files_fn
914         let n_files = read s :: Int
915         writeIORef v_Split_info (split_s_prefix, n_files)
916
917         -- Remember to delete all these files
918         addFilesToClean [ split_s_prefix ++ "__" ++ show n ++ ".s"
919                         | n <- [1..n_files]]
920
921         return (SplitAs, dflags, maybe_loc, "**splitmangle**")
922           -- we don't use the filename
923
924 -----------------------------------------------------------------------------
925 -- As phase
926
927 runPhase As stop dflags _basename _suff input_fn get_output_fn maybe_loc
928   = do  let as_opts =  getOpts dflags opt_a
929         let cmdline_include_paths = includePaths dflags
930
931         output_fn <- get_output_fn StopLn maybe_loc
932
933         -- we create directories for the object file, because it
934         -- might be a hierarchical module.
935         createDirectoryHierarchy (directoryOf output_fn)
936
937         SysTools.runAs dflags   
938                        (map SysTools.Option as_opts
939                        ++ [ SysTools.Option ("-I" ++ p) | p <- cmdline_include_paths ]
940                        ++ [ SysTools.Option "-c"
941                           , SysTools.FileOption "" input_fn
942                           , SysTools.Option "-o"
943                           , SysTools.FileOption "" output_fn
944                           ])
945
946         return (StopLn, dflags, maybe_loc, output_fn)
947
948
949 runPhase SplitAs stop dflags basename _suff _input_fn get_output_fn maybe_loc
950   = do  let as_opts = getOpts dflags opt_a
951
952         (split_s_prefix, n) <- readIORef v_Split_info
953
954         let real_odir
955                 | Just d <- outputDir dflags = d
956                 | otherwise                  = basename ++ "_split"
957
958         let assemble_file n
959               = do  let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
960                     let output_o = replaceFilenameDirectory
961                                         (basename ++ "__" ++ show n ++ ".o")
962                                          real_odir
963                     let osuf = objectSuf dflags
964                     let real_o = replaceFilenameSuffix output_o osuf
965                     SysTools.runAs dflags
966                                  (map SysTools.Option as_opts ++
967                                     [ SysTools.Option "-c"
968                                     , SysTools.Option "-o"
969                                     , SysTools.FileOption "" real_o
970                                     , SysTools.FileOption "" input_s
971                                     ])
972         
973         mapM_ assemble_file [1..n]
974
975         output_fn <- get_output_fn StopLn maybe_loc
976         return (StopLn, dflags, maybe_loc, output_fn)
977
978 -----------------------------------------------------------------------------
979 -- MoveBinary sort-of-phase
980 -- After having produced a binary, move it somewhere else and generate a
981 -- wrapper script calling the binary. Currently, we need this only in 
982 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
983 -- central directory.
984 -- This is called from staticLink below, after linking. I haven't made it
985 -- a separate phase to minimise interfering with other modules, and
986 -- we don't need the generality of a phase (MoveBinary is always
987 -- done after linking and makes only sense in a parallel setup)   -- HWL
988
989 runPhase_MoveBinary input_fn
990   = do  
991         sysMan   <- getSysMan
992         pvm_root <- getEnv "PVM_ROOT"
993         pvm_arch <- getEnv "PVM_ARCH"
994         let 
995            pvm_executable_base = "=" ++ input_fn
996            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
997         -- nuke old binary; maybe use configur'ed names for cp and rm?
998         system ("rm -f " ++ pvm_executable)
999         -- move the newly created binary into PVM land
1000         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
1001         -- generate a wrapper script for running a parallel prg under PVM
1002         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
1003         return True
1004
1005 -- generates a Perl skript starting a parallel prg under PVM
1006 mk_pvm_wrapper_script :: String -> String -> String -> String
1007 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
1008  [
1009   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
1010   "  if $running_under_some_shell;",
1011   "# =!=!=!=!=!=!=!=!=!=!=!",
1012   "# This script is automatically generated: DO NOT EDIT!!!",
1013   "# Generated by Glasgow Haskell Compiler",
1014   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
1015   "#",
1016   "$pvm_executable      = '" ++ pvm_executable ++ "';",
1017   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
1018   "$SysMan = '" ++ sysMan ++ "';",
1019   "",
1020   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
1021   "# first, some magical shortcuts to run "commands" on the binary",
1022   "# (which is hidden)",
1023   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
1024   "    local($cmd) = $1;",
1025   "    system("$cmd $pvm_executable");",
1026   "    exit(0); # all done",
1027   "}", -}
1028   "",
1029   "# Now, run the real binary; process the args first",
1030   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
1031   "$debug = '';",
1032   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
1033   "@nonPVM_args = ();",
1034   "$in_RTS_args = 0;",
1035   "",
1036   "args: while ($a = shift(@ARGV)) {",
1037   "    if ( $a eq '+RTS' ) {",
1038   "     $in_RTS_args = 1;",
1039   "    } elsif ( $a eq '-RTS' ) {",
1040   "     $in_RTS_args = 0;",
1041   "    }",
1042   "    if ( $a eq '-d' && $in_RTS_args ) {",
1043   "     $debug = '-';",
1044   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
1045   "     $nprocessors = $1;",
1046   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
1047   "     $nprocessors = $1;",
1048   "    } else {",
1049   "     push(@nonPVM_args, $a);",
1050   "    }",
1051   "}",
1052   "",
1053   "local($return_val) = 0;",
1054   "# Start the parallel execution by calling SysMan",
1055   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
1056   "$return_val = $?;",
1057   "# ToDo: fix race condition moving files and flushing them!!",
1058   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
1059   "exit($return_val);"
1060  ]
1061
1062 -----------------------------------------------------------------------------
1063 -- Complain about non-dynamic flags in OPTIONS pragmas
1064
1065 checkProcessArgsResult flags filename
1066   = do when (notNull flags) (throwDyn (ProgramError (
1067           showSDoc (hang (text filename <> char ':')
1068                       4 (text "unknown flags in  {-# OPTIONS #-} pragma:" <+>
1069                           hsep (map text flags)))
1070         )))
1071
1072 -----------------------------------------------------------------------------
1073 -- Look for the /* GHC_PACKAGES ... */ comment at the top of a .hc file
1074
1075 getHCFilePackages :: FilePath -> IO [PackageId]
1076 getHCFilePackages filename =
1077   EXCEPTION.bracket (openFile filename ReadMode) hClose $ \h -> do
1078     l <- hGetLine h
1079     case l of
1080       '/':'*':' ':'G':'H':'C':'_':'P':'A':'C':'K':'A':'G':'E':'S':rest ->
1081           return (map stringToPackageId (words rest))
1082       _other ->
1083           return []
1084
1085 -----------------------------------------------------------------------------
1086 -- Static linking, of .o files
1087
1088 -- The list of packages passed to link is the list of packages on
1089 -- which this program depends, as discovered by the compilation
1090 -- manager.  It is combined with the list of packages that the user
1091 -- specifies on the command line with -package flags.  
1092 --
1093 -- In one-shot linking mode, we can't discover the package
1094 -- dependencies (because we haven't actually done any compilation or
1095 -- read any interface files), so the user must explicitly specify all
1096 -- the packages.
1097
1098 staticLink :: DynFlags -> [FilePath] -> [PackageId] -> IO ()
1099 staticLink dflags o_files dep_packages = do
1100     let verb = getVerbFlag dflags
1101
1102     -- get the full list of packages to link with, by combining the
1103     -- explicit packages with the auto packages and all of their
1104     -- dependencies, and eliminating duplicates.
1105
1106     let o_file = outputFile dflags
1107 #if defined(mingw32_HOST_OS)
1108     let output_fn = case o_file of { Just s -> s; Nothing -> "main.exe"; }
1109 #else
1110     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
1111 #endif
1112
1113     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1114     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1115
1116     let lib_paths = libraryPaths dflags
1117     let lib_path_opts = map ("-L"++) lib_paths
1118
1119     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1120
1121 #ifdef darwin_TARGET_OS
1122     pkg_framework_paths <- getPackageFrameworkPath dflags dep_packages
1123     let pkg_framework_path_opts = map ("-F"++) pkg_framework_paths
1124
1125     let framework_paths = frameworkPaths dflags
1126         framework_path_opts = map ("-F"++) framework_paths
1127
1128     pkg_frameworks <- getPackageFrameworks dflags dep_packages
1129     let pkg_framework_opts = concat [ ["-framework", fw] | fw <- pkg_frameworks ]
1130     
1131     let frameworks = cmdlineFrameworks dflags
1132         framework_opts = concat [ ["-framework", fw] | fw <- reverse frameworks ]
1133          -- reverse because they're added in reverse order from the cmd line
1134 #endif
1135
1136         -- probably _stub.o files
1137     extra_ld_inputs <- readIORef v_Ld_inputs
1138
1139         -- opts from -optl-<blah> (including -l<blah> options)
1140     let extra_ld_opts = getOpts dflags opt_l
1141
1142     let ways = wayNames dflags
1143
1144     -- Here are some libs that need to be linked at the *end* of
1145     -- the command line, because they contain symbols that are referred to
1146     -- by the RTS.  We can't therefore use the ordinary way opts for these.
1147     let
1148         debug_opts | WayDebug `elem` ways = [ 
1149 #if defined(HAVE_LIBBFD)
1150                         "-lbfd", "-liberty"
1151 #endif
1152                          ]
1153                    | otherwise            = []
1154
1155     let
1156         thread_opts | WayThreaded `elem` ways = [ 
1157 #if !defined(mingw32_TARGET_OS) && !defined(freebsd_TARGET_OS)
1158                         "-lpthread"
1159 #endif
1160 #if defined(osf3_TARGET_OS)
1161                         , "-lexc"
1162 #endif
1163                         ]
1164                     | otherwise               = []
1165
1166     let (md_c_flags, _) = machdepCCOpts dflags
1167     SysTools.runLink dflags ( 
1168                        [ SysTools.Option verb
1169                        , SysTools.Option "-o"
1170                        , SysTools.FileOption "" output_fn
1171                        ]
1172                       ++ map SysTools.Option (
1173                          md_c_flags
1174                       ++ o_files
1175                       ++ extra_ld_inputs
1176                       ++ lib_path_opts
1177                       ++ extra_ld_opts
1178 #ifdef darwin_TARGET_OS
1179                       ++ framework_path_opts
1180                       ++ framework_opts
1181 #endif
1182                       ++ pkg_lib_path_opts
1183                       ++ pkg_link_opts
1184 #ifdef darwin_TARGET_OS
1185                       ++ pkg_framework_path_opts
1186                       ++ pkg_framework_opts
1187 #endif
1188                       ++ debug_opts
1189                       ++ thread_opts
1190                     ))
1191
1192     -- parallel only: move binary to another dir -- HWL
1193     when (WayPar `elem` ways)
1194          (do success <- runPhase_MoveBinary output_fn
1195              if success then return ()
1196                         else throwDyn (InstallationError ("cannot move binary to PVM dir")))
1197
1198 -----------------------------------------------------------------------------
1199 -- Making a DLL (only for Win32)
1200
1201 doMkDLL :: DynFlags -> [String] -> [PackageId] -> IO ()
1202 doMkDLL dflags o_files dep_packages = do
1203     let verb = getVerbFlag dflags
1204     let static = opt_Static
1205     let no_hs_main = dopt Opt_NoHsMain dflags
1206     let o_file = outputFile dflags
1207     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
1208
1209     pkg_lib_paths <- getPackageLibraryPath dflags dep_packages
1210     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
1211
1212     let lib_paths = libraryPaths dflags
1213     let lib_path_opts = map ("-L"++) lib_paths
1214
1215     pkg_link_opts <- getPackageLinkOpts dflags dep_packages
1216
1217         -- probably _stub.o files
1218     extra_ld_inputs <- readIORef v_Ld_inputs
1219
1220         -- opts from -optdll-<blah>
1221     let extra_ld_opts = getOpts dflags opt_dll 
1222
1223     let pstate = pkgState dflags
1224         rts_id | ExtPackage id <- rtsPackageId pstate = id
1225                | otherwise = panic "staticLink: rts package missing"
1226         base_id | ExtPackage id <- basePackageId pstate = id
1227                 | otherwise = panic "staticLink: base package missing"
1228         rts_pkg  = getPackageDetails pstate rts_id
1229         base_pkg = getPackageDetails pstate base_id
1230
1231     let extra_os = if static || no_hs_main
1232                    then []
1233                    else [ head (libraryDirs rts_pkg) ++ "/Main.dll_o",
1234                           head (libraryDirs base_pkg) ++ "/PrelMain.dll_o" ]
1235
1236     let (md_c_flags, _) = machdepCCOpts dflags
1237     SysTools.runMkDLL dflags
1238          ([ SysTools.Option verb
1239           , SysTools.Option "-o"
1240           , SysTools.FileOption "" output_fn
1241           ]
1242          ++ map SysTools.Option (
1243             md_c_flags
1244          ++ o_files
1245          ++ extra_os
1246          ++ [ "--target=i386-mingw32" ]
1247          ++ extra_ld_inputs
1248          ++ lib_path_opts
1249          ++ extra_ld_opts
1250          ++ pkg_lib_path_opts
1251          ++ pkg_link_opts
1252          ++ (if "--def" `elem` (concatMap words extra_ld_opts)
1253                then [ "" ]
1254                else [ "--export-all" ])
1255         ))
1256
1257 -- -----------------------------------------------------------------------------
1258 -- Running CPP
1259
1260 doCpp :: DynFlags -> Bool -> Bool -> FilePath -> FilePath -> IO ()
1261 doCpp dflags raw include_cc_opts input_fn output_fn = do
1262     let hscpp_opts = getOpts dflags opt_P
1263     let cmdline_include_paths = includePaths dflags
1264
1265     pkg_include_dirs <- getPackageIncludePath dflags []
1266     let include_paths = foldr (\ x xs -> "-I" : x : xs) []
1267                           (cmdline_include_paths ++ pkg_include_dirs)
1268
1269     let verb = getVerbFlag dflags
1270
1271     let cc_opts
1272           | not include_cc_opts = []
1273           | otherwise           = (optc ++ md_c_flags)
1274                 where 
1275                       optc = getOpts dflags opt_c
1276                       (md_c_flags, _) = machdepCCOpts dflags
1277
1278     let cpp_prog args | raw       = SysTools.runCpp dflags args
1279                       | otherwise = SysTools.runCc dflags (SysTools.Option "-E" : args)
1280
1281     let target_defs = 
1282           [ "-D" ++ HOST_OS     ++ "_BUILD_OS=1",
1283             "-D" ++ HOST_ARCH   ++ "_BUILD_ARCH=1",
1284             "-D" ++ TARGET_OS   ++ "_HOST_OS=1",
1285             "-D" ++ TARGET_ARCH ++ "_HOST_ARCH=1" ]
1286         -- remember, in code we *compile*, the HOST is the same our TARGET,
1287         -- and BUILD is the same as our HOST.
1288
1289     cpp_prog       ([SysTools.Option verb]
1290                     ++ map SysTools.Option include_paths
1291                     ++ map SysTools.Option hsSourceCppOpts
1292                     ++ map SysTools.Option hscpp_opts
1293                     ++ map SysTools.Option cc_opts
1294                     ++ map SysTools.Option target_defs
1295                     ++ [ SysTools.Option     "-x"
1296                        , SysTools.Option     "c"
1297                        , SysTools.Option     input_fn
1298         -- We hackily use Option instead of FileOption here, so that the file
1299         -- name is not back-slashed on Windows.  cpp is capable of
1300         -- dealing with / in filenames, so it works fine.  Furthermore
1301         -- if we put in backslashes, cpp outputs #line directives
1302         -- with *double* backslashes.   And that in turn means that
1303         -- our error messages get double backslashes in them.
1304         -- In due course we should arrange that the lexer deals
1305         -- with these \\ escapes properly.
1306                        , SysTools.Option     "-o"
1307                        , SysTools.FileOption "" output_fn
1308                        ])
1309
1310 cHaskell1Version = "5" -- i.e., Haskell 98
1311
1312 -- Default CPP defines in Haskell source
1313 hsSourceCppOpts =
1314         [ "-D__HASKELL1__="++cHaskell1Version
1315         , "-D__GLASGOW_HASKELL__="++cProjectVersionInt                          
1316         , "-D__HASKELL98__"
1317         , "-D__CONCURRENT_HASKELL__"
1318         ]
1319
1320 -----------------------------------------------------------------------------
1321 -- Reading OPTIONS pragmas
1322
1323 getOptionsFromSource 
1324         :: String               -- input file
1325         -> IO [String]          -- options, if any
1326 getOptionsFromSource file
1327   = do h <- openFile file ReadMode
1328        look h `finally` hClose h
1329   where
1330         look h = do
1331             r <- tryJust ioErrors (hGetLine h)
1332             case r of
1333               Left e | isEOFError e -> return []
1334                      | otherwise    -> ioError e
1335               Right l' -> do
1336                 let l = removeSpaces l'
1337                 case () of
1338                     () | null l -> look h
1339                        | prefixMatch "#" l -> look h
1340                        | prefixMatch "{-# LINE" l -> look h   -- -}
1341                        | Just opts <- matchOptions l
1342                         -> do rest <- look h
1343                               return (opts ++ rest)
1344                        | otherwise -> return []
1345
1346 getOptionsFromStringBuffer :: StringBuffer -> [(Int,String)]
1347 getOptionsFromStringBuffer buffer@(StringBuffer _ len# _) = 
1348   let 
1349         ls = lines (lexemeToString buffer (I# len#))  -- lazy, so it's ok
1350   in
1351   look 1 ls
1352   where
1353         look i [] = []
1354         look i (l':ls) = do
1355             let l = removeSpaces l'
1356             case () of
1357                 () | null l -> look (i+1) ls
1358                    | prefixMatch "#" l -> look (i+1) ls
1359                    | prefixMatch "{-# LINE" l -> look (i+1) ls   -- -}
1360                    | Just opts <- matchOptions l
1361                         -> zip (repeat i) opts ++ look (i+1) ls
1362                    | otherwise -> []
1363
1364 -- detect {-# OPTIONS_GHC ... #-}.  For the time being, we accept OPTIONS
1365 -- instead of OPTIONS_GHC, but that is deprecated.
1366 matchOptions s
1367   | Just s1 <- maybePrefixMatch "{-#" s -- -} 
1368   = matchOptions1 (removeSpaces s1)
1369   | otherwise
1370   = Nothing
1371  where
1372   matchOptions1 s
1373     | Just s2 <- maybePrefixMatch "OPTIONS" s
1374     = case () of
1375         _ | Just s3 <- maybePrefixMatch "_GHC" s2, not (is_ident (head s3))
1376           -> matchOptions2 s3
1377           | not (is_ident (head s2))
1378           -> matchOptions2 s2
1379           | otherwise
1380           -> Just []  -- OPTIONS_anything is ignored, not treated as start of source
1381     | Just s2 <- maybePrefixMatch "INCLUDE" s, not (is_ident (head s2)),
1382       Just s3 <- maybePrefixMatch "}-#" (reverse s2)
1383     = Just ["-#include", removeSpaces (reverse s3)]
1384     | otherwise = Nothing
1385   matchOptions2 s
1386     | Just s3 <- maybePrefixMatch "}-#" (reverse s) = Just (words (reverse s3))
1387     | otherwise = Nothing
1388
1389
1390 optionsErrorMsgs :: [String] -> [(Int,String)] -> FilePath -> Messages
1391 optionsErrorMsgs unhandled_flags flags_lines filename
1392   = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
1393   where
1394         unhandled_flags_lines = [ (l,f) | f <- unhandled_flags, 
1395                                           (l,f') <- flags_lines, f == f' ]
1396         mkMsg (line,flag) = 
1397             ErrUtils.mkPlainErrMsg (srcLocSpan loc) $
1398                 text "unknown flag in  {-# OPTIONS #-} pragma:" <+> text flag
1399           where
1400                 loc = mkSrcLoc (mkFastString filename) line 0
1401                 -- ToDo: we need a better SrcSpan here
1402
1403 -- -----------------------------------------------------------------------------
1404 -- Misc.
1405
1406 hscNextPhase :: DynFlags -> HscSource -> HscTarget -> Phase
1407 hscNextPhase dflags HsBootFile hsc_lang  =  StopLn
1408 hscNextPhase dflags other hsc_lang = 
1409   case hsc_lang of
1410         HscC -> HCc
1411         HscAsm | dopt Opt_SplitObjs dflags -> SplitMangle
1412                | otherwise -> As
1413         HscNothing     -> StopLn
1414         HscInterpreted -> StopLn
1415         _other         -> StopLn
1416
1417
1418 hscMaybeAdjustTarget :: DynFlags -> Phase -> HscSource -> HscTarget -> HscTarget
1419 hscMaybeAdjustTarget dflags stop HsBootFile current_hsc_lang 
1420   = HscNothing          -- No output (other than Foo.hi-boot) for hs-boot files
1421 hscMaybeAdjustTarget dflags stop other current_hsc_lang 
1422   = hsc_lang 
1423   where
1424         keep_hc = dopt Opt_KeepHcFiles dflags
1425         hsc_lang
1426                 -- don't change the lang if we're interpreting
1427                  | current_hsc_lang == HscInterpreted = current_hsc_lang
1428
1429                 -- force -fvia-C if we are being asked for a .hc file
1430                  | HCc <- stop = HscC
1431                  | keep_hc     = HscC
1432                 -- otherwise, stick to the plan
1433                  | otherwise = current_hsc_lang
1434
1435 GLOBAL_VAR(v_Split_info, ("",0), (String,Int))
1436         -- The split prefix and number of files