1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE RankNTypes #-}
3 {-# LANGUAGE ScopedTypeVariables #-}
4 {-# LANGUAGE ExistentialQuantification #-}
7 -- Module : Language.Haskell.LSP.Test
8 -- Description : A functional testing framework for LSP servers.
9 -- Maintainer : luke_lau@icloud.com
10 -- Stability : experimental
12 -- A framework for testing <https://github.com/Microsoft/language-server-protocol Language Server Protocol servers> at the JSON level.
14 module Language.Haskell.LSP.Test
18 , runSessionWithHandler
34 , publishDiagnosticsNotification
57 , getInitializeResponse
63 import Control.Applicative
64 import Control.Applicative.Combinators
66 import Control.Monad.IO.Class
67 import Control.Concurrent
68 import Control.Lens hiding ((.=))
69 import qualified Data.Text as T
70 import qualified Data.Text.IO as T
72 import qualified Data.ByteString.Lazy.Char8 as B
75 import Language.Haskell.LSP.Types
76 import qualified Language.Haskell.LSP.Types as LSP (error, id)
77 import Language.Haskell.LSP.Test.Compat
79 import System.Directory
80 import System.FilePath
81 import Language.Haskell.LSP.Test.Decoding
82 import Language.Haskell.LSP.Test.Parsing
84 -- | Starts a new session.
85 runSession :: String -- ^ The command to run the server.
86 -> FilePath -- ^ The filepath to the root directory for the session.
87 -> Session a -- ^ The session to run.
89 runSession serverExe rootDir session = do
91 absRootDir <- canonicalizePath rootDir
93 let initializeParams = InitializeParams (Just pid)
94 (Just $ T.pack absRootDir)
95 (Just $ filePathToUri absRootDir)
100 runSessionWithHandler listenServer serverExe rootDir $ do
102 -- Wrap the session around initialize and shutdown calls
103 sendRequest Initialize initializeParams
104 initRspMsg <- response :: Session InitializeResponse
106 liftIO $ maybe (return ()) (putStrLn . ("Error while initializing: " ++) . show ) (initRspMsg ^. LSP.error)
108 initRspVar <- initRsp <$> ask
109 liftIO $ putMVar initRspVar initRspMsg
112 sendNotification Initialized InitializedParams
114 -- Run the actual test
117 sendNotification Exit ExitParams
121 -- | An internal version of 'runSession' that allows for a custom handler to listen to the server.
122 -- It also does not automatically send initialize and exit messages.
123 runSessionWithHandler :: (Handle -> Session ())
128 runSessionWithHandler serverHandler serverExe rootDir session = do
129 absRootDir <- canonicalizePath rootDir
131 let createProc = (shell serverExe) { std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }
132 (Just serverIn, Just serverOut, _, serverProc) <- createProcess createProc
134 hSetBuffering serverIn NoBuffering
135 hSetBuffering serverOut NoBuffering
137 reqMap <- newMVar newRequestMap
138 messageChan <- newChan
139 meaninglessChan <- newChan
140 initRsp <- newEmptyMVar
142 let context = SessionContext serverIn absRootDir messageChan reqMap initRsp
143 initState = SessionState (IdInt 9)
145 threadId <- forkIO $ void $ runSession' meaninglessChan context initState (serverHandler serverOut)
146 (result, _) <- runSession' messageChan context initState session
148 terminateProcess serverProc
153 -- | Listens to the server output, makes sure it matches the record and
154 -- signals any semaphores
155 listenServer :: Handle -> Session ()
156 listenServer serverOut = do
157 msgBytes <- liftIO $ getNextMessage serverOut
160 reqMap <- liftIO $ readMVar $ requestMap context
162 liftIO $ writeChan (messageChan context) $ decodeFromServerMsg reqMap msgBytes
164 listenServer serverOut
166 -- | Sends a request to the server.
169 -- sendRequest (Proxy :: Proxy DocumentSymbolRequest)
170 -- TextDocumentDocumentSymbol
171 -- (DocumentSymbolParams docId)
175 => --Proxy (RequestMessage ClientMethod params resp) -- ^ A proxy to provide more type information about the request.
176 ClientMethod -- ^ The request method.
177 -> params -- ^ The request parameters.
178 -> Session LspId -- ^ The id of the request that was sent.
179 sendRequest method params = do
180 id <- curReqId <$> get
181 modify $ \c -> c { curReqId = nextId id }
183 let req = RequestMessage' "2.0" id method params
185 -- Update the request map
186 reqMap <- requestMap <$> ask
187 liftIO $ modifyMVar_ reqMap $
188 \r -> return $ updateRequestMap r id method
194 where nextId (IdInt i) = IdInt (i + 1)
195 nextId (IdString s) = IdString $ T.pack $ show $ read (T.unpack s) + 1
197 -- | A custom type for request message that doesn't
198 -- need a response type, allows us to infer the request
199 -- message type without using proxies.
200 data RequestMessage' a = RequestMessage' T.Text LspId ClientMethod a
202 instance ToJSON a => ToJSON (RequestMessage' a) where
203 toJSON (RequestMessage' rpc id method params) =
204 object ["jsonrpc" .= rpc, "id" .= id, "method" .= method, "params" .= params]
207 sendRequest' :: (ToJSON a, ToJSON b) => RequestMessage ClientMethod a b -> Session ()
208 sendRequest' req = do
209 -- Update the request map
210 reqMap <- requestMap <$> ask
211 liftIO $ modifyMVar_ reqMap $
212 \r -> return $ updateRequestMap r (req ^. LSP.id) (req ^. method)
216 -- | Sends a notification to the server.
217 sendNotification :: ToJSON a
218 => ClientMethod -- ^ The notification method.
219 -> a -- ^ The notification parameters.
221 sendNotification method params =
222 let notif = NotificationMessage "2.0" method params
223 in sendNotification' notif
225 sendNotification' :: (ToJSON a, ToJSON b) => NotificationMessage a b -> Session ()
226 sendNotification' = sendMessage
228 sendResponse :: ToJSON a => ResponseMessage a -> Session ()
229 sendResponse = sendMessage
231 sendMessage :: ToJSON a => a -> Session ()
233 h <- serverIn <$> ask
234 liftIO $ B.hPut h $ addHeader (encode msg)
236 -- | Returns the initialize response that was received from the server.
237 -- The initialize requests and responses are not included the session,
238 -- so if you need to test it use this.
239 getInitializeResponse :: Session InitializeResponse
240 getInitializeResponse = initRsp <$> ask >>= (liftIO . readMVar)
242 -- | Opens a text document and sends a notification to the client.
243 openDoc :: FilePath -> String -> Session TextDocumentIdentifier
244 openDoc file languageId = do
245 item <- getDocItem file languageId
246 sendNotification TextDocumentDidOpen (DidOpenTextDocumentParams item)
247 TextDocumentIdentifier <$> getDocUri file
249 -- | Reads in a text document as the first version.
250 getDocItem :: FilePath -- ^ The path to the text document to read in.
251 -> String -- ^ The language ID, e.g "haskell" for .hs files.
252 -> Session TextDocumentItem
253 getDocItem file languageId = do
255 let fp = rootDir context </> file
256 contents <- liftIO $ T.readFile fp
257 return $ TextDocumentItem (filePathToUri fp) (T.pack languageId) 0 contents
259 -- | Gets the Uri for the file corrected to the session directory.
260 getDocUri :: FilePath -> Session Uri
263 let fp = rootDir context </> file
264 return $ filePathToUri fp