Main.hs 11.6 KB
Newer Older
1 2
{-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}

3
-----------------------------------------------------------------------------
4
-- $Id: Main.hs,v 1.119 2003/02/17 12:24:27 simonmar Exp $
5 6 7
--
-- GHC Driver program
--
8
-- (c) The University of Glasgow 2002
9 10 11 12 13 14 15 16
--
-----------------------------------------------------------------------------

-- with path so that ghc -M can find config.h
#include "../includes/config.h"

module Main (main) where

17 18
#include "HsVersions.h"

19

20
#ifdef GHCI
21
import InteractiveUI
22
import DriverPhases( objish_file )
23 24
#endif

25

26
import CompManager	( cmInit, cmLoadModules, cmDepAnal )
27
import HscTypes		( GhciMode(..) )
28
import Config		( cBooterVersion, cGhcUnregisterised, cProjectVersion )
29
import SysTools		( getPackageConfigPath, initSysTools, cleanTempFiles )
30 31 32
import Packages		( showPackages, getPackageConfigMap, basePackage,
			  haskell98Package
			)
33
import DriverPipeline	( staticLink, doMkDLL, genPipeline, pipeLoop )
34
import DriverState	( buildCoreToDo, buildStgToDo,
35
			  findBuildTag, 
36
			  getPackageExtraGhcOpts, unregFlags, 
37
			  v_GhcMode, v_GhcModeFlag, GhcMode(..),
38
			  v_Keep_tmp_files, v_Ld_inputs, v_Ways, 
39
			  v_OptLevel, v_Output_file, v_Output_hi, 
40 41
			  readPackageConf, verifyOutputFiles, v_NoLink,
			  v_Build_tag
42
			)
43
import DriverFlags	( buildStaticHscOpts,
44
			  dynamic_flags, processArgs, static_flags)
45 46

import DriverMkDepend	( beginMkDependHS, endMkDependHS )
47
import DriverPhases	( Phase(HsPp, Hsc), haskellish_src_file, isSourceFile )
48

49
import DriverUtil	( add, handle, handleDyn, later, splitFilename,
sof's avatar
sof committed
50
			  unknownFlagsErr, getFileSuffix )
51
import CmdLineOpts	( dynFlag, restoreDynFlags,
52
			  saveDynFlags, setDynFlags, getDynFlags, dynFlag,
53 54
			  DynFlags(..), HscLang(..), v_Static_hsc_opts,
			  defaultHscLang
55
			)
56
import BasicTypes	( failed )
57
import Outputable
58
import Util
59
import Panic		( GhcException(..), panic, installSignalHandlers )
60

61 62
import DATA_IOREF	( readIORef, writeIORef )
import EXCEPTION	( throwDyn, Exception(..), 
63
			  AsyncException(StackOverflow) )
64

65 66 67 68 69 70 71 72
-- Standard Haskell libraries
import IO
import Directory	( doesFileExist )
import System		( getArgs, exitWith, ExitCode(..) )
import Monad
import List
import Maybe

73 74 75 76 77 78 79 80 81 82 83
-----------------------------------------------------------------------------
-- ToDo:

-- new mkdependHS doesn't support all the options that the old one did (-X et al.)
-- time commands when run with -v
-- split marker
-- java generation
-- user ways
-- Win32 support: proper signal handling
-- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
-- reading the package configuration file is too slow
84
-- -K<size>
85 86 87 88 89 90 91 92 93 94 95 96

-----------------------------------------------------------------------------
-- Differences vs. old driver:

-- No more "Enter your Haskell program, end with ^D (on a line of its own):"
-- consistency checking removed (may do this properly later)
-- no -Ofile

-----------------------------------------------------------------------------
-- Main loop

main =
97
  -- top-level exception handler: any unrecognised exception is a compiler bug.
98
  handle (\exception -> do
sof's avatar
sof committed
99
  	   hFlush stdout
100 101
	   case exception of
		-- an IO exception probably isn't our fault, so don't panic
102
		IOException _ ->  hPutStr stderr (show exception)
103 104 105 106
		AsyncException StackOverflow ->
			hPutStrLn stderr "stack overflow: use +RTS -K<size> \ 
					 \to increase it"
		_other ->  hPutStr stderr (show (Panic (show exception)))
107 108
	   exitWith (ExitFailure 1)
         ) $ do
109

110
  -- all error messages are propagated as exceptions
sof's avatar
sof committed
111 112 113
  handleDyn (\dyn -> do
  		hFlush stdout
  		case dyn of
sof's avatar
sof committed
114
		     PhaseFailed _ code -> exitWith code
sof's avatar
sof committed
115 116 117
		     Interrupted -> exitWith (ExitFailure 1)
		     _ -> do hPutStrLn stderr (show (dyn :: GhcException))
			     exitWith (ExitFailure 1)
118
	    ) $ do
119

120
   -- make sure we clean up after ourselves
121
   later (do  forget_it <- readIORef v_Keep_tmp_files
122
	      unless forget_it $ do
123
	      verb <- dynFlag verbosity
124
	      cleanTempFiles verb
125
     ) $ do
126 127 128 129
	-- exceptions will be blocked while we clean the temporary files,
	-- so there shouldn't be any difficulty if we receive further
	-- signals.

130
   installSignalHandlers
131

132 133 134
   argv <- getArgs
   let (minusB_args, argv') = partition (prefixMatch "-B") argv
   top_dir <- initSysTools minusB_args
135

136
	-- Read the package configuration
137 138
   conf_file <- getPackageConfigPath
   readPackageConf conf_file
139 140

	-- process all the other arguments, and get the source files
141 142 143
   non_static <- processArgs static_flags argv' []
   mode <- readIORef v_GhcMode
   stop_flag <- readIORef v_GhcModeFlag
144

145 146 147 148 149 150 151
	-- -O and --interactive are not a good combination
	-- ditto with any kind of way selection
   orig_opt_level <- readIORef v_OptLevel
   when (orig_opt_level > 0 && mode == DoInteractive) $
      do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
         writeIORef v_OptLevel 0
   orig_ways <- readIORef v_Ways
sof's avatar
sof committed
152
   when (notNull orig_ways && mode == DoInteractive) $
153
      do throwDyn (UsageError 
154 155
                   "--interactive can't be used with -prof, -ticky, -unreg or -smp.")

156 157 158 159 160 161
	-- Find the build tag, and re-process the build-specific options.
	-- Also add in flags for unregisterised compilation, if 
	-- GhcUnregisterised=YES.
   way_opts <- findBuildTag
   let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
		  | otherwise = []
162 163 164
   pkg_extra_opts <- getPackageExtraGhcOpts
   extra_non_static <- processArgs static_flags 
			   (unreg_opts ++ way_opts ++ pkg_extra_opts) []
165

166
	-- give the static flags to hsc
167
   static_opts <- buildStaticHscOpts
168
   writeIORef v_Static_hsc_opts static_opts
169

170 171
   -- build the default DynFlags (these may be adjusted on a per
   -- module basis by OPTIONS pragmas and settings in the interpreter).
172 173

   core_todo <- buildCoreToDo
174
   stg_todo  <- buildStgToDo
175

176 177 178
   -- set the "global" HscLang.  The HscLang can be further adjusted on a module
   -- by module basis, using only the -fvia-C and -fasm flags.  If the global
   -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
179
   dyn_flags <- getDynFlags
180
   build_tag <- readIORef v_Build_tag
181 182
   let lang = case mode of 
		 DoInteractive  -> HscInterpreted
183 184 185 186
		 _other | build_tag /= "" -> HscC
			| otherwise       -> hscLang dyn_flags
		-- for ways other that the normal way, we must 
		-- compile via C.
187 188 189 190 191 192 193 194

   setDynFlags (dyn_flags{ coreToDo = core_todo,
			   stgToDo  = stg_todo,
                  	   hscLang  = lang,
			   -- leave out hscOutName for now
	                   hscOutName = panic "Main.main:hscOutName not set",
		  	   verbosity = 1
			})
195

196
	-- the rest of the arguments are "dynamic"
197
   srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
198

199
	-- save the "initial DynFlags" away
200
   saveDynFlags
201

sof's avatar
sof committed
202 203 204
        -- perform some checks of the options set / report unknowns.
   checkOptions srcs
   
205
   verb <- dynFlag verbosity
206

207 208 209 210 211 212 213
	-- Show the GHCi banner
#  ifdef GHCI
   when (mode == DoInteractive && verb >= 1) $
      hPutStrLn stdout ghciWelcomeMsg
#  endif

	-- Display details of the configuration in verbose mode
214 215 216 217 218
   when (verb >= 2) 
	(do hPutStr stderr "Glasgow Haskell Compiler, Version "
 	    hPutStr stderr cProjectVersion
	    hPutStr stderr ", for Haskell 98, compiled by GHC version "
	    hPutStrLn stderr cBooterVersion)
219

220 221
   when (verb >= 2) 
	(hPutStrLn stderr ("Using package config file: " ++ conf_file))
222

223
   pkg_details <- getPackageConfigMap
224 225
   showPackages pkg_details

226 227 228
   when (verb >= 3) 
	(hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))

229
	-- mkdependHS is special
230
   when (mode == DoMkDependHS) beginMkDependHS
231

232 233 234
	-- -ohi sanity checking
   ohi    <- readIORef v_Output_hi
   if (isJust ohi && 
sof's avatar
sof committed
235
	(mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
236 237 238
	then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
	else do

239
	-- make/interactive require invoking the compilation manager
240 241
   if (mode == DoMake)        then beginMake srcs        else do
   if (mode == DoInteractive) then beginInteractive srcs else do
242

243
	-- -o sanity checking
sof's avatar
sof committed
244
   let real_srcs = filter isSourceFile srcs -- filters out .a and .o that might appear
245
   o_file <- readIORef v_Output_file
sof's avatar
sof committed
246
   if (real_srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
247
	then throwDyn (UsageError "can't apply -o to multiple source files")
248 249
	else do

chak's avatar
chak committed
250
   if null srcs then throwDyn (UsageError "no input files") else do
251

252
   let compileFile src = do
253
	  restoreDynFlags
254

255 256 257 258
	  exists <- doesFileExist src
          when (not exists) $ 
		throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))

259 260
	  -- We compile in two stages, because the file may have an
	  -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
261 262
	  let (basename, suffix) = splitFilename src

263
	  -- just preprocess (Haskell source only)
sof's avatar
sof committed
264
   	  let src_and_suff = (src, getFileSuffix src)
sof's avatar
sof committed
265 266
	  let not_hs_file  = not (haskellish_src_file src)
	  pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
sof's avatar
sof committed
267
			then return src_and_suff else do
268
		phases <- genPipeline (StopBefore Hsc) stop_flag
sof's avatar
sof committed
269 270
				      False{-not persistent-} defaultHscLang
				      src_and_suff
sof's avatar
sof committed
271
	  	pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
272
			basename suffix
273

274
	  -- rest of compilation
275
	  hsc_lang <- dynFlag hscLang
sof's avatar
sof committed
276 277 278
	  phases   <- genPipeline mode stop_flag True hsc_lang pp
	  (r,_)    <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
	  			      True{-use -o flag-} basename suffix
279 280
	  return r

281
   o_files <- mapM compileFile srcs
282

283 284
   when (mode == DoMkDependHS) endMkDependHS

285
   omit_linking <- readIORef v_NoLink
286 287 288 289 290
   when (mode == DoLink && not omit_linking) 
	(staticLink o_files [basePackage, haskell98Package])
		-- we always link in the base package in one-shot linking.
		-- any other packages required must be given using -package
		-- options on the command-line.
291

rrt's avatar
rrt committed
292
   when (mode == DoMkDLL) (doMkDLL o_files)
293 294 295



296
beginMake :: [String] -> IO ()
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
beginMake fileish_args  = do 
  -- anything that doesn't look like a Haskell source filename or
  -- a module name is passed straight through to the linker
  let (inputs, objects) = partition looks_like_an_input fileish_args
  mapM_ (add v_Ld_inputs) objects
  
  case inputs of
	[]    -> throwDyn (UsageError "no input files")
	_     -> do dflags <- getDynFlags 
		    state <- cmInit Batch
		    graph <- cmDepAnal state dflags inputs
		    (_, ok_flag, _) <- cmLoadModules state dflags graph
		    when (failed ok_flag) (exitWith (ExitFailure 1))
		    return ()
  where
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    {-
      The following things should be considered compilation manager inputs:

       - haskell source files (strings ending in .hs, .lhs or other 
         haskellish extension),

       - module names (not forgetting hierarchical module names),

       - and finally we consider everything not containing a '.' to be
         a comp manager input, as shorthand for a .hs or .lhs filename.

      Everything else is considered to be a linker object, and passed
      straight through to the linker.
    -}
    looks_like_an_input m =  haskellish_src_file m 
			  || looksLikeModuleName m
			  || '.' `notElem` m
329

330 331

beginInteractive :: [String] -> IO ()
332
#ifndef GHCI
333
beginInteractive = throwDyn (CmdLineError "not built for interactive use")
334
#else
335
beginInteractive fileish_args
336
  = do state <- cmInit Interactive
337 338 339

       let (objs, mods) = partition objish_file fileish_args

340
       interactiveUI state mods objs
341
#endif
sof's avatar
sof committed
342 343 344 345 346

checkOptions :: [String] -> IO ()
checkOptions srcs = do
     -- complain about any unknown flags
   let unknown_opts = [ f | f@('-':_) <- srcs ]
sof's avatar
sof committed
347
   when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
sof's avatar
sof committed
348 349 350 351 352
     -- verify that output files point somewhere sensible.
   verifyOutputFiles
     -- and anything else that it might be worth checking for
     -- before kicking of a compilation (pipeline).