[project @ 2001-06-18 09:09:28 by simonmar]
[ghc-hetmet.git] / ghc / compiler / ghci / InteractiveUI.hs
index 208662d..e64323c 100644 (file)
@@ -1,5 +1,5 @@
 -----------------------------------------------------------------------------
--- $Id: InteractiveUI.hs,v 1.69 2001/05/28 03:17:03 sof Exp $
+-- $Id: InteractiveUI.hs,v 1.77 2001/06/18 09:09:28 simonmar Exp $
 --
 -- GHC Interactive User Interface
 --
@@ -13,8 +13,9 @@ module InteractiveUI ( interactiveUI, ghciWelcomeMsg ) where
 #include "../includes/config.h"
 #include "HsVersions.h"
 
+import Packages
 import CompManager
-import CmStaticInfo
+import HscTypes                ( GhciMode(..) )
 import ByteCodeLink
 import DriverFlags
 import DriverState
@@ -24,7 +25,7 @@ import Finder         ( flushPackageCache )
 import Util
 import Name            ( Name )
 import Outputable
-import CmdLineOpts     ( DynFlag(..), dopt_unset )
+import CmdLineOpts     ( DynFlag(..), getDynFlags, saveDynFlags, restoreDynFlags, dopt_unset )
 import Panic           ( GhcException(..) )
 import Config
 
@@ -145,9 +146,9 @@ interactiveUI cmstate mod cmdline_libs = do
        Just hval -> writeIORef flush_stdout (unsafeCoerce# hval :: IO ())
        _ -> panic "interactiveUI:stdout"
 
-   (unGHCi runGHCi) GHCiState{ target = mod,
-                              cmstate = cmstate,
-                              options = [] }
+   startGHCi runGHCi GHCiState{ target = mod,
+                               cmstate = cmstate,
+                               options = [] }
    return ()
 
 
@@ -267,27 +268,28 @@ readlineLoop = do
 -- and carries on.
 runCommand :: String -> GHCi Bool
 runCommand c = 
-  ghciHandle ( \exception -> 
-       (case exception of
-          DynException dyn -> 
-             case fromDynamic dyn of
-               Nothing -> io (putStrLn ("*** Exception: (unknown)"))
-               Just ghc_ex -> 
-                 case ghc_ex of
-                   PhaseFailed phase code ->
-                       io ( putStrLn ("Phase " ++ phase ++ " failed (code "
-                                       ++ show code ++ ")"))
-                   Interrupted -> io (putStrLn "Interrupted.")
-                       -- omit the location for CmdLineError
-                   CmdLineError s -> io (putStrLn s)
-                   other -> io (putStrLn (show (ghc_ex :: GhcException)))
-
-          other -> io (putStrLn ("*** Exception: " ++ show exception))
-
-       ) >> return False
-     ) $
-
-   doCommand c
+  ghciHandle ( \exception -> do
+               flushEverything
+               showException exception
+               return False
+            ) $
+  doCommand c
+
+showException (DynException dyn) =
+  case fromDynamic dyn of
+    Nothing -> 
+       io (putStrLn ("*** Exception: (unknown)"))
+    Just (PhaseFailed phase code) ->
+       io (putStrLn ("Phase " ++ phase ++ " failed (code "
+                      ++ show code ++ ")"))
+    Just Interrupted ->
+       io (putStrLn "Interrupted.")
+    Just (CmdLineError s) -> 
+       io (putStrLn s)  -- omit the location for CmdLineError
+    Just other_ghc_ex ->
+       io (putStrLn (show other_ghc_ex))
+showException other_exception
+  = io (putStrLn ("*** Exception: " ++ show other_exception))
 
 doCommand (':' : command) = specialCommand command
 doCommand stmt
@@ -302,7 +304,7 @@ runStmt stmt
  = return Nothing
  | otherwise
  = do st <- getGHCiState
-      dflags <- io (getDynFlags)
+      dflags <- io getDynFlags
       let dflags' = dopt_unset dflags Opt_WarnUnusedBinds
       (new_cmstate, names) <- io (cmRunStmt (cmstate st) dflags' stmt)
       setGHCiState st{cmstate = new_cmstate}
@@ -363,8 +365,10 @@ addModule _ = throwDyn (InstallationError ":add not implemented")
 setContext :: String -> GHCi ()
 setContext ""
   = throwDyn (CmdLineError "syntax: `:m <module>'")
-setContext m | not (isUpper (head m)) || not (all isAlphaNum (tail m))
+setContext m | not (isUpper (head m)) || not (all isAlphaNumEx (tail m))
   = throwDyn (CmdLineError ("strange looking module name: `" ++ m ++ "'"))
+    where
+       isAlphaNumEx c = isAlphaNum c || c == '_'
 setContext str
   = do st <- getGHCiState
        new_cmstate <- io (cmSetContext (cmstate st) str)
@@ -394,7 +398,7 @@ defineMacro s = do
 
   -- compile the expression
   st <- getGHCiState
-  dflags <- io (getDynFlags)
+  dflags <- io getDynFlags
   (new_cmstate, maybe_hv) <- io (cmCompileExpr (cmstate st) dflags new_expr)
   setGHCiState st{cmstate = new_cmstate}
   case maybe_hv of
@@ -425,14 +429,12 @@ loadModule path = timeIt (loadModule' path)
 
 loadModule' path = do
   state <- getGHCiState
-  dflags <- io (getDynFlags)
+  dflags <- io getDynFlags
   cmstate1 <- io (cmUnload (cmstate state) dflags)
+  setGHCiState state{ cmstate = cmstate1, target = Nothing }
   io (revertCAFs)                      -- always revert CAFs on load.
   (cmstate2, ok, mods) <- io (cmLoadModule cmstate1 path)
-  let new_state = state{ cmstate = cmstate2,
-                        target = Just path
-                      }
-  setGHCiState new_state
+  setGHCiState state{ cmstate = cmstate2, target = Just path }
   modulesLoadedMsg ok mods
 
 reloadModule :: String -> GHCi ()
@@ -464,7 +466,7 @@ modulesLoadedMsg ok mods = do
 typeOfExpr :: String -> GHCi ()
 typeOfExpr str 
   = do st <- getGHCiState
-       dflags <- io (getDynFlags)
+       dflags <- io getDynFlags
        (new_cmstate, maybe_tystr) <- io (cmTypeOfExpr (cmstate st) dflags str)
        setGHCiState st{cmstate = new_cmstate}
        case maybe_tystr of
@@ -513,11 +515,9 @@ setOptions str
 
       -- then, dynamic flags
       io $ do 
-       dyn_flags <- readIORef v_InitDynFlags
-        writeIORef v_DynFlags dyn_flags
+       restoreDynFlags
         leftovers <- processArgs dynamic_flags leftovers []
-        dyn_flags <- readIORef v_DynFlags
-        writeIORef v_InitDynFlags dyn_flags
+       saveDynFlags
 
         if (not (null leftovers))
                then throwDyn (CmdLineError ("unrecognised flags: " ++ 
@@ -572,7 +572,7 @@ optToStr RevertCAFs = "r"
 
 newPackages new_pkgs = do
   state <- getGHCiState
-  dflags <- io (getDynFlags)
+  dflags <- io getDynFlags
   cmstate1 <- io (cmUnload (cmstate state) dflags)
   setGHCiState state{ cmstate = cmstate1, target = Nothing }
 
@@ -602,14 +602,17 @@ data GHCiOption
 GLOBAL_VAR(flush_stdout, error "no flush_stdout", IO ())
 GLOBAL_VAR(flush_stderr, error "no flush_stdout", IO ())
 
-newtype GHCi a = GHCi { unGHCi :: GHCiState -> IO (GHCiState, a) }
+newtype GHCi a = GHCi { unGHCi :: IORef GHCiState -> IO a }
+
+startGHCi :: GHCi a -> GHCiState -> IO a
+startGHCi g state = do ref <- newIORef state; unGHCi g ref
 
 instance Monad GHCi where
-  (GHCi m) >>= k  =  GHCi $ \s -> m s >>= \(s,a) -> unGHCi (k a) s
-  return a  = GHCi $ \s -> return (s,a)
+  (GHCi m) >>= k  =  GHCi $ \s -> m s >>= \a -> unGHCi (k a) s
+  return a  = GHCi $ \s -> return a
 
-getGHCiState   = GHCi $ \s -> return (s,s)
-setGHCiState s = GHCi $ \_ -> return (s,())
+getGHCiState   = GHCi $ \r -> readIORef r
+setGHCiState s = GHCi $ \r -> writeIORef r s
 
 isOptionSet :: GHCiOption -> GHCi Bool
 isOptionSet opt
@@ -626,7 +629,7 @@ unsetOption opt
  = do st <- getGHCiState
       setGHCiState (st{ options = filter (/= opt) (options st) })
 
-io m = GHCi $ \s -> m >>= \a -> return (s,a)
+io m = GHCi $ \s -> m >>= \a -> return a
 
 -----------------------------------------------------------------------------
 -- recursive exception handlers
@@ -651,7 +654,11 @@ ghciUnblock (GHCi a) = GHCi $ \s -> Exception.unblock (a s)
 --        e.g.    On unix     "qt"  denotes "libqt.so"
 --                On WinDoze  "burble"  denotes "burble.DLL"
 --        addDLL is platform-specific and adds the lib/.so/.DLL
---        prefixes plaform-dependently; we don't do that here.
+--        suffixes platform-dependently; we don't do that here.
+-- 
+-- For dynamic objects only, try to find the object file in all the 
+-- directories specified in v_Library_Paths before giving up.
+
 type LibrarySpec
    = Either FilePath String
 
@@ -661,30 +668,51 @@ showLS (Right nm) = "(dynamic) " ++ nm
 linkPackages :: [LibrarySpec] -> [PackageConfig] -> IO ()
 linkPackages cmdline_lib_specs pkgs
    = do sequence_ [ linkPackage (name p `elem` loaded) p | p <- reverse pkgs ]
-        mapM_ preloadLib cmdline_lib_specs
+        lib_paths <- readIORef v_Library_paths
+        mapM_ (preloadLib lib_paths) cmdline_lib_specs
      where
        -- packages that are already linked into GHCi
-       loaded = [ "concurrent", "posix", "text", "util" ]
+       loaded = [ "gmp", "rts", "std", "concurrent", "posix", "text", "util" ]
 
-        preloadLib lib_spec
+        preloadLib :: [String] -> LibrarySpec -> IO ()
+        preloadLib lib_paths lib_spec
            = do putStr ("Loading object " ++ showLS lib_spec ++ " ... ")
                 case lib_spec of
                    Left static_ish
-                      -> do b <- doesFileExist static_ish
-                            if    not b
-                             then do putStr "not found.\n"
-                                     croak
-                             else do loadObj static_ish
-                                     putStr "done.\n"
+                      -> do b <- preload_static lib_paths static_ish
+                            putStrLn (if b then "done" else "not found")
                    Right dll_unadorned
-                      -> do maybe_errmsg <- addDLL dll_unadorned
-                            if    maybe_errmsg == nullPtr
-                             then putStr "done.\n"
-                             else do str <- peekCString maybe_errmsg
-                                     putStr ("failed (" ++ str ++ ")\n")
-                                     croak
-
-        croak = throwDyn (CmdLineError "user specified .o/.so/.DLL could not be loaded.")
+                      -> -- We add "" to the set of paths to try, so that
+                         -- if none of the real paths match, we force addDLL
+                         -- to look in the default dynamic-link search paths.
+                         do b <- preload_dynamic (lib_paths++[""]) dll_unadorned
+                            when (not b) (cantFind lib_paths lib_spec)
+                            putStrLn "done"
+
+        cantFind :: [String] -> LibrarySpec -> IO ()
+        cantFind paths spec
+           = do putStr ("failed.\nCan't find " ++ showLS spec
+                        ++ " in directories:\n"
+                        ++ unlines (map ("   "++) paths) )
+                give_up
+
+        -- not interested in the paths in the static case.
+        preload_static paths name
+           = do b <- doesFileExist name
+                if not b then return False
+                         else loadObj name >> return True
+
+        preload_dynamic [] name
+           = return False
+        preload_dynamic (path:paths) rootname
+           = do maybe_errmsg <- addDLL path rootname
+                if    maybe_errmsg /= nullPtr
+                 then preload_dynamic paths rootname
+                 else return True
+
+        give_up 
+           = (throwDyn . CmdLineError)
+                "user specified .o/.so/.DLL could not be loaded."
 
 
 linkPackage :: Bool -> PackageConfig -> IO ()
@@ -718,7 +746,7 @@ loadClassified :: LibrarySpec -> IO ()
 loadClassified (Left obj_absolute_filename)
    = do loadObj obj_absolute_filename
 loadClassified (Right dll_unadorned)
-   = do maybe_errmsg <- addDLL dll_unadorned
+   = do maybe_errmsg <- addDLL "" dll_unadorned -- doesn't seem right to me
         if    maybe_errmsg == nullPtr
          then return ()
          else do str <- peekCString maybe_errmsg