+
+updateStateC :: ConduitM FromServerMessage FromServerMessage (StateT SessionState (ReaderT SessionContext IO)) ()
+updateStateC = awaitForever $ \msg -> do
+ updateState msg
+ yield msg
+
+updateState :: (MonadIO m, HasReader SessionContext m, HasState SessionState m)
+ => FromServerMessage -> m ()
+
+-- Keep track of dynamic capability registration
+updateState (FromServerMess SClientRegisterCapability req) = do
+ let List newRegs = (\sr@(SomeRegistration r) -> (r ^. LSP.id, sr)) <$> req ^. params . registrations
+ modify $ \s ->
+ s { curDynCaps = Map.union (Map.fromList newRegs) (curDynCaps s) }
+
+updateState (FromServerMess SClientUnregisterCapability req) = do
+ let List unRegs = (^. LSP.id) <$> req ^. params . unregistrations
+ modify $ \s ->
+ let newCurDynCaps = foldr' Map.delete (curDynCaps s) unRegs
+ in s { curDynCaps = newCurDynCaps }
+
+updateState (FromServerMess STextDocumentPublishDiagnostics n) = do
+ let List diags = n ^. params . diagnostics
+ doc = n ^. params . uri
+ modify $ \s ->
+ let newDiags = Map.insert (toNormalizedUri doc) diags (curDiagnostics s)
+ in s { curDiagnostics = newDiags }
+
+updateState (FromServerMess SWorkspaceApplyEdit r) = do
+
+ -- First, prefer the versioned documentChanges field
+ allChangeParams <- case r ^. params . edit . documentChanges of
+ Just (List cs) -> do
+ mapM_ (checkIfNeedsOpened . (^. textDocument . uri)) cs
+ return $ map getParams cs
+ -- Then fall back to the changes field
+ Nothing -> case r ^. params . edit . changes of
+ Just cs -> do
+ mapM_ checkIfNeedsOpened (HashMap.keys cs)
+ concat <$> mapM (uncurry getChangeParams) (HashMap.toList cs)
+ Nothing ->
+ error "WorkspaceEdit contains neither documentChanges nor changes!"
+
+ modifyM $ \s -> do
+ newVFS <- liftIO $ changeFromServerVFS (vfs s) r
+ return $ s { vfs = newVFS }
+
+ let groupedParams = groupBy (\a b -> a ^. textDocument == b ^. textDocument) allChangeParams
+ mergedParams = map mergeParams groupedParams
+
+ -- TODO: Don't do this when replaying a session
+ forM_ mergedParams (sendMessage . NotificationMessage "2.0" STextDocumentDidChange)
+
+ -- Update VFS to new document versions
+ let sortedVersions = map (sortBy (compare `on` (^. textDocument . version))) groupedParams
+ latestVersions = map ((^. textDocument) . last) sortedVersions
+ bumpedVersions = map (version . _Just +~ 1) latestVersions
+
+ forM_ bumpedVersions $ \(VersionedTextDocumentIdentifier uri v) ->
+ modify $ \s ->
+ let oldVFS = vfs s
+ update (VirtualFile oldV file_ver t) = VirtualFile (fromMaybe oldV v) (file_ver + 1) t
+ newVFS = updateVFS (Map.adjust update (toNormalizedUri uri)) oldVFS
+ in s { vfs = newVFS }
+
+ where checkIfNeedsOpened uri = do
+ oldVFS <- vfs <$> get
+ ctx <- ask
+
+ -- if its not open, open it
+ unless (toNormalizedUri uri `Map.member` vfsMap oldVFS) $ do
+ let fp = fromJust $ uriToFilePath uri
+ contents <- liftIO $ T.readFile fp
+ let item = TextDocumentItem (filePathToUri fp) "" 0 contents
+ msg = NotificationMessage "2.0" STextDocumentDidOpen (DidOpenTextDocumentParams item)
+ liftIO $ B.hPut (serverIn ctx) $ addHeader (encode msg)
+
+ modifyM $ \s -> do
+ let (newVFS,_) = openVFS (vfs s) msg
+ return $ s { vfs = newVFS }
+
+ getParams (TextDocumentEdit docId (List edits)) =
+ let changeEvents = map (\e -> TextDocumentContentChangeEvent (Just (e ^. range)) Nothing (e ^. newText)) edits
+ in DidChangeTextDocumentParams docId (List changeEvents)
+
+ -- For a uri returns an infinite list of versions [n,n+1,n+2,...]
+ -- where n is the current version
+ textDocumentVersions uri = do
+ m <- vfsMap . vfs <$> get
+ let curVer = fromMaybe 0 $
+ _lsp_version <$> m Map.!? (toNormalizedUri uri)
+ pure $ map (VersionedTextDocumentIdentifier uri . Just) [curVer + 1..]
+
+ textDocumentEdits uri edits = do
+ vers <- textDocumentVersions uri
+ pure $ map (\(v, e) -> TextDocumentEdit v (List [e])) $ zip vers edits
+
+ getChangeParams uri (List edits) =
+ map <$> pure getParams <*> textDocumentEdits uri (reverse edits)
+
+ mergeParams :: [DidChangeTextDocumentParams] -> DidChangeTextDocumentParams
+ mergeParams params = let events = concat (toList (map (toList . (^. contentChanges)) params))
+ in DidChangeTextDocumentParams (head params ^. textDocument) (List events)
+updateState _ = return ()
+
+sendMessage :: (MonadIO m, HasReader SessionContext m, ToJSON a) => a -> m ()
+sendMessage msg = do
+ h <- serverIn <$> ask
+ logMsg LogClient msg
+ liftIO $ B.hPut h (addHeader $ encode msg)
+
+-- | Execute a block f that will throw a 'Language.Haskell.LSP.Test.Exception.Timeout' exception
+-- after duration seconds. This will override the global timeout
+-- for waiting for messages to arrive defined in 'SessionConfig'.
+withTimeout :: Int -> Session a -> Session a
+withTimeout duration f = do
+ chan <- asks messageChan
+ timeoutId <- getCurTimeoutId
+ modify $ \s -> s { overridingTimeout = True }
+ liftIO $ forkIO $ do
+ threadDelay (duration * 1000000)
+ writeChan chan (TimeoutMessage timeoutId)
+ res <- f
+ bumpTimeoutId timeoutId
+ modify $ \s -> s { overridingTimeout = False }
+ return res
+
+data LogMsgType = LogServer | LogClient
+ deriving Eq
+
+-- | Logs the message if the config specified it
+logMsg :: (ToJSON a, MonadIO m, HasReader SessionContext m)
+ => LogMsgType -> a -> m ()
+logMsg t msg = do
+ shouldLog <- asks $ logMessages . config
+ shouldColor <- asks $ logColor . config
+ liftIO $ when shouldLog $ do
+ when shouldColor $ setSGR [SetColor Foreground Dull color]
+ putStrLn $ arrow ++ showPretty msg
+ when shouldColor $ setSGR [Reset]
+
+ where arrow
+ | t == LogServer = "<-- "
+ | otherwise = "--> "
+ color
+ | t == LogServer = Magenta
+ | otherwise = Cyan
+
+ showPretty = B.unpack . encodePretty