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