[project @ 2000-10-05 13:25:03 by simonmar]
[ghc-hetmet.git] / ghc / driver / Main.hs
index 2c053dc..45169cd 100644 (file)
@@ -1,6 +1,6 @@
-{-# OPTIONS -W #-}
+{-# OPTIONS -W -fno-warn-incomplete-patterns #-}
 -----------------------------------------------------------------------------
--- $Id: Main.hs,v 1.51 2000/08/06 12:19:21 panne Exp $
+-- $Id: Main.hs,v 1.63 2000/10/05 13:25:03 simonmar Exp $
 --
 -- GHC Driver program
 --
@@ -73,7 +73,7 @@ cHaskell1Version = "5" -- i.e., Haskell 98
 -----------------------------------------------------------------------------
 -- Usage Message
 
-short_usage = "Usage: For basic information, try the `-help' option."
+short_usage = "Usage: For basic information, try the `--help' option."
    
 long_usage = do
   let usage_file = "ghc-usage.txt"
@@ -292,7 +292,7 @@ GLOBAL_VAR(keep_raw_s_files,        False,          Bool)
 GLOBAL_VAR(scale_sizes_by,      1.0,           Double)
 GLOBAL_VAR(dry_run,            False,          Bool)
 GLOBAL_VAR(recomp,             True,           Bool)
-GLOBAL_VAR(tmp_prefix,                 cTMPDIR,        String)
+GLOBAL_VAR(tmpdir,             cDEFAULT_TMPDIR, String)
 #if !defined(HAVE_WIN32_DLL_SUPPORT) || defined(DONT_WANT_WIN32_DLL_SUPPORT)
 GLOBAL_VAR(static,             True,           Bool)
 #else
@@ -325,6 +325,7 @@ data HscLang
   = HscC
   | HscAsm
   | HscJava
+  deriving Eq
 
 GLOBAL_VAR(hsc_lang, if cGhcWithNativeCodeGen == "YES" && 
                         (prefixMatch "i386" cTARGETPLATFORM ||
@@ -506,7 +507,6 @@ hsc_minusO_flags = do
                "-fmax-simplifier-iterations2",
          "]",
 
-
        "-fsimplify",
          "[", 
                "-fmax-simplifier-iterations2",
@@ -517,6 +517,7 @@ hsc_minusO_flags = do
        "-fstrictness",
        "-fcpr-analyse",
        "-fworker-wrapper",
+       "-fglom-binds",
 
        "-fsimplify",
          "[", 
@@ -604,12 +605,12 @@ newPackage = do
   details <- readIORef package_details
   hPutStr stdout "Reading package info from stdin... "
   stuff <- getContents
-  let new_pkg = read stuff :: (String,Package)
+  let new_pkg = read stuff :: Package
   catchAll new_pkg
        (\_ -> throwDyn (OtherError "parse error in package info"))
   hPutStrLn stdout "done."
-  if (fst new_pkg `elem` map fst details)
-       then throwDyn (OtherError ("package `" ++ fst new_pkg ++ 
+  if (name new_pkg `elem` map name details)
+       then throwDyn (OtherError ("package `" ++ name new_pkg ++ 
                                        "' already installed"))
        else do
   conf_file <- readIORef package_config
@@ -622,13 +623,13 @@ deletePackage :: String -> IO ()
 deletePackage pkg = do  
   checkConfigAccess
   details <- readIORef package_details
-  if (pkg `notElem` map fst details)
+  if (pkg `notElem` map name details)
        then throwDyn (OtherError ("package `" ++ pkg ++ "' not installed"))
        else do
   conf_file <- readIORef package_config
   savePackageConfig conf_file
   maybeRestoreOldConfig conf_file $ do
-  writeNewConfig conf_file (filter ((/= pkg) . fst))
+  writeNewConfig conf_file (filter ((/= pkg) . name))
   exitWith ExitSuccess
 
 checkConfigAccess :: IO ()
@@ -649,7 +650,7 @@ maybeRestoreOldConfig conf_file io
        throw e
     )
 
-writeNewConfig :: String -> ([(String,Package)] -> [(String,Package)]) -> IO ()
+writeNewConfig :: String -> ([Package] -> [Package]) -> IO ()
 writeNewConfig conf_file fn = do
   hPutStr stdout "Writing new package config file... "
   old_details <- readIORef package_details
@@ -675,7 +676,7 @@ packages = global ["std", "rts", "gmp"] :: IORef [String]
 addPackage :: String -> IO ()
 addPackage package
   = do pkg_details <- readIORef package_details
-       case lookup package pkg_details of
+       case lookupPkg package pkg_details of
          Nothing -> throwDyn (OtherError ("unknown package name: " ++ package))
          Just details -> do
            ps <- readIORef packages
@@ -740,9 +741,15 @@ getPackageExtraLdOpts = do
 getPackageDetails :: [String] -> IO [Package]
 getPackageDetails ps = do
   pkg_details <- readIORef package_details
-  return [ pkg | p <- ps, Just pkg <- [ lookup p pkg_details ] ]
+  return [ pkg | p <- ps, Just pkg <- [ lookupPkg p pkg_details ] ]
+
+GLOBAL_VAR(package_details, (error "package_details"), [Package])
 
-GLOBAL_VAR(package_details, (error "package_details"), [(String,Package)])
+lookupPkg :: String -> [Package] -> Maybe Package
+lookupPkg nm ps
+   = case [p | p <- ps, name p == nm] of
+        []    -> Nothing
+        (p:_) -> Just p
 
 -----------------------------------------------------------------------------
 -- Ways
@@ -1076,12 +1083,12 @@ getOptionsFromSource file
            case () of
                () | null l -> look h
                   | prefixMatch "#" l -> look h
-                  | prefixMatch "{-# LINE" l -> look h
+                  | prefixMatch "{-# LINE" l -> look h   -- -}
                   | Just (opts:_) <- matchRegex optionRegex l
                        -> return (words opts)
                   | otherwise -> return []
 
-optionRegex = mkRegex "{-#[ \t]+OPTIONS[ \t]+(.*)#-}"
+optionRegex = mkRegex "\\{-#[ \t]+OPTIONS[ \t]+(.*)#-\\}"   -- -}
 
 -----------------------------------------------------------------------------
 -- Main loop
@@ -1122,6 +1129,10 @@ main =
        -- grab any -B options from the command line first
    argv'  <- setTopDir argv
 
+       -- check whether TMPDIR is set in the environment
+   IO.try (do dir <- getEnv "TMPDIR" -- fails if not set
+             writeIORef tmpdir dir)
+
        -- read the package configuration
    conf_file <- readIORef package_config
    contents <- readFile conf_file
@@ -1129,6 +1140,7 @@ main =
 
        -- find the phase to stop after (i.e. -E, -C, -c, -S flags)
    (flags2, todo, stop_flag) <- getToDo argv'
+   writeIORef v_todo todo
 
        -- process all the other arguments, and get the source files
    srcs <- processArgs driver_opts flags2 []
@@ -1180,6 +1192,8 @@ main =
 data ToDo = DoMkDependHS | DoMkDLL | StopBefore Phase | DoLink
   deriving (Eq)
 
+GLOBAL_VAR(v_todo, error "todo", ToDo)
+
 todoFlag :: String -> Maybe ToDo
 todoFlag "-M" = Just $ DoMkDependHS
 todoFlag "-E" = Just $ StopBefore Hsc
@@ -1265,17 +1279,21 @@ genPipeline todo stop_flag filename
 
    let
    ----------- -----  ----   ---   --   --  -  -  -
-    start_phase = startPhase suffix
-
     (_basename, suffix) = splitFilename filename
 
+    start_phase = startPhase suffix
+
     haskell_ish_file = suffix `elem` [ "hs", "lhs", "hc" ]
     c_ish_file       = suffix `elem` [ "c", "s", "S" ]  -- maybe .cc et al.??
 
-       -- hack for .hc files
-    real_lang | suffix == "hc" = HscC
-             | otherwise      = lang
+   -- for a .hc file, or if the -C flag is given, we need to force lang to HscC
+    real_lang 
+       | suffix == "hc"  = HscC
+       | todo == StopBefore HCc && lang /= HscC && haskell_ish_file = HscC
+       | otherwise = lang
 
+   let
+   ----------- -----  ----   ---   --   --  -  -  -
     pipeline
       | todo == DoMkDependHS = [ Unlit, Cpp, MkDependHS ]
 
@@ -1388,23 +1406,16 @@ run_pipeline ((phase, keep, o_suffix):phases)
        input_fn do_linking use_ofile orig_basename orig_suffix
   = do
 
-     output_fn <- 
-       (if null phases && not do_linking && use_ofile
-           then do o_file <- readIORef output_file
-                   case o_file of 
-                       Just s  -> return s
-                       Nothing -> do
-                           f <- odir_ify (orig_basename ++ '.':o_suffix)
-                           osuf_ify f
-
-           else if keep == Persistent
-                       then odir_ify (orig_basename ++ '.':o_suffix)
-                       else do filename <- newTempName o_suffix
-                               add files_to_clean filename
-                               return filename
-       )
+     output_fn <- outputFileName (null phases) keep o_suffix
 
-     run_phase phase orig_basename orig_suffix input_fn output_fn
+     carry_on <- run_phase phase orig_basename orig_suffix input_fn output_fn
+       -- sometimes we bail out early, eg. when the compiler's recompilation
+       -- checker has determined that recompilation isn't necessary.
+     if not carry_on 
+       then do let (_,keep,final_suffix) = last phases
+               ofile <- outputFileName True keep final_suffix
+               return ofile
+       else do -- carry on ...
 
        -- sadly, ghc -E is supposed to write the file to stdout.  We
        -- generate <file>.cpp, so we also have to cat the file here.
@@ -1414,12 +1425,25 @@ run_pipeline ((phase, keep, o_suffix):phases)
 
      run_pipeline phases output_fn do_linking use_ofile orig_basename orig_suffix
 
+  where
+     outputFileName last_phase keep suffix
+       = do o_file <- readIORef output_file
+            if last_phase && not do_linking && use_ofile && isJust o_file
+              then case o_file of 
+                      Just s  -> return s
+                      Nothing -> error "outputFileName"
+              else if keep == Persistent
+                          then do f <- odir_ify (orig_basename ++ '.':suffix)
+                                  osuf_ify f
+                          else do filename <- newTempName suffix
+                                  add files_to_clean filename
+                                  return filename
 
 -- find a temporary name that doesn't already exist.
 newTempName :: String -> IO String
 newTempName extn = do
   x <- getProcessID
-  tmp_dir <- readIORef tmp_prefix 
+  tmp_dir <- readIORef tmpdir
   findTempName tmp_dir x
   where findTempName tmp_dir x = do
           let filename = tmp_dir ++ "/ghc" ++ show x ++ '.':extn
@@ -1615,6 +1639,7 @@ run_phase Unlit _basename _suff input_fn output_fn
        run_something "Literate pre-processor"
          ("echo '# 1 \"" ++input_fn++"\"' > "++output_fn++" && "
           ++ unlit ++ ' ':input_fn ++ " - >> " ++ output_fn)
+       return True
 
 -------------------------------------------------------------------------------
 -- Cpp phase 
@@ -1648,10 +1673,11 @@ run_phase Cpp _basename _suff input_fn output_fn
                    ++ [ "-x", "c", input_fn, ">>", output_fn ]
                   ))
          else do
-           run_something "Inefective C pre-processor"
+           run_something "Ineffective C pre-processor"
                   ("echo '{-# LINE 1 \""  ++ input_fn ++ "\" -}' > " 
                    ++ output_fn ++ " && cat " ++ input_fn
                    ++ " >> " ++ output_fn)
+       return True
 
 -----------------------------------------------------------------------------
 -- MkDependHS phase
@@ -1690,7 +1716,7 @@ run_phase MkDependHS basename suff input_fn _output_fn = do
 
    mapM genDep [ d | Just d <- deps ]
 
-   return ()
+   return True
 
 -- add the lines to dep_makefile:
           -- always:
@@ -1713,7 +1739,7 @@ run_phase MkDependHS basename suff input_fn _output_fn = do
 -----------------------------------------------------------------------------
 -- Hsc phase
 
-run_phase Hsc  basename _suff input_fn output_fn
+run_phase Hsc  basename suff input_fn output_fn
   = do  hsc <- readIORef pgm_C
        
   -- we add the current directory (i.e. the directory in which
@@ -1754,12 +1780,37 @@ run_phase Hsc   basename _suff input_fn output_fn
                           Nothing -> [ "-hidir="++current_dir, "-hisuf="++hisuf ]
                           Just fn -> [ "-hifile="++fn ]
 
+  -- figure out if the source has changed, for recompilation avoidance.
+  -- only do this if we're eventually going to generate a .o file.
+  -- (ToDo: do when generating .hc files too?)
+  --
+  -- Setting source_unchanged to "-fsource_unchanged" means that M.o seems
+  -- to be up to date wrt M.hs; so no need to recompile unless imports have
+  -- changed (which the compiler itself figures out).
+  -- Setting source_unchanged to "" tells the compiler that M.o is out of
+  -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
+       do_recomp <- readIORef recomp
+       todo <- readIORef v_todo
+       source_unchanged <- 
+          if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
+            then return ""
+            else do t1 <- getModificationTime (basename ++ '.':suff)
+                    o_file <- odir_ify (basename ++ '.':phase_input_ext Ln)
+                    o_file_exists <- doesFileExist o_file
+                    if not o_file_exists
+                       then return ""  -- Need to recompile
+                       else do t2 <- getModificationTime o_file
+                               if t2 > t1
+                                 then return "-fsource-unchanged"
+                                 else return ""
+
   -- run the compiler!
        run_something "Haskell Compiler" 
                 (unwords (hsc : input_fn : (
                    hsc_opts
                    ++ hi_flags
                    ++ [ 
+                         source_unchanged,
                          "-ofile="++output_fn, 
                          "-F="++tmp_stub_c, 
                          "-FH="++tmp_stub_h 
@@ -1767,6 +1818,14 @@ run_phase Hsc    basename _suff input_fn output_fn
                    ++ stat_opts
                 )))
 
+  -- check whether compilation was performed, bail out if not
+       b <- doesFileExist output_fn
+       if not b && not (null source_unchanged) -- sanity
+               then do run_something "Touching object file"
+                           ("touch " ++ output_fn)
+                       return False
+               else do -- carry on...
+
   -- Generate -Rghc-timing info
        when (timing) (
            run_something "Generate timing stats"
@@ -1802,6 +1861,7 @@ run_phase Hsc     basename _suff input_fn output_fn
 
                add ld_inputs (basename++"_stub.o")
         )
+       return True
 
 -----------------------------------------------------------------------------
 -- Cc phase
@@ -1876,6 +1936,7 @@ run_phase cc_phase _basename _suff input_fn output_fn
                   ++ pkg_extra_cc_opts
 --                ++ [">", ccout]
                   ))
+       return True
 
        -- ToDo: postprocess the output from gcc
 
@@ -1896,6 +1957,7 @@ run_phase Mangle _basename _suff input_fn output_fn
                  ++ [ input_fn, output_fn ]
                  ++ machdep_opts
                ))
+       return True
 
 -----------------------------------------------------------------------------
 -- Splitting phase
@@ -1904,7 +1966,7 @@ run_phase SplitMangle _basename _suff input_fn _output_fn
   = do  splitter <- readIORef pgm_s
 
        -- this is the prefix used for the split .s files
-       tmp_pfx <- readIORef tmp_prefix
+       tmp_pfx <- readIORef tmpdir
        x <- getProcessID
        let split_s_prefix = tmp_pfx ++ "/ghc" ++ show x
        writeIORef split_prefix split_s_prefix
@@ -1925,6 +1987,7 @@ run_phase SplitMangle _basename _suff input_fn _output_fn
        s <- readFile n_files
        let n = read s :: Int
        writeIORef n_split_files n
+       return True
 
 -----------------------------------------------------------------------------
 -- As phase
@@ -1940,6 +2003,7 @@ run_phase As _basename _suff input_fn output_fn
                       ++ cmdline_include_flags
                       ++ [ "-c", input_fn, "-o",  output_fn ]
                    ))
+       return True
 
 run_phase SplitAs basename _suff _input_fn _output_fn
   = do  as <- readIORef pgm_a
@@ -1964,6 +2028,7 @@ run_phase SplitAs basename _suff _input_fn _output_fn
                            ))
        
        mapM_ assemble_file [1..n]
+       return True
 
 -----------------------------------------------------------------------------
 -- Linking
@@ -2109,6 +2174,11 @@ driver_opts =
   ,  ( "caf-all"       , NoArg (addOpt_C "-fauto-sccs-on-individual-cafs") )
          -- "ignore-sccs"  doesn't work  (ToDo)
 
+  ,  ( "no-auto-dicts" , NoArg (addAntiOpt_C "-fauto-sccs-on-dicts") )
+  ,  ( "no-auto-all"   , NoArg (addAntiOpt_C "-fauto-sccs-on-all-toplevs") )
+  ,  ( "no-auto"       , NoArg (addAntiOpt_C "-fauto-sccs-on-exported-toplevs") )
+  ,  ( "no-caf-all"    , NoArg (addAntiOpt_C "-fauto-sccs-on-individual-cafs") )
+
        ------- Miscellaneous -----------------------------------------------
   ,  ( "cpp"           , NoArg (updateState (\s -> s{ cpp_flag = True })) )
   ,  ( "#include"      , HasArg (addCmdlineHCInclude) )
@@ -2119,7 +2189,7 @@ driver_opts =
   ,  ( "o"             , SepArg (writeIORef output_file . Just) )
   ,  ( "osuf"          , HasArg (writeIORef output_suf  . Just) )
   ,  ( "hisuf"         , HasArg (writeIORef hi_suf) )
-  ,  ( "tmpdir"                , HasArg (writeIORef tmp_prefix  . (++ "/")) )
+  ,  ( "tmpdir"                , HasArg (writeIORef tmpdir . (++ "/")) )
   ,  ( "ohi"           , HasArg (\s -> case s of 
                                          "-" -> writeIORef hi_on_stdout True
                                          _   -> writeIORef output_hi (Just s)) )
@@ -2438,3 +2508,11 @@ newdir dir s = dir ++ '/':drop_longest_prefix s '/'
 
 remove_spaces :: String -> String
 remove_spaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace
+
+-----------------------------------------------------------------------------
+-- compatibility code
+
+#if __GLASGOW_HASKELL__ <= 408
+catchJust = catchIO
+ioErrors  = justIoErrors
+#endif