@@ -1,9 +1,6 @@
1−{-# LANGUAGE BangPatterns #-}
2{-# LANGUAGE CPP #-}
1{-# LANGUAGE CPP #-}
3{-# LANGUAGE LambdaCase #-}
2{-# LANGUAGE LambdaCase #-}
4{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE OverloadedStrings #-}
5−{-# LANGUAGE MagicHash #-}
6−{-# LANGUAGE UnboxedTuples #-}
7-----------------------------------------------------------------------------
4-----------------------------------------------------------------------------
9-- Module : Language.Javascript.JSaddle.Run
6-- Module : Language.Javascript.JSaddle.Run
@@ -37,59 +34,43 @@ module Language.Javascript.JSaddle.Run (
39#ifdef ghcjs_HOST_OS
36#ifdef ghcjs_HOST_OS
40−import Language.Javascript.JSaddle.Types (JSM, syncPoint, syncAfter)
37+import Language.Javascript.JSaddle.Types (JSM)
41import qualified JavaScript.Web.AnimationFrame as GHCJS
38import qualified JavaScript.Web.AnimationFrame as GHCJS
42 (waitForAnimationFrame)
39 (waitForAnimationFrame)
44−import Control.Exception (throwIO, evaluate)
41+import Control.Exception (throwIO)
45−import Control.Monad (void, when, zipWithM_)
42+import Control.Monad (void, when, forever, zipWithM_)
46import Control.Monad.IO.Class (MonadIO(..))
43import Control.Monad.IO.Class (MonadIO(..))
47import Control.Monad.Trans.Reader (ask, runReaderT)
44import Control.Monad.Trans.Reader (ask, runReaderT)
48import Control.Monad.STM (atomically)
45import Control.Monad.STM (atomically)
49−import Control.Concurrent (forkIO, myThreadId)
46+import Control.Concurrent (forkIO)
50import Control.Concurrent.STM.TChan
47import Control.Concurrent.STM.TChan
51 (tryReadTChan, TChan, readTChan, writeTChan, newTChanIO)
48 (tryReadTChan, TChan, readTChan, writeTChan, newTChanIO)
52import Control.Concurrent.STM.TVar
49import Control.Concurrent.STM.TVar
53 (writeTVar, readTVar, readTVarIO, modifyTVar', newTVarIO)
50 (writeTVar, readTVar, readTVarIO, modifyTVar', newTVarIO)
54import Control.Concurrent.MVar
51import Control.Concurrent.MVar
55− (tryTakeMVar, MVar, putMVar, takeMVar, newMVar, newEmptyMVar, readMVar, modifyMVar)
52+ (tryTakeMVar, MVar, putMVar, takeMVar, newEmptyMVar, readMVar)
57import System.IO.Unsafe (unsafeInterleaveIO)
54import System.IO.Unsafe (unsafeInterleaveIO)
58import System.Mem.Weak (addFinalizer)
55import System.Mem.Weak (addFinalizer)
61−import GHC.Base (IO(..), mkWeak#)
62−import GHC.Conc (ThreadId(..))
63import Data.Monoid ((<>))
57import Data.Monoid ((<>))
64−import qualified Data.Text as T (unpack, pack)
58+import qualified Data.Text as T (unpack)
65import qualified Data.Map as M (lookup, delete, insert, empty, size)
59import qualified Data.Map as M (lookup, delete, insert, empty, size)
66−import qualified Data.Set as S (empty, member, insert, delete)
67import Data.Time.Clock (getCurrentTime,diffUTCTime)
60import Data.Time.Clock (getCurrentTime,diffUTCTime)
69− (mkWeakIORef, newIORef, atomicWriteIORef, readIORef)
61+import Data.IORef (newIORef, atomicWriteIORef, readIORef)
71import Language.Javascript.JSaddle.Types
63import Language.Javascript.JSaddle.Types
72 (Command(..), AsyncCommand(..), Result(..), BatchResults(..), Results(..), JSContextRef(..), JSVal(..),
64 (Command(..), AsyncCommand(..), Result(..), BatchResults(..), Results(..), JSContextRef(..), JSVal(..),
73− Object(..), JSValueReceived(..), JSM(..), Batch(..), JSValueForSend(..), syncPoint, syncAfter, sendCommand)
65+ Object(..), JSValueReceived(..), JSM(..), Batch(..), JSValueForSend(..))
74import Language.Javascript.JSaddle.Exception (JSException(..))
66import Language.Javascript.JSaddle.Exception (JSException(..))
67+-- import Language.Javascript.JSaddle.Native.Internal (wrapJSVal)
75−import Control.DeepSeq (force, deepseq)
68+import Control.DeepSeq (deepseq)
76−#if MIN_VERSION_base(4,11,0)
77−import GHC.Stats (getRTSStatsEnabled, getRTSStats, RTSStats(..), gcdetails_live_bytes, gc)
79import GHC.Stats (getGCStatsEnabled, getGCStats, GCStats(..))
69import GHC.Stats (getGCStatsEnabled, getGCStats, GCStats(..))
80−#endif
70+import Data.Maybe (isJust)
81import Data.Foldable (forM_)
71import Data.Foldable (forM_)
85−#if MIN_VERSION_base(4,11,0)
86−currentBytesUsed = gcdetails_live_bytes . gc
88−getRTSStatsEnabled = getGCStatsEnabled
89−getRTSStats = getGCStats
93-- | Enable (or disable) JSaddle logging
74-- | Enable (or disable) JSaddle logging
94enableLogging :: Bool -> JSM ()
75enableLogging :: Bool -> JSM ()
95#ifdef ghcjs_HOST_OS
76#ifdef ghcjs_HOST_OS
@@ -100,6 +81,27 @@ enableLogging v = do
100 liftIO $ f v
81 liftIO $ f v
84+-- | Forces execution of pending asyncronous code
90+ SyncResult <- sendCommand Sync
94+-- | Forces execution of pending asyncronous code after performing `f`
95+syncAfter :: JSM a -> JSM a
103-- | On GHCJS this is 'JavaScript.Web.AnimationFrame.waitForAnimationFrame'.
105-- | On GHCJS this is 'JavaScript.Web.AnimationFrame.waitForAnimationFrame'.
104-- On GHC it will delay the execution of the current batch of asynchronous
106-- On GHC it will delay the execution of the current batch of asynchronous
105-- command when they are sent to JavaScript. It will not delay the Haskell
107-- command when they are sent to JavaScript. It will not delay the Haskell
@@ -125,12 +127,17 @@ nextAnimationFrame f = do
125 syncAfter (f t)
127 syncAfter (f t)
127#ifndef ghcjs_HOST_OS
129#ifndef ghcjs_HOST_OS
130+sendCommand :: Command -> JSM Result
132+ s <- doSendCommand <$> JSM ask
128sendLazyCommand :: (JSValueForSend -> AsyncCommand) -> JSM JSVal
135sendLazyCommand :: (JSValueForSend -> AsyncCommand) -> JSM JSVal
129sendLazyCommand cmd = do
136sendLazyCommand cmd = do
130 nextRefTVar <- nextRef <$> JSM ask
137 nextRefTVar <- nextRef <$> JSM ask
131 n <- liftIO . atomically $ do
138 n <- liftIO . atomically $ do
132 n <- subtract 1 <$> readTVar nextRefTVar
139 n <- subtract 1 <$> readTVar nextRefTVar
133− writeTVar nextRefTVar $! n
140+ writeTVar nextRefTVar n
135 s <- doSendAsyncCommand <$> JSM ask
142 s <- doSendAsyncCommand <$> JSM ask
136 liftIO $ s (cmd $ JSValueForSend n)
143 liftIO $ s (cmd $ JSValueForSend n)
@@ -143,45 +150,34 @@ sendAsyncCommand cmd = do
144runJavaScript :: (Batch -> IO ()) -> JSM () -> IO (Results -> IO (), Results -> IO Batch, IO ())
151runJavaScript :: (Batch -> IO ()) -> JSM () -> IO (Results -> IO (), Results -> IO Batch, IO ())
145runJavaScript sendBatch entryPoint = do
152runJavaScript sendBatch entryPoint = do
146− contextId' <- randomIO
147 startTime' <- getCurrentTime
153 startTime' <- getCurrentTime
148 recvMVar <- newEmptyMVar
154 recvMVar <- newEmptyMVar
149 lastAsyncBatch <- newEmptyMVar
155 lastAsyncBatch <- newEmptyMVar
150 commandChan <- newTChanIO
156 commandChan <- newTChanIO
151 callbacks <- newTVarIO M.empty
157 callbacks <- newTVarIO M.empty
152 nextRef' <- newTVarIO 0
158 nextRef' <- newTVarIO 0
153− finalizerThreads' <- newMVar S.empty
154− animationFrameHandlers' <- newMVar []
155 loggingEnabled <- newIORef False
159 loggingEnabled <- newIORef False
156− liveRefs' <- newMVar S.empty
157 let ctx = JSContextRef {
160 let ctx = JSContextRef {
158− contextId = contextId'
159− , startTime = startTime'
161+ startTime = startTime'
160− , doSendCommand = \cmd -> cmd `deepseq` do
162+ , doSendCommand = \cmd -> cmd `deepseq` do
161− result <- newEmptyMVar
163+ result <- newEmptyMVar
162− atomically $ writeTChan commandChan (Right (cmd, result))
164+ atomically $ writeTChan commandChan (Right (cmd, result))
163− unsafeInterleaveIO $
165+ unsafeInterleaveIO $
164− takeMVar result >>= \case
166+ takeMVar result >>= \case
165− (ThrowJSValue v) -> do
166− jsval <- wrapJSVal' ctx v
167− throwIO $ JSException jsval
167+ (ThrowJSValue (JSValueReceived v)) -> throwIO $ JSException (JSVal v)
168− r -> return r
168+ r -> return r
169− , doSendAsyncCommand = \cmd -> cmd `deepseq` atomically (writeTChan commandChan $ Left cmd)
169+ , doSendAsyncCommand = \cmd -> cmd `deepseq` atomically (writeTChan commandChan $ Left cmd)
170− , addCallback = \(Object (JSVal ioref)) cb -> do
171− val <- readIORef ioref
172− atomically $ modifyTVar' callbacks (M.insert val cb)
170+ , addCallback = \(Object (JSVal val)) cb -> atomically $ modifyTVar' callbacks (M.insert val cb)
171+ , freeCallback = \(Object (JSVal val)) -> atomically $ modifyTVar' callbacks (M.delete val)
173− , nextRef = nextRef'
172+ , nextRef = nextRef'
174− , doEnableLogging = atomicWriteIORef loggingEnabled
173+ , doEnableLogging = atomicWriteIORef loggingEnabled
175− , finalizerThreads = finalizerThreads'
176− , animationFrameHandlers = animationFrameHandlers'
177− , liveRefs = liveRefs'
179− processResults :: Bool -> Results -> IO ()
175+ let processResults :: Bool -> Results -> IO ()
180 processResults syncCallbacks = \case
176 processResults syncCallbacks = \case
181 (ProtocolError err) -> error $ "Protocol error : " <> T.unpack err
177 (ProtocolError err) -> error $ "Protocol error : " <> T.unpack err
182− (Callback n br (JSValueReceived fNumber) f this a) -> do
178+ (Callback n br f this a) -> do
183 putMVar recvMVar (n, br)
179 putMVar recvMVar (n, br)
184− f' <- runReaderT (unJSM $ wrapJSVal f) ctx
180+ f'@(JSVal fNumber) <- runReaderT (unJSM $ wrapJSVal f) ctx
185 this' <- runReaderT (unJSM $ wrapJSVal this) ctx
181 this' <- runReaderT (unJSM $ wrapJSVal this) ctx
186 args <- runReaderT (unJSM $ mapM wrapJSVal a) ctx
182 args <- runReaderT (unJSM $ mapM wrapJSVal a) ctx
187 logInfo (("Call " <> show fNumber <> " ") <>)
183 logInfo (("Call " <> show fNumber <> " ") <>)
@@ -206,13 +202,13 @@ runJavaScript sendBatch entryPoint = do
206 logInfo s =
202 logInfo s =
207 readIORef loggingEnabled >>= \case
203 readIORef loggingEnabled >>= \case
208 True -> do
204 True -> do
209− currentBytesUsedStr <- getRTSStatsEnabled >>= \case
205+ currentBytesUsedStr <- getGCStatsEnabled >>= \case
210− True -> show . currentBytesUsed <$> getRTSStats
206+ True -> show . currentBytesUsed <$> getGCStats
211 False -> return "??"
207 False -> return "??"
212 cbCount <- M.size <$> readTVarIO callbacks
208 cbCount <- M.size <$> readTVarIO callbacks
213− putStrLn . s $ "M " <> currentBytesUsedStr <> " CB " <> show cbCount <> " "
209+ putStrLn . s $ "M " <> currentBytesUsedStr <> "CB " <> show cbCount
214 False -> return ()
210 False -> return ()
215− _ <- forkIO . numberForeverFromM_ 1 $ \nBatch ->
211+ _ <- forkIO . forM_ [1..] $ \nBatch ->
216 readBatch nBatch commandChan >>= \case
212 readBatch nBatch commandChan >>= \case
217 (batch@(Batch cmds _ _), resultMVars) -> do
213 (batch@(Batch cmds _ _), resultMVars) -> do
218 logInfo (\x -> "Sync " <> x <> show (length cmds, last cmds))
214 logInfo (\x -> "Sync " <> x <> show (length cmds, last cmds))
@@ -220,27 +216,16 @@ runJavaScript sendBatch entryPoint = do
220 putMVar lastAsyncBatch batch
216 putMVar lastAsyncBatch batch
221 sendBatch batch
217 sendBatch batch
222 takeResult recvMVar nBatch >>= \case
218 takeResult recvMVar nBatch >>= \case
223− (n, _) | n /= nBatch -> error $ "Unexpected jsaddle results (expected batch " <> show nBatch <> ", got batch " <> show n <> ")"
219+ (n, _) | n /= nBatch -> error $ "Unexpected jsaddle results (expected batch " <> show nBatch <> ", got batch " <> show n <> ")"
224− (_, Success callbacksToFree results)
225− | length results /= length resultMVars -> error "Unexpected number of jsaddle results"
220+ (_, Success results) | length results /= length resultMVars -> error "Unexpected number of jsaddle results"
227− zipWithM_ putMVar resultMVars results
221+ | otherwise -> zipWithM_ putMVar resultMVars results
228− forM_ callbacksToFree $ \(JSValueReceived val) ->
229− atomically (modifyTVar' callbacks (M.delete val))
230− (_, Failure callbacksToFree results exception err) -> do
222+ (_, Failure results exception) -> do
231− -- The exception will only be rethrown in Haskell if/when one of the
223+ -- The exception will only be rethrown in Haskell if/when one of the
232− -- missing results (if any) is evaluated.
224+ -- missing results (if any) is evaluated.
233− putStrLn "A JavaScript exception was thrown! (may not reach Haskell code)"
225+ putStrLn "A JavaScript exception was thrown! (may not reach Haskell code)"
235− zipWithM_ putMVar resultMVars $ results <> repeat (ThrowJSValue exception)
226+ zipWithM_ putMVar resultMVars $ results <> repeat (ThrowJSValue exception)
236− forM_ callbacksToFree $ \(JSValueReceived val) ->
237− atomically (modifyTVar' callbacks (M.delete val))
238 return (asyncResults, syncResults, runReaderT (unJSM entryPoint) ctx)
227 return (asyncResults, syncResults, runReaderT (unJSM entryPoint) ctx)
240− numberForeverFromM_ :: (Monad m, Enum n) => n -> (n -> m a) -> m ()
241− numberForeverFromM_ !n f = do
243− numberForeverFromM_ (succ n) f
244 takeResult recvMVar nBatch =
229 takeResult recvMVar nBatch =
245 takeMVar recvMVar >>= \case
230 takeMVar recvMVar >>= \case
246 (n, _) | n < nBatch -> takeResult recvMVar nBatch
231 (n, _) | n < nBatch -> takeResult recvMVar nBatch
@@ -273,39 +258,12 @@ runJavaScript sendBatch entryPoint = do
273 loopAnimation (Left asyncCmd) (cmds, resultMVars) =
258 loopAnimation (Left asyncCmd) (cmds, resultMVars) =
274 atomically (readTChan chan) >>= \cmd -> loopAnimation cmd (Left asyncCmd:cmds, resultMVars)
259 atomically (readTChan chan) >>= \cmd -> loopAnimation cmd (Left asyncCmd:cmds, resultMVars)
276−addThreadFinalizer :: ThreadId -> IO () -> IO ()
277−addThreadFinalizer t@(ThreadId t#) (IO finalizer) =
278− IO $ \s -> case mkWeak# t# t finalizer s of { (# s1, _ #) -> (# s1, () #) }
281wrapJSVal :: JSValueReceived -> JSM JSVal
261wrapJSVal :: JSValueReceived -> JSM JSVal
282−wrapJSVal v = do
262+wrapJSVal (JSValueReceived ref) = do
283− ctx <- JSM ask
263+ -- TODO make sure this ref has not already been wrapped (perhaps only in debug version)
284− liftIO $ wrapJSVal' ctx v
264+ let result = JSVal ref
286−wrapJSVal' :: JSContextRef -> JSValueReceived -> IO JSVal
287−wrapJSVal' ctx (JSValueReceived n) = do
288− ref <- liftIO $ newIORef n
289− when (n >= 5 || n < 0) $
265+ when (ref >= 5) $ do
290−#ifdef JSADDLE_CHECK_WRAPJSVAL
266+ ctx <- JSM ask
291− do lr <- takeMVar $ liveRefs ctx
294− putStrLn $ "JS Value Ref " <> show n <> " already wrapped"
295− putMVar (liveRefs ctx) lr
296− else putMVar (liveRefs ctx) =<< evaluate (S.insert n lr)
298− void . mkWeakIORef ref $ do
299− ft <- takeMVar $ finalizerThreads ctx
301− let tname = T.pack $ show t
302− doSendAsyncCommand ctx $ FreeRef tname $ JSValueForSend n
267+ liftIO . addFinalizer result $ doSendAsyncCommand ctx $ FreeRef $ JSValueForSend ref
303− if tname `S.member` ft
304− then putMVar (finalizerThreads ctx) ft
306− addThreadFinalizer t $ do
307− modifyMVar (finalizerThreads ctx) $ \s -> return (S.delete tname s, ())
308− doSendAsyncCommand ctx $ FreeRefs tname
309− putMVar (finalizerThreads ctx) =<< evaluate (S.insert tname ft)
310− return (JSVal ref)
268+ return result