/
Repl.hs
263 lines (233 loc) · 7.85 KB
/
Repl.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
module Language.Haskell.Repl
( Repl
, patienceForResult
, patienceForErrors
, lineLength
-- * Making 'Repl's
, newRepl
, repl'
, defaultWait
, defaultErrorWait
, defaultLineLength
, defaultImports
, defaultExtensions
-- * Killing 'Repl's
, stopRepl
-- * Interaction
, prompt
, promptWith
, enter
, results
) where
import Control.Concurrent
import Control.Applicative
import Control.Exception
import Control.Monad
import Data.Dynamic
import GHC
import GHC.Paths (libdir)
import DynFlags
import GhcMonad
import Outputable (showSDocForUser, ppr, neverQualify)
import Data.IORef
import Data.Maybe
import Data.Foldable (for_)
data Repl = Repl
{ input :: Chan [String]
, output :: Chan [String]
, interpreter :: ThreadId
, patienceForResult :: Maybe Double
, patienceForErrors :: Maybe Int
, lineLength :: Maybe Int
}
apply :: String -> String -> String
apply f x = f ++ " (" ++ x ++ ")"
enter :: Repl
-> [String] -- ^ Commands
-> String -- ^ Expression used for results.
-> IO ()
enter r sts x = writeChan (input r) (sts ++ [x])
-- | Naiively get the next set of results. This /does not/ take into account
-- 'patienceForResults', 'patienceForErrors', or 'lineLength'.
results :: Repl -> IO [String]
results = readChan . output
-- | Enter commands and an expression to a 'Repl', and immediately consume results.
-- However, truncate input to the given length, and stop the computation after the
-- given amount of time in seconds.
prompt
:: Repl
-> [String] -- ^ Commands
-> String -- ^ Expression used for results.
-> IO [String]
prompt r xs x = do
let trimLine = case lineLength r of
Just l -> take l
_ -> id
enter r xs x
lazyResults <- results r
final <- newEmptyMVar
timeout <- forkIO (patienceForResult r `for_` \ p -> do
threadDelay (floor (p*1000000))
putMVar final ["Thread timed out."])
attempt <- forkIO $ case patienceForErrors r of
Just p -> do
(tr,ir) <- progress lazyResults
threadDelay p
killThread tr
prog <- readIORef ir
let hs = map trimLine (take prog lazyResults)
ends hs `seq` putMVar final hs
_ -> putMVar final (map trimLine lazyResults)
fin <- takeMVar final
killThread timeout
killThread attempt
return fin
promptWith
:: Repl
-> (String -> IO a)
-> [String]
-> String
-> IO ()
promptWith r f xs x = prompt r xs x >>= mapM_ f
-- | See if a lazy list has ended.
ends :: [a] -> Bool
ends [] = True
ends (_:xs) = ends xs
-- | See 'how far' a lazy list has evaluated.
progress :: [a] -> IO (ThreadId, IORef Int)
progress [] = (,) <$> forkIO (return ()) <*> newIORef 0
progress xs = do
r <- newIORef 0
let go [] = return ()
go (_:ys) = modifyIORef r (+1) >> go ys
t <- forkIO (go xs)
return (t, r)
stopRepl :: Repl -> IO ()
stopRepl = killThread . interpreter
newRepl :: IO Repl
newRepl = do
inp <- newChan
out <- newChan
repl' defaultImports defaultExtensions inp out defaultWait defaultErrorWait defaultLineLength
defaultWait :: Maybe Double
defaultWait = Just 5
defaultErrorWait :: Maybe Int
defaultErrorWait = Just 3000
defaultLineLength :: Maybe Int
defaultLineLength = Just 512
defaultImports :: [String]
defaultImports
= ["import Prelude hiding ((.), id)"
,"import GHC.TypeLits"
,"import qualified Data.Map as M"
,"import qualified Data.Foldable as F"
,"import qualified Data.Traversable as T"
,"import Control.Monad.Reader"
,"import Control.Monad.State"
,"import Control.Monad.Writer"
,"import Control.Monad.RWS"
,"import Control.Comonad"
,"import Control.Category"
,"import Data.Function hiding ((.), id)"
,"import Control.Arrow"
,"import Data.List"
,"import Data.Maybe"
,"import Data.Semigroup"
,"import Control.Monad"
,"import Control.Monad.Fix"
,"import Control.Applicative"
,"import Control.Lens"
,"import Data.Monoid"
,"import Data.Functor"
,"import Data.Typeable"]
defaultExtensions :: [ExtensionFlag]
defaultExtensions
= [Opt_DataKinds
,Opt_PolyKinds
,Opt_TypeFamilies
,Opt_TypeOperators
,Opt_DeriveFunctor
,Opt_DeriveDataTypeable
,Opt_OverloadedStrings
,Opt_ImplicitParams
,Opt_BangPatterns
,Opt_PatternGuards
,Opt_MultiWayIf
,Opt_LambdaCase
,Opt_FlexibleInstances
,Opt_FlexibleContexts
,Opt_FunctionalDependencies
,Opt_GADTs]
-- | 'Repl' smart constructor.
repl'
:: [String] -- ^ Imports, using normal Haskell import syntax
-> [ExtensionFlag] -- ^ List of compiler extensions to use
-> Chan [String] -- ^ Input channel
-> Chan [String] -- ^ Output channel
-> Maybe Double -- ^ Maximum time to wait for a result, in seconds (default: 5)
-> Maybe Int -- ^ Maximum time to wait for an error, in microseconds (default: 3000)
-> Maybe Int -- ^ Maximum line length in 'Char' (default: 512)
-> IO Repl
repl' imports exts inp out wait ewait len = do
interp <- forkIO $
runGhc (Just libdir) $ do
dflags <- session
forever $ do
import_ imports
x <- liftIO (readChan inp)
msg <- liftIO (newIORef [])
forM_ (init x) (\s ->
runDeclOrStmt s
`gcatch`
\e@SomeException{} -> liftIO (modifyIORef msg (++ lines (show e))))
liftIO . modifyIORef msg . flip (++) =<<
case last x of
':':c:' ':arg -> case c of
't' -> errs (showSDocForUser dflags neverQualify . ppr) (snd . splitForAllTys <$> exprType arg)
'k' -> errs (showSDocForUser dflags neverQualify . ppr) (snd <$> typeKind True arg)
'd' | arg == "all" -> do
setTargets []
_<-load LoadAllTargets
return ["Cleared memory."]
_ -> return ["Invalid command."]
e | isDecl e -> errs
(const "OK.")
(runDecls e)
| otherwise -> case words e of
("let":_) -> errs
(const "OK.")
(runStmt e SingleStep)
_ -> errs
(`fromDyn` "")
(dynCompileExpr ("show" `apply` e))
liftIO $ writeChan out =<< readIORef msg
return $ Repl inp out interp wait ewait len
where
runDeclOrStmt s
| isDecl s = void (runDecls s)
| otherwise = void (runStmt ("let {" ++ s ++ "}") SingleStep)
isDecl x = maybe False decl (listToMaybe (words x))
decl x = case x of
"instance" -> True
"data" -> True
"class" -> True
"type" -> True
"newtype" -> True
_ -> False
errs :: (a -> String) -> Ghc a -> Ghc [String]
errs f x = fmap (lines . f) x
`gcatch` \e@SomeException{}
-> return
( -- map (dropWhile isSpace . dropWhileEnd isSpace)
lines
. show
$ e)
import_ = mapM (fmap IIDecl . parseImportDecl) >=> setContext
getExts = foldr (fmap . flip xopt_set) id
session = do
s <- getProgramDynFlags
_ <- setSessionDynFlags
$ (\d -> d { safeHaskell = Sf_Safe })
. flip dopt_set Opt_DoCoreLinting
$ getExts exts s
getSessionDynFlags