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