From fac990136efa62c46e50adf28235196c8f51c441 Mon Sep 17 00:00:00 2001 From: Martijn Bastiaan Date: Sun, 27 Apr 2025 18:08:01 +0200 Subject: [PATCH 1/6] Use `data` for `Signed`, `Unsigned`, `Index`, and `BiSignalOut` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GHC may insert coercions making Clash see underlying types. For the types mentioned in the commit title, this means Clash will see either a `Natural` or an `Integer`. These types are (for better or for worse) represented as machine words, potentially truncating any operations. As a concrete example, take: top :: Unsinged 68 -> Unsigned 68 -> Vec 1 (Unsigned 64) top x y = let res = x + y in res `seq` res :> Nil Translated to core, we get: λ(x :: Unsigned 68) -> λ(y :: Unsigned 68) -> let nt :: Natural = +# @68 topEntity2[GlobalId] x[LocalId] y[LocalId] in case nt[LocalId] of _ -> Cons @(+ 0 1) @(Unsigned 68) @0 (_CO_ @(~# Natural Natural (+ 0 1) (+ 0 1))) nt[LocalId] ((Λb -> Nil @0 @b (_CO_ @(~# Natural Natural 0 0))) @(Unsigned 68)) I.e., the result of `x + y` gets assinged to a binder of type `Natural`, making the calculation truncate. --- clash-prelude/src/Clash/Signal/BiSignal.hs | 5 ----- clash-prelude/src/Clash/Sized/Internal/Index.hs | 7 ------- clash-prelude/src/Clash/Sized/Internal/Signed.hs | 7 ------- clash-prelude/src/Clash/Sized/Internal/Unsigned.hs | 7 ------- clash-prelude/src/Clash/Sized/Vector.hs | 6 ------ 5 files changed, 32 deletions(-) diff --git a/clash-prelude/src/Clash/Signal/BiSignal.hs b/clash-prelude/src/Clash/Signal/BiSignal.hs index 29b8fedf36..d554220617 100644 --- a/clash-prelude/src/Clash/Signal/BiSignal.hs +++ b/clash-prelude/src/Clash/Signal/BiSignal.hs @@ -206,13 +206,8 @@ type role BiSignalOut nominal nominal nominal -- -- as it is not safe to coerce the default behaviour, synthesis domain or width -- of the data in the signal. -#if MIN_VERSION_base(4,15,0) && !MIN_VERSION_base(4,17,0) data BiSignalOut (ds :: BiSignalDefault) (dom :: Domain) (n :: Nat) = BiSignalOut ![Signal dom (Maybe (BitVector n))] -#else -newtype BiSignalOut (ds :: BiSignalDefault) (dom :: Domain) (n :: Nat) - = BiSignalOut [Signal dom (Maybe (BitVector n))] -#endif type instance HasDomain dom1 (BiSignalOut ds dom2 n) = DomEq dom1 dom2 type instance TryDomain t (BiSignalOut ds dom n) = 'Found dom diff --git a/clash-prelude/src/Clash/Sized/Internal/Index.hs b/clash-prelude/src/Clash/Sized/Internal/Index.hs index 6c8149c79a..164bef353a 100644 --- a/clash-prelude/src/Clash/Sized/Internal/Index.hs +++ b/clash-prelude/src/Clash/Sized/Internal/Index.hs @@ -158,17 +158,10 @@ type role Index nominal -- -- as it is not safe to coerce between 'Index'es with different ranges. To -- change the size, use the functions in the 'Resize' class. -#if MIN_VERSION_base(4,15,0) && !MIN_VERSION_base(4,17,0) data Index (n :: Nat) = -- | The constructor, 'I', and the field, 'unsafeToInteger', are not -- synthesizable. I { unsafeToInteger :: !Integer } -#else -newtype Index (n :: Nat) = - -- | The constructor, 'I', and the field, 'unsafeToInteger', are not - -- synthesizable. - I { unsafeToInteger :: Integer } -#endif deriving (Data, Generic) {-# ANN I hasBlackBox #-} diff --git a/clash-prelude/src/Clash/Sized/Internal/Signed.hs b/clash-prelude/src/Clash/Sized/Internal/Signed.hs index 787f857a68..c31c8faaa8 100644 --- a/clash-prelude/src/Clash/Sized/Internal/Signed.hs +++ b/clash-prelude/src/Clash/Sized/Internal/Signed.hs @@ -184,17 +184,10 @@ type role Signed nominal -- -- as it is not safe to coerce between different width Signed. To change the -- width, use the functions in the 'Clash.Class.Resize.Resize' class. -#if MIN_VERSION_base(4,15,0) && !MIN_VERSION_base(4,17,0) data Signed (n :: Nat) = -- | The constructor, 'S', and the field, 'unsafeToInteger', are not -- synthesizable. S { unsafeToInteger :: !Integer} -#else -newtype Signed (n :: Nat) = - -- | The constructor, 'S', and the field, 'unsafeToInteger', are not - -- synthesizable. - S { unsafeToInteger :: Integer} -#endif deriving (Data, Generic) {-# ANN S hasBlackBox #-} diff --git a/clash-prelude/src/Clash/Sized/Internal/Unsigned.hs b/clash-prelude/src/Clash/Sized/Internal/Unsigned.hs index 0936227e32..fa783a3736 100644 --- a/clash-prelude/src/Clash/Sized/Internal/Unsigned.hs +++ b/clash-prelude/src/Clash/Sized/Internal/Unsigned.hs @@ -200,17 +200,10 @@ type role Unsigned nominal -- -- as it is not safe to coerce between different width Unsigned. To change the -- width, use the functions in the 'Clash.Class.Resize.Resize' class. -#if MIN_VERSION_base(4,15,0) && !MIN_VERSION_base(4,17,0) data Unsigned (n :: Nat) = -- | The constructor, 'U', and the field, 'unsafeToNatural', are not -- synthesizable. U { unsafeToNatural :: !Natural } -#else -newtype Unsigned (n :: Nat) = - -- | The constructor, 'U', and the field, 'unsafeToNatural', are not - -- synthesizable. - U { unsafeToNatural :: Natural } -#endif deriving (Data, Generic) {-# ANN U hasBlackBox #-} diff --git a/clash-prelude/src/Clash/Sized/Vector.hs b/clash-prelude/src/Clash/Sized/Vector.hs index 672b508a04..d2d4fa8bdc 100644 --- a/clash-prelude/src/Clash/Sized/Vector.hs +++ b/clash-prelude/src/Clash/Sized/Vector.hs @@ -887,15 +887,9 @@ imap f = go 0 {- | Zip two vectors with a functions that also takes the elements' indices. -#if (__GLASGOW_HASKELL__ >= 900 && __GLASGOW_HASKELL__ < 904) || __GLASGOW_HASKELL__ >= 910 >>> izipWith (\i a b -> i + a + b) (2 :> 2 :> Nil) (3 :> 3:> Nil) *** Exception: X: Clash.Sized.Index: result 2 is out of bounds: [0..1] ... -#else ->>> izipWith (\i a b -> i + a + b) (2 :> 2 :> Nil) (3 :> 3:> Nil) -*** Exception: X: Clash.Sized.Index: result 3 is out of bounds: [0..1] -... -#endif >>> izipWith (\i a b -> extend (bitCoerce i) + a + b) (2 :> 2 :> Nil) (3 :> 3 :> Nil) :: Vec 2 (Unsigned 8) 5 :> 6 :> Nil From 48f3498641d81e73caa8e9831762bf6c78b0f229 Mon Sep 17 00:00:00 2001 From: Martijn Bastiaan Date: Sat, 19 Jul 2025 12:12:52 +0200 Subject: [PATCH 2/6] Rename `src-bin-9.10` to `src-bin-9.10.1` --- clash-ghc/clash-ghc.cabal | 2 +- clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/Leak.hs | 0 clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI.hs | 0 .../{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI/Exception.hs | 0 .../{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI/Info.hs | 0 .../{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI/Monad.hs | 0 clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/Util.hs | 0 clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/Main.hs | 0 8 files changed, 1 insertion(+), 1 deletion(-) rename clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/Leak.hs (100%) rename clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI.hs (100%) rename clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI/Exception.hs (100%) rename clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI/Info.hs (100%) rename clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/UI/Monad.hs (100%) rename clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/GHCi/Util.hs (100%) rename clash-ghc/{src-bin-9.10 => src-bin-9.10.1}/Clash/Main.hs (100%) diff --git a/clash-ghc/clash-ghc.cabal b/clash-ghc/clash-ghc.cabal index 915f93b770..212cc4eecd 100644 --- a/clash-ghc/clash-ghc.cabal +++ b/clash-ghc/clash-ghc.cabal @@ -122,7 +122,7 @@ library import: common-options HS-Source-Dirs: src-ghc, src-bin-common if impl(ghc >= 9.10.0) - HS-Source-Dirs: src-bin-9.10 + HS-Source-Dirs: src-bin-9.10.1 elif impl(ghc >= 9.8.0) HS-Source-Dirs: src-bin-9.8 elif impl(ghc >= 9.6.0) diff --git a/clash-ghc/src-bin-9.10/Clash/GHCi/Leak.hs b/clash-ghc/src-bin-9.10.1/Clash/GHCi/Leak.hs similarity index 100% rename from clash-ghc/src-bin-9.10/Clash/GHCi/Leak.hs rename to clash-ghc/src-bin-9.10.1/Clash/GHCi/Leak.hs diff --git a/clash-ghc/src-bin-9.10/Clash/GHCi/UI.hs b/clash-ghc/src-bin-9.10.1/Clash/GHCi/UI.hs similarity index 100% rename from clash-ghc/src-bin-9.10/Clash/GHCi/UI.hs rename to clash-ghc/src-bin-9.10.1/Clash/GHCi/UI.hs diff --git a/clash-ghc/src-bin-9.10/Clash/GHCi/UI/Exception.hs b/clash-ghc/src-bin-9.10.1/Clash/GHCi/UI/Exception.hs similarity index 100% rename from clash-ghc/src-bin-9.10/Clash/GHCi/UI/Exception.hs rename to clash-ghc/src-bin-9.10.1/Clash/GHCi/UI/Exception.hs diff --git a/clash-ghc/src-bin-9.10/Clash/GHCi/UI/Info.hs b/clash-ghc/src-bin-9.10.1/Clash/GHCi/UI/Info.hs similarity index 100% rename from clash-ghc/src-bin-9.10/Clash/GHCi/UI/Info.hs rename to clash-ghc/src-bin-9.10.1/Clash/GHCi/UI/Info.hs diff --git a/clash-ghc/src-bin-9.10/Clash/GHCi/UI/Monad.hs b/clash-ghc/src-bin-9.10.1/Clash/GHCi/UI/Monad.hs similarity index 100% rename from clash-ghc/src-bin-9.10/Clash/GHCi/UI/Monad.hs rename to clash-ghc/src-bin-9.10.1/Clash/GHCi/UI/Monad.hs diff --git a/clash-ghc/src-bin-9.10/Clash/GHCi/Util.hs b/clash-ghc/src-bin-9.10.1/Clash/GHCi/Util.hs similarity index 100% rename from clash-ghc/src-bin-9.10/Clash/GHCi/Util.hs rename to clash-ghc/src-bin-9.10.1/Clash/GHCi/Util.hs diff --git a/clash-ghc/src-bin-9.10/Clash/Main.hs b/clash-ghc/src-bin-9.10.1/Clash/Main.hs similarity index 100% rename from clash-ghc/src-bin-9.10/Clash/Main.hs rename to clash-ghc/src-bin-9.10.1/Clash/Main.hs From 618ef8bea211fb73422ad1d19f97d19883ce555b Mon Sep 17 00:00:00 2001 From: Martijn Bastiaan Date: Sat, 19 Jul 2025 12:31:42 +0200 Subject: [PATCH 3/6] Add source for GHC 9.10.2 executable --- clash-ghc/src-bin-9.10.2/Clash/GHCi/Leak.hs | 85 + clash-ghc/src-bin-9.10.2/Clash/GHCi/UI.hs | 4757 +++++++++++++++++ .../src-bin-9.10.2/Clash/GHCi/UI/Exception.hs | 141 + .../src-bin-9.10.2/Clash/GHCi/UI/Info.hs | 409 ++ .../src-bin-9.10.2/Clash/GHCi/UI/Monad.hs | 575 ++ clash-ghc/src-bin-9.10.2/Clash/GHCi/Util.hs | 16 + clash-ghc/src-bin-9.10.2/Clash/Main.hs | 1145 ++++ 7 files changed, 7128 insertions(+) create mode 100644 clash-ghc/src-bin-9.10.2/Clash/GHCi/Leak.hs create mode 100644 clash-ghc/src-bin-9.10.2/Clash/GHCi/UI.hs create mode 100644 clash-ghc/src-bin-9.10.2/Clash/GHCi/UI/Exception.hs create mode 100644 clash-ghc/src-bin-9.10.2/Clash/GHCi/UI/Info.hs create mode 100644 clash-ghc/src-bin-9.10.2/Clash/GHCi/UI/Monad.hs create mode 100644 clash-ghc/src-bin-9.10.2/Clash/GHCi/Util.hs create mode 100644 clash-ghc/src-bin-9.10.2/Clash/Main.hs diff --git a/clash-ghc/src-bin-9.10.2/Clash/GHCi/Leak.hs b/clash-ghc/src-bin-9.10.2/Clash/GHCi/Leak.hs new file mode 100644 index 0000000000..51e3958ba2 --- /dev/null +++ b/clash-ghc/src-bin-9.10.2/Clash/GHCi/Leak.hs @@ -0,0 +1,85 @@ +{-# LANGUAGE RecordWildCards, LambdaCase #-} +module GHCi.Leak + ( LeakIndicators + , getLeakIndicators + , checkLeakIndicators + ) where + +import Control.Monad +import Data.Bits +import Foreign.Ptr (ptrToIntPtr, intPtrToPtr) +import GHC +import GHC.Ptr (Ptr (..)) +import GHCi.Util +import GHC.Driver.Env +import GHC.Driver.Ppr +import GHC.Utils.Outputable +import GHC.Unit.Module.ModDetails +import GHC.Unit.Home.ModInfo +import GHC.Platform (target32Bit) +import GHC.Linker.Types +import Prelude +import System.Mem +import System.Mem.Weak +import GHC.Types.Unique.DFM +import Control.Exception + +-- Checking for space leaks in GHCi. See #15111, and the +-- -fghci-leak-check flag. + +data LeakIndicators = LeakIndicators [LeakModIndicators] + +data LeakModIndicators = LeakModIndicators + { leakMod :: Weak HomeModInfo + , leakIface :: Weak ModIface + , leakDetails :: Weak ModDetails + , leakLinkable :: [Maybe (Weak Linkable)] + } + +-- | Grab weak references to some of the data structures representing +-- the currently loaded modules. +getLeakIndicators :: HscEnv -> IO LeakIndicators +getLeakIndicators hsc_env = + fmap LeakIndicators $ + forM (eltsUDFM (hsc_HPT hsc_env)) $ \hmi@HomeModInfo{..} -> do + leakMod <- mkWeakPtr hmi Nothing + leakIface <- mkWeakPtr hm_iface Nothing + leakDetails <- mkWeakPtr hm_details Nothing + leakLinkable <- mkWeakLinkables hm_linkable + return $ LeakModIndicators{..} + where + mkWeakLinkables :: HomeModLinkable -> IO [Maybe (Weak Linkable)] + mkWeakLinkables (HomeModLinkable mbc mo) = + mapM (\ln -> traverse (flip mkWeakPtr Nothing <=< evaluate) ln) [mbc, mo] + +-- | Look at the LeakIndicators collected by an earlier call to +-- `getLeakIndicators`, and print messasges if any of them are still +-- alive. +checkLeakIndicators :: DynFlags -> LeakIndicators -> IO () +checkLeakIndicators dflags (LeakIndicators leakmods) = do + performGC + forM_ leakmods $ \LeakModIndicators{..} -> do + deRefWeak leakMod >>= \case + Nothing -> return () + Just hmi -> + report ("HomeModInfo for " ++ + showSDoc dflags (ppr (mi_module (hm_iface hmi)))) (Just hmi) + deRefWeak leakIface >>= \case + Nothing -> return () + Just miface -> report ("ModIface:" ++ moduleNameString (moduleName (mi_module miface))) (Just miface) + deRefWeak leakDetails >>= report "ModDetails" + forM_ leakLinkable $ \l -> forM_ l $ \l' -> deRefWeak l' >>= report "Linkable" + where + report :: String -> Maybe a -> IO () + report _ Nothing = return () + report msg (Just a) = do + addr <- anyToPtr a + putStrLn ("-fghci-leak-check: " ++ msg ++ " is still alive at " ++ + show (maskTagBits addr)) + + tagBits + | target32Bit (targetPlatform dflags) = 2 + | otherwise = 3 + + maskTagBits :: Ptr a -> Ptr a + maskTagBits p = intPtrToPtr (ptrToIntPtr p .&. complement (shiftL 1 tagBits - 1)) diff --git a/clash-ghc/src-bin-9.10.2/Clash/GHCi/UI.hs b/clash-ghc/src-bin-9.10.2/Clash/GHCi/UI.hs new file mode 100644 index 0000000000..491e422c10 --- /dev/null +++ b/clash-ghc/src-bin-9.10.2/Clash/GHCi/UI.hs @@ -0,0 +1,4757 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE BangPatterns #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE MagicHash #-} +{-# LANGUAGE MultiWayIf #-} +{-# LANGUAGE NondecreasingIndentation #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RecordWildCards #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE ViewPatterns #-} +{-# LANGUAGE TypeFamilies #-} + +{-# OPTIONS -fno-warn-name-shadowing #-} +-- This module does a lot of it + +----------------------------------------------------------------------------- +-- +-- GHC Interactive User Interface +-- +-- (c) The GHC Team 2005-2006 +-- +----------------------------------------------------------------------------- + +module GHCi.UI ( + interactiveUI, + GhciSettings(..), + defaultGhciSettings, + ghciCommands, + ghciWelcomeMsg + ) where + +-- GHCi +import qualified GHCi.UI.Monad as GhciMonad ( args, runStmt, runDecls' ) +import GHCi.UI.Monad hiding ( args, runStmt ) +import GHCi.UI.Info +import GHCi.UI.Exception +import GHC.Runtime.Debugger + +-- The GHC interface +import GHC.Runtime.Interpreter +import GHCi.RemoteTypes +import GHCi.BreakArray( breakOn, breakOff ) +import GHC.ByteCode.Types +import GHC.Core.DataCon +import GHC.Core.ConLike +import GHC.Core.PatSyn +import GHC.Driver.Flags +import GHC.Driver.Errors +import GHC.Driver.Errors.Types +import GHC.Driver.Phases +import GHC.Driver.Session as DynFlags +import GHC.Driver.Ppr hiding (printForUser) +import GHC.Utils.Error hiding (traceCmd) +import GHC.Driver.Monad ( modifySession ) +import GHC.Driver.Make ( newIfaceCache, ModIfaceCache(..) ) +import GHC.Driver.Config.Parser (initParserOpts) +import GHC.Driver.Config.Diagnostic +import qualified GHC +import GHC ( LoadHowMuch(..), Target(..), TargetId(..), + Resume, SingleStep, Ghc, + GetDocsFailure(..), pushLogHookM, + getModuleGraph, handleSourceError, ms_mod ) +import GHC.Driver.Main (hscParseModuleWithLocation, hscParseStmtWithLocation) +import GHC.Hs.ImpExp +import GHC.Hs +import GHC.Driver.Env +import GHC.Runtime.Context +import GHC.Types.TyThing +import GHC.Types.TyThing.Ppr +import GHC.Core.TyCo.Ppr +import GHC.Types.SafeHaskell ( getSafeMode ) +import GHC.Types.SourceError ( SourceError ) +import GHC.Types.Name +import GHC.Types.Breakpoint +import GHC.Types.Var ( varType ) +import GHC.Iface.Syntax ( showToHeader ) +import GHC.Builtin.Names +import GHC.Builtin.Types( stringTyCon_RDR ) +import GHC.Types.Name.Reader as RdrName ( getGRE_NameQualifier_maybes, getRdrName ) +import GHC.Types.SrcLoc as SrcLoc +import qualified GHC.Parser.Lexer as Lexer +import GHC.Parser.Header ( toArgs ) +import qualified GHC.Parser.Header as Header +import GHC.Types.PkgQual + +import GHC.Unit +import GHC.Unit.Finder as Finder +import GHC.Unit.Module.Graph (filterToposortToModules) +import GHC.Unit.Module.ModSummary + +import GHC.Data.StringBuffer +import GHC.Utils.Outputable +import GHC.Utils.Logger + +-- Other random utilities +import GHC.Types.Basic hiding ( isTopLevel ) +import GHC.Settings.Config +import GHC.Data.Graph.Directed +import GHC.Utils.Encoding +import GHC.Data.FastString +import qualified GHC.Linker.Loader as Loader +import GHC.Data.Maybe ( orElse, expectJust ) +import GHC.Types.Name.Set +import GHC.Utils.Panic hiding ( showException, try ) +import GHC.Utils.Misc +import qualified GHC.LanguageExtensions as LangExt +import GHC.Data.Bag (unitBag) +import qualified GHC.Data.Strict as Strict +import GHC.Types.Error + +-- Haskell Libraries +import System.Console.Haskeline as Haskeline + +import Control.Applicative hiding (empty) +import Control.DeepSeq (deepseq) +import Control.Monad as Monad +import Control.Monad.Catch as MC +import Control.Monad.IO.Class +import Control.Monad.Trans.Class +import Control.Monad.Trans.Except + +import Data.Array +import qualified Data.ByteString.Char8 as BS +import Data.Char +import Data.Function +import Data.IORef ( IORef, modifyIORef, newIORef, readIORef, writeIORef ) +import Data.List ( elemIndices, find, intercalate, intersperse, minimumBy, + isPrefixOf, isSuffixOf, nub, partition, sort, sortBy, (\\) ) +import qualified Data.List.NonEmpty as NE +import qualified Data.Set as S +import Data.Maybe +import qualified Data.Map as M +import Data.IntMap.Strict (IntMap) +import qualified Data.IntMap.Strict as IntMap +import Data.Time.LocalTime ( getZonedTime ) +import Data.Time.Format ( formatTime, defaultTimeLocale ) +import Data.Version ( showVersion ) +import qualified Data.Semigroup as S +import Prelude hiding ((<>)) + +import GHC.Utils.Exception as Exception hiding (catch, mask, handle) +import Foreign hiding (void) +import GHC.Stack hiding (SrcLoc(..)) +import GHC.Unit.Env +import GHC.Unit.Home.ModInfo + +import System.Directory +import System.Environment +import System.Exit ( exitWith, ExitCode(..) ) +import System.FilePath +import System.Info +import System.IO +import System.IO.Error +import System.IO.Unsafe ( unsafePerformIO ) +import System.Process +import Text.Printf +import Text.Read ( readMaybe ) +import Text.Read.Lex (isSymbolChar) + +import Unsafe.Coerce + +#if !defined(mingw32_HOST_OS) +import System.Posix hiding ( getEnv ) +#else +import qualified System.Win32 +#endif + +import GHC.IO.Exception ( IOErrorType(InvalidArgument) ) +import GHC.IO.Handle ( hFlushAll ) +import GHC.TopHandler ( topHandler ) + +import GHCi.Leak +import qualified GHC.Unit.Module.Graph as GHC + +----------------------------------------------------------------------------- + +data GhciSettings = GhciSettings { + availableCommands :: [Command], + shortHelpText :: String, + fullHelpText :: String, + defPrompt :: PromptFunction, + defPromptCont :: PromptFunction + } + +defaultGhciSettings :: GhciSettings +defaultGhciSettings = + GhciSettings { + availableCommands = ghciCommands, + shortHelpText = defShortHelpText, + defPrompt = default_prompt, + defPromptCont = default_prompt_cont, + fullHelpText = defFullHelpText + } + +ghciWelcomeMsg :: String +ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++ + ": https://www.haskell.org/ghc/ :? for help" + +ghciCommands :: [Command] +ghciCommands = map mkCmd [ + -- Hugs users are accustomed to :e, so make sure it doesn't overlap + ("?", keepGoing help, noCompletion), + ("add", keepGoingPaths addModule, completeFilename), + ("abandon", keepGoing abandonCmd, noCompletion), + ("break", keepGoing breakCmd, completeBreakpoint), + ("back", keepGoing backCmd, noCompletion), + ("browse", keepGoing' (browseCmd False), completeModule), + ("browse!", keepGoing' (browseCmd True), completeModule), + ("cd", keepGoingMulti' changeDirectory, completeFilename), + ("check", keepGoing' checkModule, completeHomeModule), + ("continue", keepGoing continueCmd, noCompletion), + ("cmd", keepGoing cmdCmd, completeExpression), + ("def", keepGoing (defineMacro False), completeExpression), + ("def!", keepGoing (defineMacro True), completeExpression), + ("delete", keepGoing deleteCmd, noCompletion), + ("disable", keepGoing disableCmd, noCompletion), + ("doc", keepGoing' docCmd, completeIdentifier), + ("edit", keepGoingMulti' editFile, completeFilename), + ("enable", keepGoing enableCmd, noCompletion), + ("force", keepGoing forceCmd, completeExpression), + ("forward", keepGoing forwardCmd, noCompletion), + ("help", keepGoingMulti help, noCompletion), + ("history", keepGoingMulti historyCmd, noCompletion), + ("info", keepGoingMulti' (info False), completeIdentifier), + ("info!", keepGoingMulti' (info True), completeIdentifier), + ("issafe", keepGoing' isSafeCmd, completeModule), + ("ignore", keepGoing ignoreCmd, noCompletion), + ("kind", keepGoingMulti' (kindOfType False), completeIdentifier), + ("kind!", keepGoingMulti' (kindOfType True), completeIdentifier), + ("load", keepGoingPaths loadModule_, completeHomeModuleOrFile), + ("load!", keepGoingPaths loadModuleDefer, completeHomeModuleOrFile), + ("list", keepGoing' listCmd, noCompletion), + ("module", keepGoing moduleCmd, completeSetModule), + ("main", keepGoing runMain, completeFilename), + ("print", keepGoing printCmd, completeExpression), + ("quit", quit, noCompletion), + ("reload", keepGoingMulti' reloadModule, noCompletion), + ("reload!", keepGoingMulti' reloadModuleDefer, noCompletion), + ("run", keepGoing runRun, completeFilename), + ("script", keepGoing' scriptCmd, completeFilename), + ("set", keepGoingMulti setCmd, completeSetOptions), + ("seti", keepGoingMulti setiCmd, completeSeti), + ("show", keepGoingMulti' showCmd, completeShowOptions), + ("showi", keepGoing showiCmd, completeShowiOptions), + ("sprint", keepGoing sprintCmd, completeExpression), + ("step", keepGoing stepCmd, completeIdentifier), + ("steplocal", keepGoing stepLocalCmd, completeIdentifier), + ("stepmodule",keepGoing stepModuleCmd, completeIdentifier), + ("type", keepGoingMulti' typeOfExpr, completeExpression), + ("trace", keepGoing traceCmd, completeExpression), + ("unadd", keepGoingPaths unAddModule, completeFilename), + ("undef", keepGoing undefineMacro, completeMacro), + ("unset", keepGoing unsetOptions, completeSetOptions), + ("where", keepGoing whereCmd, noCompletion), + ("instances", keepGoing' instancesCmd, completeExpression) + ] ++ map mkCmdHidden [ -- hidden commands + ("all-types", keepGoing' allTypesCmd), + ("complete", keepGoing completeCmd), + ("loc-at", keepGoing' locAtCmd), + ("type-at", keepGoing' typeAtCmd), + ("uses", keepGoing' usesCmd) + ] + where + mkCmd (n,a,c) = Command { cmdName = n + , cmdAction = a + , cmdHidden = False + , cmdCompletionFunc = c + } + + mkCmdHidden (n,a) = Command { cmdName = n + , cmdAction = a + , cmdHidden = True + , cmdCompletionFunc = noCompletion + } + +-- We initialize readline (in the interactiveUI function) to use +-- word_break_chars as the default set of completion word break characters. +-- This can be overridden for a particular command (for example, filename +-- expansion shouldn't consider '/' to be a word break) by setting the third +-- entry in the Command tuple above. +-- +-- NOTE: in order for us to override the default correctly, any custom entry +-- must be a SUBSET of word_break_chars. +word_break_chars :: String +word_break_chars = spaces ++ specials ++ symbols + +word_break_chars_pred :: Char -> Bool +word_break_chars_pred '.' = False +word_break_chars_pred c = c `elem` (spaces ++ specials) || isSymbolChar c + +symbols, specials, spaces :: String +symbols = "!#$%&*+/<=>?@\\^|-~" +specials = "(),;[]`{}" +spaces = " \t\n" + +flagWordBreakChars :: String +flagWordBreakChars = " \t\n" + + +showSDocForUser' :: GHC.GhcMonad m => SDoc -> m String +showSDocForUser' doc = do + dflags <- getDynFlags + unit_state <- hsc_units <$> GHC.getSession + name_ppr_ctx <- GHC.getNamePprCtx + pure $ showSDocForUser dflags unit_state name_ppr_ctx doc + +showSDocForUserQualify :: GHC.GhcMonad m => SDoc -> m String +showSDocForUserQualify doc = do + dflags <- getDynFlags + unit_state <- hsc_units <$> GHC.getSession + pure $ showSDocForUser dflags unit_state alwaysQualify doc + + +keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi CmdExecOutcome) +keepGoing a str = keepGoing' (lift . a) str + +keepGoingMulti :: (String -> GHCi ()) -> (String -> InputT GHCi CmdExecOutcome) +keepGoingMulti a str = keepGoingMulti' (lift . a) str + +keepGoing' :: GhciMonad m => (a -> m ()) -> a -> m CmdExecOutcome +keepGoing' a str = do + in_multi <- inMultiMode + if in_multi + then + liftIO $ hPutStrLn stderr "Command is not supported (yet) in multi-mode" + else + a str + return CmdSuccess + +-- For commands which are actually support in multi-mode, initially just :reload +keepGoingMulti' :: GhciMonad m => (String -> m ()) -> String -> m CmdExecOutcome +keepGoingMulti' a str = a str >> return CmdSuccess + +inMultiMode :: GhciMonad m => m Bool +inMultiMode = multiMode <$> getGHCiState + +keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi CmdExecOutcome) +keepGoingPaths a str + = do case toArgsNoLoc str of + Left err -> liftIO $ hPutStrLn stderr err >> return CmdSuccess + Right args -> keepGoing' a args + +defShortHelpText :: String +defShortHelpText = "use :? for help.\n" + +defFullHelpText :: String +defFullHelpText = + " Commands available from the prompt:\n" ++ + "\n" ++ + " evaluate/run \n" ++ + " : repeat last command\n" ++ + " :{\\n ..lines.. \\n:}\\n multiline command\n" ++ + " :add [*] ... add module(s) to the current target set\n" ++ + " :browse[!] [[*]] display the names defined by module \n" ++ + " (!: more details; *: all top-level names)\n" ++ + " :cd change directory to \n" ++ + " :cmd run the commands returned by ::IO String\n" ++ + " :complete [] list completions for partial input string\n" ++ + " :def[!] define command : (later defined command has\n" ++ + " precedence, :: is always a builtin command)\n" ++ + " (!: redefine an existing command name)\n" ++ + " :doc display docs for the given name (experimental)\n" ++ + " :edit edit file\n" ++ + " :edit edit last module\n" ++ + " :help, :? display this list of commands\n" ++ + " :info[!] [ ...] display information about the given names\n" ++ + " (!: do not filter instances)\n" ++ + " :instances display the class instances available for \n" ++ + " :issafe [] display safe haskell information of module \n" ++ + " :kind[!] show the kind of \n" ++ + " (!: also print the normalised type)\n" ++ + " :load[!] [*] ... load module(s) and their dependents\n" ++ + " (!: defer type errors)\n" ++ + " :main [ ...] run the main function with the given arguments\n" ++ + " :module [+/-] [*] ... set the context for expression evaluation\n" ++ + " :quit exit GHCi\n" ++ + " :reload[!] reload the current module set\n" ++ + " (!: defer type errors)\n" ++ + " :run function [ ...] run the function with the given arguments\n" ++ + " :script run the script \n" ++ + " :type show the type of \n" ++ + " :type +d show the type of , defaulting type variables\n" ++ + " :unadd ... remove module(s) from the current target set\n" ++ + " :undef undefine user-defined command :\n" ++ + " :: run the builtin command\n" ++ + " :! run the shell command \n" ++ + "\n" ++ + " -- Commands for debugging:\n" ++ + "\n" ++ + " :abandon at a breakpoint, abandon current computation\n" ++ + " :back [] go back in the history N steps (after :trace)\n" ++ + " :break [] [] set a breakpoint at the specified location\n" ++ + " :break set a breakpoint on the specified function\n" ++ + " :continue [] resume after a breakpoint [and set break ignore count]\n" ++ + " :delete ... delete the specified breakpoints\n" ++ + " :delete * delete all breakpoints\n" ++ + " :disable ... disable the specified breakpoints\n" ++ + " :disable * disable all breakpoints\n" ++ + " :enable ... enable the specified breakpoints\n" ++ + " :enable * enable all breakpoints\n" ++ + " :force print , forcing unevaluated parts\n" ++ + " :forward [] go forward in the history N step s(after :back)\n" ++ + " :history [] after :trace, show the execution history\n" ++ + " :ignore for break set break ignore \n" ++ + " :list show the source code around current breakpoint\n" ++ + " :list show the source code for \n" ++ + " :list [] show the source code around line number \n" ++ + " :print [ ...] show a value without forcing its computation\n" ++ + " :sprint [ ...] simplified version of :print\n" ++ + " :step single-step after stopping at a breakpoint\n"++ + " :step single-step into \n"++ + " :steplocal single-step within the current top-level binding\n"++ + " :stepmodule single-step restricted to the current module\n"++ + " :trace trace after stopping at a breakpoint\n"++ + " :trace evaluate with tracing on (see :history)\n"++ + + "\n" ++ + " -- Commands for changing settings:\n" ++ + "\n" ++ + " :set