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