Debian Codegraph @

src-bin-861/Clash/Main.hs

raw
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE NondecreasingIndentation #-}
3
4 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
5
6 -----------------------------------------------------------------------------
7 --
8 -- GHC Driver program
9 --
10 -- (c) The University of Glasgow 2005
11 --
12 -----------------------------------------------------------------------------
13
14 module Clash.Main (defaultMain, defaultMainWithAction) where
15
16 -- For Int/Word size
17 #include "MachDeps.h"
18
19 -- The official GHC API
20 import qualified GHC
21 import GHC ( -- DynFlags(..), HscTarget(..),
22 -- GhcMode(..), GhcLink(..),
23 Ghc, GhcMonad(..),
24 LoadHowMuch(..) )
25 import CmdLineParser
26
27 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
28 import LoadIface ( showIface )
29 import HscMain ( newHscEnv )
30 import DriverPipeline ( oneShot, compileFile )
31 import DriverMkDepend ( doMkDependHS )
32 import DriverBkp ( doBackpack )
33 #if defined(GHCI)
34 import Clash.GHCi.UI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings )
35 #endif
36
37 -- Frontend plugins
38 #if defined(GHCI)
39 import DynamicLoading ( loadFrontendPlugin )
40 import Plugins
41 #else
42 import DynamicLoading ( pluginError )
43 #endif
44 import Module ( ModuleName )
45
46
47 -- Various other random stuff that we need
48 import GHC.HandleEncoding
49 import Config
50 import Constants
51 import HscTypes
52 import Packages ( pprPackages, pprPackagesSimple )
53 import DriverPhases
54 import BasicTypes ( failed )
55 import DynFlags hiding (WarnReason(..))
56 import EnumSet as EnumSet
57 import ErrUtils
58 import FastString
59 import Outputable
60 import SrcLoc
61 import Util
62 import Panic
63 import UniqSupply
64 import MonadUtils ( liftIO )
65 import DynamicLoading ( initializePlugins )
66
67 -- Imports for --abi-hash
68 import LoadIface ( loadUserInterface )
69 import Module ( mkModuleName )
70 import Finder ( findImportedModule, cannotFindModule )
71 import TcRnMonad ( initIfaceCheck )
72 import Binary ( openBinMem, put_ )
73 import BinFingerprint ( fingerprintBinMem )
74
75 -- Standard Haskell libraries
76 import System.IO
77 import System.Environment
78 import System.Exit
79 import System.FilePath
80 import Control.Monad
81 import Data.Char
82 import Data.List
83 import Data.Proxy
84 import Data.Maybe
85
86 -- clash additions
87 import Paths_clash_ghc
88 import Clash.GHCi.UI (makeHDL)
89 import Exception (gcatch)
90 import Data.IORef (IORef, newIORef, readIORef, modifyIORef')
91 import qualified Data.Version (showVersion)
92
93 import Clash.Backend (Backend)
94 import Clash.Backend.SystemVerilog (SystemVerilogState)
95 import Clash.Backend.VHDL (VHDLState)
96 import Clash.Backend.Verilog (VerilogState)
97 import Clash.Driver.Types
98 (ClashOpts (..), defClashOpts)
99 import Clash.GHC.ClashFlags
100 import Clash.Util (clashLibVersion)
101 import Clash.GHC.LoadModules (ghcLibDir, setWantedLanguageExtensions)
102 import Clash.GHC.Util (handleClashException)
103
104 -----------------------------------------------------------------------------
105 -- ToDo:
106
107 -- time commands when run with -v
108 -- user ways
109 -- Win32 support: proper signal handling
110 -- reading the package configuration file is too slow
111 -- -K<size>
112
113 -----------------------------------------------------------------------------
114 -- GHC's command-line interface
115
116 defaultMain :: [String] -> IO ()
117 defaultMain = defaultMainWithAction (return ())
118
119 defaultMainWithAction :: Ghc () -> [String] -> IO ()
120 defaultMainWithAction startAction = flip withArgs $ do
121 initGCStatistics -- See Note [-Bsymbolic and hooks]
122 hSetBuffering stdout LineBuffering
123 hSetBuffering stderr LineBuffering
124
125 configureHandleEncoding
126 GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
127 -- 1. extract the -B flag from the args
128 argv0 <- getArgs
129
130 -- let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
131 -- mbMinusB | null minusB_args = Nothing
132 -- | otherwise = Just (drop 2 (last minusB_args))
133
134 -- let argv2 = map (mkGeneralLocated "on the commandline") argv1
135 libDir <- ghcLibDir
136
137 let argv1 = map (mkGeneralLocated "on the commandline") argv0
138 r <- newIORef defClashOpts
139 (argv2, clashFlagWarnings) <- parseClashFlags r argv1
140
141 -- 2. Parse the "mode" flags (--make, --interactive etc.)
142 -- (mode, argv3, flagWarnings) <- parseModeFlags argv2
143 (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
144 let flagWarnings = modeFlagWarnings ++ clashFlagWarnings
145
146 -- If all we want to do is something like showing the version number
147 -- then do it now, before we start a GHC session etc. This makes
148 -- getting basic information much more resilient.
149
150 -- In particular, if we wait until later before giving the version
151 -- number then bootstrapping gets confused, as it tries to find out
152 -- what version of GHC it's using before package.conf exists, so
153 -- starting the session fails.
154 case mode of
155 Left preStartupMode ->
156 do case preStartupMode of
157 ShowSupportedExtensions -> showSupportedExtensions
158 ShowVersion -> showVersion
159 ShowNumVersion -> putStrLn cProjectVersion
160 ShowOptions isInteractive -> showOptions isInteractive r
161 Right postStartupMode ->
162 -- start our GHC session
163 GHC.runGhc (Just libDir) $ do
164
165 dflags <- GHC.getSessionDynFlags
166 let dflagsExtra = setWantedLanguageExtensions dflags
167
168 ghcTyLitNormPlugin = GHC.mkModuleName "GHC.TypeLits.Normalise"
169 ghcTyLitExtrPlugin = GHC.mkModuleName "GHC.TypeLits.Extra.Solver"
170 ghcTyLitKNPlugin = GHC.mkModuleName "GHC.TypeLits.KnownNat.Solver"
171 dflagsExtra1 = dflagsExtra
172 { DynFlags.pluginModNames = nub $
173 ghcTyLitNormPlugin : ghcTyLitExtrPlugin :
174 ghcTyLitKNPlugin :
175 DynFlags.pluginModNames dflagsExtra
176 }
177
178 case postStartupMode of
179 Left preLoadMode ->
180 liftIO $ do
181 case preLoadMode of
182 ShowInfo -> showInfo dflagsExtra1
183 ShowGhcUsage -> showGhcUsage dflagsExtra1
184 ShowGhciUsage -> showGhciUsage dflagsExtra1
185 PrintWithDynFlags f -> putStrLn (f dflagsExtra1)
186 Right postLoadMode ->
187 main' postLoadMode dflagsExtra1 argv3 flagWarnings startAction r
188
189 main' :: PostLoadMode -> DynFlags -> [Located String] -> [Warn]
190 -> Ghc () -> IORef ClashOpts
191 -> Ghc ()
192 main' postLoadMode dflags0 args flagWarnings startAction clashOpts = do
193 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
194 -- can be further adjusted on a module by module basis, using only
195 -- the -fvia-C and -fasm flags. If the default HscTarget is not
196 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
197 let dflt_target = hscTarget dflags0
198 (mode, lang, link)
199 = case postLoadMode of
200 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
201 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
202 DoMake -> (CompManager, dflt_target, LinkBinary)
203 DoBackpack -> (CompManager, dflt_target, LinkBinary)
204 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
205 DoAbiHash -> (OneShot, dflt_target, LinkBinary)
206 DoVHDL -> (CompManager, HscNothing, NoLink)
207 DoVerilog -> (CompManager, HscNothing, NoLink)
208 DoSystemVerilog -> (CompManager, HscNothing, NoLink)
209 _ -> (OneShot, dflt_target, LinkBinary)
210
211 let dflags1 = dflags0{ ghcMode = mode,
212 hscTarget = lang,
213 ghcLink = link,
214 verbosity = case postLoadMode of
215 DoEval _ -> 0
216 _other -> 1
217 }
218
219 -- turn on -fimplicit-import-qualified for GHCi now, so that it
220 -- can be overriden from the command-line
221 -- XXX: this should really be in the interactive DynFlags, but
222 -- we don't set that until later in interactiveUI
223 -- We also set -fignore-optim-changes and -fignore-hpc-changes,
224 -- which are program-level options. Again, this doesn't really
225 -- feel like the right place to handle this, but we don't have
226 -- a great story for the moment.
227 dflags2 | DoInteractive <- postLoadMode = def_ghci_flags
228 | DoEval _ <- postLoadMode = def_ghci_flags
229 | otherwise = dflags1
230 where def_ghci_flags = dflags1 `gopt_set` Opt_ImplicitImportQualified
231 `gopt_set` Opt_IgnoreOptimChanges
232 `gopt_set` Opt_IgnoreHpcChanges
233
234 -- The rest of the arguments are "dynamic"
235 -- Leftover ones are presumably files
236 (dflags3, fileish_args, dynamicFlagWarnings) <-
237 GHC.parseDynamicFlags dflags2 args
238
239 -- Propagate -Werror to Clash
240 liftIO . modifyIORef' clashOpts $ \opts ->
241 opts { opt_werror = EnumSet.member Opt_WarnIsError (generalFlags dflags3) }
242
243 let dflags4 = case lang of
244 HscInterpreted | not (gopt Opt_ExternalInterpreter dflags3) ->
245 let platform = targetPlatform dflags3
246 dflags3a = updateWays $ dflags3 { ways = interpWays }
247 dflags3b = foldl gopt_set dflags3a
248 $ concatMap (wayGeneralFlags platform)
249 interpWays
250 dflags3c = foldl gopt_unset dflags3b
251 $ concatMap (wayUnsetGeneralFlags platform)
252 interpWays
253 in dflags3c
254 _ ->
255 dflags3
256
257 GHC.prettyPrintGhcErrors dflags4 $ do
258
259 let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
260
261 handleSourceError (\e -> do
262 GHC.printException e
263 liftIO $ exitWith (ExitFailure 1)) $ do
264 liftIO $ handleFlagWarnings dflags4 flagWarnings'
265
266 liftIO $ showBanner postLoadMode dflags4
267
268 let
269 -- To simplify the handling of filepaths, we normalise all filepaths right
270 -- away - e.g., for win32 platforms, backslashes are converted
271 -- into forward slashes.
272 normal_fileish_paths = map (normalise . unLoc) fileish_args
273 (srcs, objs) = partition_args normal_fileish_paths [] []
274
275 dflags5 = dflags4 { ldInputs = map (FileOption "") objs
276 ++ ldInputs dflags4 }
277
278 -- we've finished manipulating the DynFlags, update the session
279 _ <- GHC.setSessionDynFlags dflags5
280 dflags6 <- GHC.getSessionDynFlags
281 hsc_env <- GHC.getSession
282
283 ---------------- Display configuration -----------
284 case verbosity dflags6 of
285 v | v == 4 -> liftIO $ dumpPackagesSimple dflags6
286 | v >= 5 -> liftIO $ dumpPackages dflags6
287 | otherwise -> return ()
288
289 liftIO $ initUniqSupply (initialUnique dflags6) (uniqueIncrement dflags6)
290 ---------------- Final sanity checking -----------
291 liftIO $ checkOptions postLoadMode dflags6 srcs objs
292
293 ---------------- Do the business -----------
294 handleSourceError (\e -> do
295 GHC.printException e
296 liftIO $ exitWith (ExitFailure 1)) $ do
297 clashOpts' <- liftIO (readIORef clashOpts)
298 let clash fun = gcatch (fun startAction clashOpts srcs) (handleClashException dflags6 clashOpts')
299 case postLoadMode of
300 ShowInterface f -> liftIO $ doShowIface dflags6 f
301 DoMake -> doMake srcs
302 DoMkDependHS -> doMkDependHS (map fst srcs)
303 StopBefore p -> liftIO (oneShot hsc_env p srcs)
304 DoInteractive -> ghciUI clashOpts hsc_env dflags6 srcs Nothing
305 DoEval exprs -> ghciUI clashOpts hsc_env dflags6 srcs $ Just $ reverse exprs
306 DoAbiHash -> abiHash (map fst srcs)
307 ShowPackages -> liftIO $ showPackages dflags6
308 DoFrontend f -> doFrontend f srcs
309 DoBackpack -> doBackpack (map fst srcs)
310 DoVHDL -> clash makeVHDL
311 DoVerilog -> clash makeVerilog
312 DoSystemVerilog -> clash makeSystemVerilog
313
314 liftIO $ dumpFinalStats dflags6
315
316 ghciUI :: IORef ClashOpts -> HscEnv -> DynFlags -> [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc ()
317 #if !defined(GHCI)
318 ghciUI _ _ _ _ _ = throwGhcException (CmdLineError "not built for interactive use")
319 #else
320 ghciUI opts hsc_env dflags0 srcs maybe_expr = do
321 dflags1 <- liftIO (initializePlugins hsc_env dflags0)
322 _ <- GHC.setSessionDynFlags dflags1
323 interactiveUI (defaultGhciSettings opts) srcs maybe_expr
324 #endif
325
326 -- -----------------------------------------------------------------------------
327 -- Splitting arguments into source files and object files. This is where we
328 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
329 -- file indicating the phase specified by the -x option in force, if any.
330
331 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
332 -> ([(String, Maybe Phase)], [String])
333 partition_args [] srcs objs = (reverse srcs, reverse objs)
334 partition_args ("-x":suff:args) srcs objs
335 | "none" <- suff = partition_args args srcs objs
336 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
337 | otherwise = partition_args rest (these_srcs ++ srcs) objs
338 where phase = startPhase suff
339 (slurp,rest) = break (== "-x") args
340 these_srcs = zip slurp (repeat (Just phase))
341 partition_args (arg:args) srcs objs
342 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
343 | otherwise = partition_args args srcs (arg:objs)
344
345 {-
346 We split out the object files (.o, .dll) and add them
347 to ldInputs for use by the linker.
348
349 The following things should be considered compilation manager inputs:
350
351 - haskell source files (strings ending in .hs, .lhs or other
352 haskellish extension),
353
354 - module names (not forgetting hierarchical module names),
355
356 - things beginning with '-' are flags that were not recognised by
357 the flag parser, and we want them to generate errors later in
358 checkOptions, so we class them as source files (#5921)
359
360 - and finally we consider everything without an extension to be
361 a comp manager input, as shorthand for a .hs or .lhs filename.
362
363 Everything else is considered to be a linker object, and passed
364 straight through to the linker.
365 -}
366 looks_like_an_input :: String -> Bool
367 looks_like_an_input m = isSourceFilename m
368 || looksLikeModuleName m
369 || "-" `isPrefixOf` m
370 || not (hasExtension m)
371
372 -- -----------------------------------------------------------------------------
373 -- Option sanity checks
374
375 -- | Ensure sanity of options.
376 --
377 -- Throws 'UsageError' or 'CmdLineError' if not.
378 checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
379 -- Final sanity checking before kicking off a compilation (pipeline).
380 checkOptions mode dflags srcs objs = do
381 -- Complain about any unknown flags
382 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
383 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
384
385 when (notNull (filter wayRTSOnly (ways dflags))
386 && isInterpretiveMode mode) $
387 hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
388
389 -- -prof and --interactive are not a good combination
390 when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays)
391 && isInterpretiveMode mode
392 && not (gopt Opt_ExternalInterpreter dflags)) $
393 do throwGhcException (UsageError
394 "-fexternal-interpreter is required when using --interactive with a non-standard way (-prof, -static, or -dynamic).")
395 -- -ohi sanity check
396 if (isJust (outputHi dflags) &&
397 (isCompManagerMode mode || srcs `lengthExceeds` 1))
398 then throwGhcException (UsageError "-ohi can only be used when compiling a single source file")
399 else do
400
401 -- -o sanity checking
402 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
403 && not (isLinkMode mode))
404 then throwGhcException (UsageError "can't apply -o to multiple source files")
405 else do
406
407 let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
408
409 when (not_linking && not (null objs)) $
410 hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
411
412 -- Check that there are some input files
413 -- (except in the interactive case)
414 if null srcs && (null objs || not_linking) && needsInputsMode mode
415 then throwGhcException (UsageError "no input files")
416 else do
417
418 case mode of
419 StopBefore HCc | hscTarget dflags /= HscC
420 -> throwGhcException $ UsageError $
421 "the option -C is only available with an unregisterised GHC"
422 _ -> return ()
423
424 -- Verify that output files point somewhere sensible.
425 verifyOutputFiles dflags
426
427 -- Compiler output options
428
429 -- Called to verify that the output files point somewhere valid.
430 --
431 -- The assumption is that the directory portion of these output
432 -- options will have to exist by the time 'verifyOutputFiles'
433 -- is invoked.
434 --
435 -- We create the directories for -odir, -hidir, -outputdir etc. ourselves if
436 -- they don't exist, so don't check for those here (#2278).
437 verifyOutputFiles :: DynFlags -> IO ()
438 verifyOutputFiles dflags = do
439 let ofile = outputFile dflags
440 when (isJust ofile) $ do
441 let fn = fromJust ofile
442 flg <- doesDirNameExist fn
443 when (not flg) (nonExistentDir "-o" fn)
444 let ohi = outputHi dflags
445 when (isJust ohi) $ do
446 let hi = fromJust ohi
447 flg <- doesDirNameExist hi
448 when (not flg) (nonExistentDir "-ohi" hi)
449 where
450 nonExistentDir flg dir =
451 throwGhcException (CmdLineError ("error: directory portion of " ++
452 show dir ++ " does not exist (used with " ++
453 show flg ++ " option.)"))
454
455 -----------------------------------------------------------------------------
456 -- GHC modes of operation
457
458 type Mode = Either PreStartupMode PostStartupMode
459 type PostStartupMode = Either PreLoadMode PostLoadMode
460
461 data PreStartupMode
462 = ShowVersion -- ghc -V/--version
463 | ShowNumVersion -- ghc --numeric-version
464 | ShowSupportedExtensions -- ghc --supported-extensions
465 | ShowOptions Bool {- isInteractive -} -- ghc --show-options
466
467 showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode
468 showVersionMode = mkPreStartupMode ShowVersion
469 showNumVersionMode = mkPreStartupMode ShowNumVersion
470 showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
471 showOptionsMode = mkPreStartupMode (ShowOptions False)
472
473 mkPreStartupMode :: PreStartupMode -> Mode
474 mkPreStartupMode = Left
475
476 isShowVersionMode :: Mode -> Bool
477 isShowVersionMode (Left ShowVersion) = True
478 isShowVersionMode _ = False
479
480 isShowNumVersionMode :: Mode -> Bool
481 isShowNumVersionMode (Left ShowNumVersion) = True
482 isShowNumVersionMode _ = False
483
484 data PreLoadMode
485 = ShowGhcUsage -- ghc -?
486 | ShowGhciUsage -- ghci -?
487 | ShowInfo -- ghc --info
488 | PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
489
490 showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
491 showGhcUsageMode = mkPreLoadMode ShowGhcUsage
492 showGhciUsageMode = mkPreLoadMode ShowGhciUsage
493 showInfoMode = mkPreLoadMode ShowInfo
494
495 printSetting :: String -> Mode
496 printSetting k = mkPreLoadMode (PrintWithDynFlags f)
497 where f dflags = fromMaybe (panic ("Setting not found: " ++ show k))
498 $ lookup k (compilerInfo dflags)
499
500 mkPreLoadMode :: PreLoadMode -> Mode
501 mkPreLoadMode = Right . Left
502
503 isShowGhcUsageMode :: Mode -> Bool
504 isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
505 isShowGhcUsageMode _ = False
506
507 isShowGhciUsageMode :: Mode -> Bool
508 isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
509 isShowGhciUsageMode _ = False
510
511 data PostLoadMode
512 = ShowInterface FilePath -- ghc --show-iface
513 | DoMkDependHS -- ghc -M
514 | StopBefore Phase -- ghc -E | -C | -S
515 -- StopBefore StopLn is the default
516 | DoMake -- ghc --make
517 | DoBackpack -- ghc --backpack foo.bkp
518 | DoInteractive -- ghc --interactive
519 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
520 | DoAbiHash -- ghc --abi-hash
521 | ShowPackages -- ghc --show-packages
522 | DoFrontend ModuleName -- ghc --frontend Plugin.Module
523 | DoVHDL -- ghc --vhdl
524 | DoVerilog -- ghc --verilog
525 | DoSystemVerilog -- ghc --systemverilog
526
527 doMkDependHSMode, doMakeMode, doInteractiveMode,
528 doAbiHashMode, showPackagesMode, doVHDLMode, doVerilogMode,
529 doSystemVerilogMode :: Mode
530 doMkDependHSMode = mkPostLoadMode DoMkDependHS
531 doMakeMode = mkPostLoadMode DoMake
532 doInteractiveMode = mkPostLoadMode DoInteractive
533 doAbiHashMode = mkPostLoadMode DoAbiHash
534 showPackagesMode = mkPostLoadMode ShowPackages
535 doVHDLMode = mkPostLoadMode DoVHDL
536 doVerilogMode = mkPostLoadMode DoVerilog
537 doSystemVerilogMode = mkPostLoadMode DoSystemVerilog
538
539 showInterfaceMode :: FilePath -> Mode
540 showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
541
542 stopBeforeMode :: Phase -> Mode
543 stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
544
545 doEvalMode :: String -> Mode
546 doEvalMode str = mkPostLoadMode (DoEval [str])
547
548 doFrontendMode :: String -> Mode
549 doFrontendMode str = mkPostLoadMode (DoFrontend (mkModuleName str))
550
551 doBackpackMode :: Mode
552 doBackpackMode = mkPostLoadMode DoBackpack
553
554 mkPostLoadMode :: PostLoadMode -> Mode
555 mkPostLoadMode = Right . Right
556
557 isDoInteractiveMode :: Mode -> Bool
558 isDoInteractiveMode (Right (Right DoInteractive)) = True
559 isDoInteractiveMode _ = False
560
561 isStopLnMode :: Mode -> Bool
562 isStopLnMode (Right (Right (StopBefore StopLn))) = True
563 isStopLnMode _ = False
564
565 isDoMakeMode :: Mode -> Bool
566 isDoMakeMode (Right (Right DoMake)) = True
567 isDoMakeMode _ = False
568
569 isDoEvalMode :: Mode -> Bool
570 isDoEvalMode (Right (Right (DoEval _))) = True
571 isDoEvalMode _ = False
572
573 #if defined(GHCI)
574 isInteractiveMode :: PostLoadMode -> Bool
575 isInteractiveMode DoInteractive = True
576 isInteractiveMode _ = False
577 #endif
578
579 -- isInterpretiveMode: byte-code compiler involved
580 isInterpretiveMode :: PostLoadMode -> Bool
581 isInterpretiveMode DoInteractive = True
582 isInterpretiveMode (DoEval _) = True
583 isInterpretiveMode _ = False
584
585 needsInputsMode :: PostLoadMode -> Bool
586 needsInputsMode DoMkDependHS = True
587 needsInputsMode (StopBefore _) = True
588 needsInputsMode DoMake = True
589 needsInputsMode DoVHDL = True
590 needsInputsMode DoVerilog = True
591 needsInputsMode DoSystemVerilog = True
592 needsInputsMode _ = False
593
594 -- True if we are going to attempt to link in this mode.
595 -- (we might not actually link, depending on the GhcLink flag)
596 isLinkMode :: PostLoadMode -> Bool
597 isLinkMode (StopBefore StopLn) = True
598 isLinkMode DoMake = True
599 isLinkMode DoInteractive = True
600 isLinkMode (DoEval _) = True
601 isLinkMode _ = False
602
603 isCompManagerMode :: PostLoadMode -> Bool
604 isCompManagerMode DoMake = True
605 isCompManagerMode DoInteractive = True
606 isCompManagerMode (DoEval _) = True
607 isCompManagerMode DoVHDL = True
608 isCompManagerMode DoVerilog = True
609 isCompManagerMode DoSystemVerilog = True
610 isCompManagerMode _ = False
611
612 -- -----------------------------------------------------------------------------
613 -- Parsing the mode flag
614
615 parseModeFlags :: [Located String]
616 -> IO (Mode,
617 [Located String],
618 [Warn])
619 parseModeFlags args = do
620 let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
621 runCmdLine (processArgs mode_flags args)
622 (Nothing, [], [])
623 mode = case mModeFlag of
624 Nothing -> doMakeMode
625 Just (m, _) -> m
626
627 -- See Note [Handling errors when parsing commandline flags]
628 unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $
629 map (("on the commandline", )) $ map (unLoc . errMsg) errs1 ++ errs2
630
631 return (mode, flags' ++ leftover, warns)
632
633 type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String])
634 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
635 -- so we collect the new ones and return them.
636
637 mode_flags :: [Flag ModeM]
638 mode_flags =
639 [ ------- help / version ----------------------------------------------
640 defFlag "?" (PassFlag (setMode showGhcUsageMode))
641 , defFlag "-help" (PassFlag (setMode showGhcUsageMode))
642 , defFlag "V" (PassFlag (setMode showVersionMode))
643 , defFlag "-version" (PassFlag (setMode showVersionMode))
644 , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode))
645 , defFlag "-info" (PassFlag (setMode showInfoMode))
646 , defFlag "-show-options" (PassFlag (setMode showOptionsMode))
647 , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode))
648 , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
649 , defFlag "-show-packages" (PassFlag (setMode showPackagesMode))
650 ] ++
651 [ defFlag k' (PassFlag (setMode (printSetting k)))
652 | k <- ["Project version",
653 "Project Git commit id",
654 "Booter version",
655 "Stage",
656 "Build platform",
657 "Host platform",
658 "Target platform",
659 "Have interpreter",
660 "Object splitting supported",
661 "Have native code generator",
662 "Support SMP",
663 "Unregisterised",
664 "Tables next to code",
665 "RTS ways",
666 "Leading underscore",
667 "Debug on",
668 "LibDir",
669 "Global Package DB",
670 "C compiler flags",
671 "C compiler link flags",
672 "ld flags"],
673 let k' = "-print-" ++ map (replaceSpace . toLower) k
674 replaceSpace ' ' = '-'
675 replaceSpace c = c
676 ] ++
677 ------- interfaces ----------------------------------------------------
678 [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f)
679 "--show-iface"))
680
681 ------- primary modes ------------------------------------------------
682 , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
683 addFlag "-no-link" f))
684 , defFlag "M" (PassFlag (setMode doMkDependHSMode))
685 , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc)))
686 , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc)))
687 , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False))))
688 , defFlag "-make" (PassFlag (setMode doMakeMode))
689 , defFlag "-backpack" (PassFlag (setMode doBackpackMode))
690 , defFlag "-interactive" (PassFlag (setMode doInteractiveMode))
691 , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode))
692 , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e"))
693 , defFlag "-frontend" (SepArg (\s -> setMode (doFrontendMode s) "-frontend"))
694 , defFlag "-vhdl" (PassFlag (setMode doVHDLMode))
695 , defFlag "-verilog" (PassFlag (setMode doVerilogMode))
696 , defFlag "-systemverilog" (PassFlag (setMode doSystemVerilogMode))
697 ]
698
699 setMode :: Mode -> String -> EwM ModeM ()
700 setMode newMode newFlag = liftEwM $ do
701 (mModeFlag, errs, flags') <- getCmdLineState
702 let (modeFlag', errs') =
703 case mModeFlag of
704 Nothing -> ((newMode, newFlag), errs)
705 Just (oldMode, oldFlag) ->
706 case (oldMode, newMode) of
707 -- -c/--make are allowed together, and mean --make -no-link
708 _ | isStopLnMode oldMode && isDoMakeMode newMode
709 || isStopLnMode newMode && isDoMakeMode oldMode ->
710 ((doMakeMode, "--make"), [])
711
712 -- If we have both --help and --interactive then we
713 -- want showGhciUsage
714 _ | isShowGhcUsageMode oldMode &&
715 isDoInteractiveMode newMode ->
716 ((showGhciUsageMode, oldFlag), [])
717 | isShowGhcUsageMode newMode &&
718 isDoInteractiveMode oldMode ->
719 ((showGhciUsageMode, newFlag), [])
720
721 -- If we have both -e and --interactive then -e always wins
722 _ | isDoEvalMode oldMode &&
723 isDoInteractiveMode newMode ->
724 ((oldMode, oldFlag), [])
725 | isDoEvalMode newMode &&
726 isDoInteractiveMode oldMode ->
727 ((newMode, newFlag), [])
728
729 -- Otherwise, --help/--version/--numeric-version always win
730 | isDominantFlag oldMode -> ((oldMode, oldFlag), [])
731 | isDominantFlag newMode -> ((newMode, newFlag), [])
732 -- We need to accumulate eval flags like "-e foo -e bar"
733 (Right (Right (DoEval esOld)),
734 Right (Right (DoEval [eNew]))) ->
735 ((Right (Right (DoEval (eNew : esOld))), oldFlag),
736 errs)
737 -- Saying e.g. --interactive --interactive is OK
738 _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
739
740 -- --interactive and --show-options are used together
741 (Right (Right DoInteractive), Left (ShowOptions _)) ->
742 ((Left (ShowOptions True),
743 "--interactive --show-options"), errs)
744 (Left (ShowOptions _), (Right (Right DoInteractive))) ->
745 ((Left (ShowOptions True),
746 "--show-options --interactive"), errs)
747 -- Otherwise, complain
748 _ -> let err = flagMismatchErr oldFlag newFlag
749 in ((oldMode, oldFlag), err : errs)
750 putCmdLineState (Just modeFlag', errs', flags')
751 where isDominantFlag f = isShowGhcUsageMode f ||
752 isShowGhciUsageMode f ||
753 isShowVersionMode f ||
754 isShowNumVersionMode f
755
756 flagMismatchErr :: String -> String -> String
757 flagMismatchErr oldFlag newFlag
758 = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'"
759
760 addFlag :: String -> String -> EwM ModeM ()
761 addFlag s flag = liftEwM $ do
762 (m, e, flags') <- getCmdLineState
763 putCmdLineState (m, e, mkGeneralLocated loc s : flags')
764 where loc = "addFlag by " ++ flag ++ " on the commandline"
765
766 -- ----------------------------------------------------------------------------
767 -- Run --make mode
768
769 doMake :: [(String,Maybe Phase)] -> Ghc ()
770 doMake srcs = do
771 let (hs_srcs, non_hs_srcs) = partition isHaskellishTarget srcs
772
773 hsc_env <- GHC.getSession
774
775 -- if we have no haskell sources from which to do a dependency
776 -- analysis, then just do one-shot compilation and/or linking.
777 -- This means that "ghc Foo.o Bar.o -o baz" links the program as
778 -- we expect.
779 if (null hs_srcs)
780 then liftIO (oneShot hsc_env StopLn srcs)
781 else do
782
783 o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x)
784 non_hs_srcs
785 dflags <- GHC.getSessionDynFlags
786 let dflags' = dflags { ldInputs = map (FileOption "") o_files
787 ++ ldInputs dflags }
788 _ <- GHC.setSessionDynFlags dflags'
789
790 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
791 GHC.setTargets targets
792 ok_flag <- GHC.load LoadAllTargets
793
794 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
795 return ()
796
797
798 -- ---------------------------------------------------------------------------
799 -- --show-iface mode
800
801 doShowIface :: DynFlags -> FilePath -> IO ()
802 doShowIface dflags file = do
803 hsc_env <- newHscEnv dflags
804 showIface hsc_env file
805
806 -- ---------------------------------------------------------------------------
807 -- Various banners and verbosity output.
808
809 showBanner :: PostLoadMode -> DynFlags -> IO ()
810 showBanner _postLoadMode dflags = do
811 let verb = verbosity dflags
812
813 #if defined(GHCI)
814 -- Show the GHCi banner
815 when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
816 #endif
817
818 -- Display details of the configuration in verbose mode
819 when (verb >= 2) $
820 do hPutStr stderr "Glasgow Haskell Compiler, Version "
821 hPutStr stderr cProjectVersion
822 hPutStr stderr ", stage "
823 hPutStr stderr cStage
824 hPutStr stderr " booted by GHC version "
825 hPutStrLn stderr cBooterVersion
826
827 -- We print out a Read-friendly string, but a prettier one than the
828 -- Show instance gives us
829 showInfo :: DynFlags -> IO ()
830 showInfo dflags = do
831 let sq x = " [" ++ x ++ "\n ]"
832 putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags
833
834 showSupportedExtensions :: IO ()
835 showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions
836
837 showVersion :: IO ()
838 showVersion = putStrLn $ concat [ "Clash, version "
839 , Data.Version.showVersion Paths_clash_ghc.version
840 , " (using clash-lib, version: "
841 , Data.Version.showVersion clashLibVersion
842 , ")"
843 ]
844
845 showOptions :: Bool -> IORef ClashOpts -> IO ()
846 showOptions isInteractive = putStr . unlines . availableOptions
847 where
848 availableOptions opts = concat
849 [ flagsForCompletion isInteractive
850 , map ('-':) (getFlagNames mode_flags)
851 , map ('-':) (getFlagNames (flagsClash opts))
852 ]
853 getFlagNames opts = map flagName opts
854
855 showGhcUsage :: DynFlags -> IO ()
856 showGhcUsage = showUsage False
857
858 showGhciUsage :: DynFlags -> IO ()
859 showGhciUsage = showUsage True
860
861 showUsage :: Bool -> DynFlags -> IO ()
862 showUsage ghci dflags = do
863 let usage_path = if ghci then ghciUsagePath dflags
864 else ghcUsagePath dflags
865 usage <- readFile usage_path
866 dump usage
867 where
868 dump "" = return ()
869 dump ('$':'$':s) = putStr progName >> dump s
870 dump (c:s) = putChar c >> dump s
871
872 dumpFinalStats :: DynFlags -> IO ()
873 dumpFinalStats dflags =
874 when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
875
876 dumpFastStringStats :: DynFlags -> IO ()
877 dumpFastStringStats dflags = do
878 buckets <- getFastStringTable
879 let (entries, longest, has_z) = countFS 0 0 0 buckets
880 msg = text "FastString stats:" $$
881 nest 4 (vcat [text "size: " <+> int (length buckets),
882 text "entries: " <+> int entries,
883 text "longest chain: " <+> int longest,
884 text "has z-encoding: " <+> (has_z `pcntOf` entries)
885 ])
886 -- we usually get more "has z-encoding" than "z-encoded", because
887 -- when we z-encode a string it might hash to the exact same string,
888 -- which is not counted as "z-encoded". Only strings whose
889 -- Z-encoding is different from the original string are counted in
890 -- the "z-encoded" total.
891 putMsg dflags msg
892 where
893 x `pcntOf` y = int ((x * 100) `quot` y) Outputable.<> char '%'
894
895 countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int)
896 countFS entries longest has_z [] = (entries, longest, has_z)
897 countFS entries longest has_z (b:bs) =
898 let
899 len = length b
900 longest' = max len longest
901 entries' = entries + len
902 has_zs = length (filter hasZEncoding b)
903 in
904 countFS entries' longest' (has_z + has_zs) bs
905
906 showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO ()
907 showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags))
908 dumpPackages dflags = putMsg dflags (pprPackages dflags)
909 dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags)
910
911 -- -----------------------------------------------------------------------------
912 -- Frontend plugin support
913
914 doFrontend :: ModuleName -> [(String, Maybe Phase)] -> Ghc ()
915 #if !defined(GHCI)
916 doFrontend modname _ = pluginError [modname]
917 #else
918 doFrontend modname srcs = do
919 hsc_env <- getSession
920 frontend_plugin <- liftIO $ loadFrontendPlugin hsc_env modname
921 frontend frontend_plugin
922 (reverse $ frontendPluginOpts (hsc_dflags hsc_env)) srcs
923 #endif
924
925 -- -----------------------------------------------------------------------------
926 -- ABI hash support
927
928 {-
929 ghc --abi-hash Data.Foo System.Bar
930
931 Generates a combined hash of the ABI for modules Data.Foo and
932 System.Bar. The modules must already be compiled, and appropriate -i
933 options may be necessary in order to find the .hi files.
934
935 This is used by Cabal for generating the ComponentId for a
936 package. The ComponentId must change when the visible ABI of
937 the package chagnes, so during registration Cabal calls ghc --abi-hash
938 to get a hash of the package's ABI.
939 -}
940
941 -- | Print ABI hash of input modules.
942 --
943 -- The resulting hash is the MD5 of the GHC version used (Trac #5328,
944 -- see 'hiVersion') and of the existing ABI hash from each module (see
945 -- 'mi_mod_hash').
946 abiHash :: [String] -- ^ List of module names
947 -> Ghc ()
948 abiHash strs = do
949 hsc_env <- getSession
950 let dflags = hsc_dflags hsc_env
951
952 liftIO $ do
953
954 let find_it str = do
955 let modname = mkModuleName str
956 r <- findImportedModule hsc_env modname Nothing
957 case r of
958 Found _ m -> return m
959 _error -> throwGhcException $ CmdLineError $ showSDoc dflags $
960 cannotFindModule dflags modname r
961
962 mods <- mapM find_it strs
963
964 let get_iface modl = loadUserInterface False (text "abiHash") modl
965 ifaces <- initIfaceCheck (text "abiHash") hsc_env $ mapM get_iface mods
966
967 bh <- openBinMem (3*1024) -- just less than a block
968 put_ bh hiVersion
969 -- package hashes change when the compiler version changes (for now)
970 -- see #5328
971 mapM_ (put_ bh . mi_mod_hash) ifaces
972 f <- fingerprintBinMem bh
973
974 putStrLn (showPpr dflags f)
975
976 -----------------------------------------------------------------------------
977 -- HDL Generation
978
979 makeHDL'
980 :: forall backend
981 . Backend backend
982 => Proxy backend
983 -> Ghc ()
984 -> IORef ClashOpts
985 -> [(String,Maybe Phase)]
986 -> Ghc ()
987 makeHDL' _ _ _ [] = throwGhcException (CmdLineError "No input files")
988 makeHDL' proxy startAction r srcs = makeHDL proxy startAction r $ fmap fst srcs
989
990 makeVHDL :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc ()
991 makeVHDL = makeHDL' (Proxy @VHDLState)
992
993 makeVerilog :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc ()
994 makeVerilog = makeHDL' (Proxy @VerilogState)
995
996 makeSystemVerilog :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc ()
997 makeSystemVerilog = makeHDL' (Proxy @SystemVerilogState)
998
999 -- -----------------------------------------------------------------------------
1000 -- Util
1001
1002 unknownFlagsErr :: [String] -> a
1003 unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs
1004 where
1005 oneError f =
1006 "unrecognised flag: " ++ f ++ "\n" ++
1007 (case match f (nubSort allNonDeprecatedFlags) of
1008 [] -> ""
1009 suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs))
1010 -- fixes #11789
1011 -- If the flag contains '=',
1012 -- this uses both the whole and the left side of '=' for comparing.
1013 match f allFlags
1014 | elem '=' f =
1015 let (flagsWithEq, flagsWithoutEq) = partition (elem '=') allFlags
1016 fName = takeWhile (/= '=') f
1017 in (fuzzyMatch f flagsWithEq) ++ (fuzzyMatch fName flagsWithoutEq)
1018 | otherwise = fuzzyMatch f allFlags
1019
1020 {- Note [-Bsymbolic and hooks]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1022 -Bsymbolic is a flag that prevents the binding of references to global
1023 symbols to symbols outside the shared library being compiled (see `man
1024 ld`). When dynamically linking, we don't use -Bsymbolic on the RTS
1025 package: that is because we want hooks to be overridden by the user,
1026 we don't want to constrain them to the RTS package.
1027
1028 Unfortunately this seems to have broken somehow on OS X: as a result,
1029 defaultHooks (in hschooks.c) is not called, which does not initialize
1030 the GC stats. As a result, this breaks things like `:set +s` in GHCi
1031 (#8754). As a hacky workaround, we instead call 'defaultHooks'
1032 directly to initalize the flags in the RTS.
1033
1034 A byproduct of this, I believe, is that hooks are likely broken on OS
1035 X when dynamically linking. But this probably doesn't affect most
1036 people since we're linking GHC dynamically, but most things themselves
1037 link statically.
1038 -}
1039
1040 foreign import ccall safe "initGCStatistics"
1041 initGCStatistics :: IO ()