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