Skip to content

Commit c257288

Browse files
committed
Use typed response errors
I have a branch adapting to this in HLS, it wasn't so bad. Fixes #586
1 parent 8fc240d commit c257288

File tree

10 files changed

+27
-27
lines changed

10 files changed

+27
-27
lines changed

lsp-test/src/Language/LSP/Test.hs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -674,7 +674,7 @@ getDocumentSymbols doc = do
674674
Right (InL xs) -> return (Left xs)
675675
Right (InR (InL xs)) -> return (Right xs)
676676
Right (InR (InR _)) -> return (Right [])
677-
Left err -> throw (UnexpectedResponseError (SomeLspId $ fromJust rspLid) err)
677+
Left err -> throw (UnexpectedResponseError (fromJust rspLid) err)
678678

679679
-- | Returns the code actions in the specified range.
680680
getCodeActions :: TextDocumentIdentifier -> Range -> Session [Command |? CodeAction]
@@ -685,7 +685,7 @@ getCodeActions doc range = do
685685
case rsp ^. L.result of
686686
Right (InL xs) -> return xs
687687
Right (InR _) -> return []
688-
Left error -> throw (UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. L.id) error)
688+
Left error -> throw (UnexpectedResponseError (fromJust $ rsp ^. L.id) error)
689689

690690
{- | Returns the code actions in the specified range, resolving any with
691691
a non empty _data_ field.
@@ -713,7 +713,7 @@ getAllCodeActions doc = do
713713
TResponseMessage _ rspLid res <- request SMethod_TextDocumentCodeAction (CodeActionParams Nothing Nothing doc (diag ^. L.range) ctx)
714714

715715
case res of
716-
Left e -> throw (UnexpectedResponseError (SomeLspId $ fromJust rspLid) e)
716+
Left e -> throw (UnexpectedResponseError (fromJust rspLid) e)
717717
Right (InL cmdOrCAs) -> pure (acc ++ cmdOrCAs)
718718
Right (InR _) -> pure acc
719719

@@ -781,7 +781,7 @@ resolveCodeAction ca = do
781781
rsp <- request SMethod_CodeActionResolve ca
782782
case rsp ^. L.result of
783783
Right ca -> return ca
784-
Left er -> throw (UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. L.id) er)
784+
Left er -> throw (UnexpectedResponseError (fromJust $ rsp ^. L.id) er)
785785

786786
{- | If a code action contains a _data_ field: resolves the code action, then
787787
executes it. Otherwise, just executes it.
@@ -849,7 +849,7 @@ resolveCompletion ci = do
849849
rsp <- request SMethod_CompletionItemResolve ci
850850
case rsp ^. L.result of
851851
Right ci -> return ci
852-
Left error -> throw (UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. L.id) error)
852+
Left error -> throw (UnexpectedResponseError (fromJust $ rsp ^. L.id) error)
853853

854854
-- | Returns the references for the position in the document.
855855
getReferences ::
@@ -937,11 +937,11 @@ getHighlights doc pos =
937937
{- | Checks the response for errors and throws an exception if needed.
938938
Returns the result if successful.
939939
-}
940-
getResponseResult :: (ToJSON (ErrorData m)) => TResponseMessage m -> MessageResult m
940+
getResponseResult :: (Show (ErrorData m)) => TResponseMessage m -> MessageResult m
941941
getResponseResult rsp =
942942
case rsp ^. L.result of
943943
Right x -> x
944-
Left err -> throw $ UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. L.id) err
944+
Left err -> throw $ UnexpectedResponseError (fromJust $ rsp ^. L.id) err
945945

946946
-- | Applies formatting to the specified document.
947947
formatDoc :: TextDocumentIdentifier -> FormattingOptions -> Session ()
@@ -984,7 +984,7 @@ resolveCodeLens cl = do
984984
rsp <- request SMethod_CodeLensResolve cl
985985
case rsp ^. L.result of
986986
Right cl -> return cl
987-
Left error -> throw (UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. L.id) error)
987+
Left error -> throw (UnexpectedResponseError (fromJust $ rsp ^. L.id) error)
988988

989989
-- | Returns the inlay hints in the specified range.
990990
getInlayHints :: TextDocumentIdentifier -> Range -> Session [InlayHint]
@@ -1006,7 +1006,7 @@ resolveInlayHint ih = do
10061006
rsp <- request SMethod_InlayHintResolve ih
10071007
case rsp ^. L.result of
10081008
Right ih -> return ih
1009-
Left error -> throw (UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. L.id) error)
1009+
Left error -> throw (UnexpectedResponseError (fromJust $ rsp ^. L.id) error)
10101010

10111011
-- | Pass a param and return the response from `prepareCallHierarchy`
10121012
prepareCallHierarchy :: CallHierarchyPrepareParams -> Session [CallHierarchyItem]
@@ -1021,7 +1021,7 @@ outgoingCalls = resolveRequestWithListResp SMethod_CallHierarchyOutgoingCalls
10211021
-- | Send a request and receive a response with list.
10221022
resolveRequestWithListResp ::
10231023
forall (m :: Method ClientToServer Request) a.
1024-
(ToJSON (ErrorData m), MessageResult m ~ ([a] |? Null)) =>
1024+
(Show (ErrorData m), MessageResult m ~ ([a] |? Null)) =>
10251025
SMethod m ->
10261026
MessageParams m ->
10271027
Session [a]

lsp-test/src/Language/LSP/Test/Exceptions.hs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,10 @@ data SessionException
1717
| ReplayOutOfOrder FromServerMessage [FromServerMessage]
1818
| UnexpectedDiagnostics
1919
| IncorrectApplyEditRequest String
20-
| UnexpectedResponseError SomeLspId ResponseError
20+
| forall m. Show (ErrorData m) => UnexpectedResponseError (LspId m) (TResponseError m)
2121
| UnexpectedServerTermination
2222
| IllegalInitSequenceMessage FromServerMessage
2323
| MessageSendError Value IOError
24-
deriving (Eq)
2524

2625
instance Exception SessionException
2726

lsp-test/src/Language/LSP/Test/Session.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ updateStateC = awaitForever $ \msg -> do
349349
sendMessage $ TResponseMessage "2.0" (Just $ r ^. L.id) $
350350
if null errs
351351
then Right configs
352-
else Left $ ResponseError (InL LSPErrorCodes_RequestFailed) ("No configuration for requested sections: " <> T.pack (show errs)) Nothing
352+
else Left $ TResponseError (InL LSPErrorCodes_RequestFailed) ("No configuration for requested sections: " <> T.pack (show errs)) Nothing
353353
_ -> pure ()
354354
unless (
355355
(ignoringLogNotifications state && isLogNotification msg)

lsp-test/test/DummyServer.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ handlers =
255255
, requestHandler SMethod_TextDocumentSemanticTokensFull $ \_req resp -> do
256256
let tokens = makeSemanticTokens defaultSemanticTokensLegend [SemanticTokenAbsolute 0 1 2 SemanticTokenTypes_Type []]
257257
case tokens of
258-
Left t -> resp $ Left $ ResponseError (InR ErrorCodes_InternalError) t Nothing
258+
Left t -> resp $ Left $ TResponseError (InR ErrorCodes_InternalError) t Nothing
259259
Right tokens -> resp $ Right $ InL tokens
260260
, requestHandler SMethod_TextDocumentInlayHint $ \req resp -> do
261261
let TRequestMessage _ _ _ params = req

lsp-types/ChangeLog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Unreleased
44

55
- Add support for identifying client and server capabilities associated with a method.
6+
- `TResponseMessage` now contains a `TResponseError` instead of a `ResponseError`
67

78
## 2.2.0.0 -- 2024-04-29
89

lsp-types/src/Language/LSP/Protocol/Message/Types.hs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,7 @@ toUntypedResponseError (TResponseError c m d) = ResponseError c m (fmap toJSON d
192192
data TResponseMessage (m :: Method f Request) = TResponseMessage
193193
{ _jsonrpc :: Text
194194
, _id :: Maybe (LspId m)
195-
, -- TODO: use `TResponseError m` for the error type, this will require quite a lot of adaptation downstream
196-
_result :: Either ResponseError (MessageResult m)
195+
, _result :: Either (TResponseError m) (MessageResult m)
197196
}
198197
deriving stock (Generic)
199198

lsp-types/test/JsonSpec.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ spec = do
7777
let input = "{\"jsonrpc\": \"2.0\", \"id\": 123, \"error\": { \"code\": -32700, \"message\": \"oh no\", \"data\": null }}"
7878
in J.decode input
7979
`shouldBe` Just
80-
( (TResponseMessage "2.0" (Just (IdInt 123)) (Left $ ResponseError (InR ErrorCodes_ParseError) "oh no" (Just J.Null))) ::
80+
( (TResponseMessage "2.0" (Just (IdInt 123)) (Left $ TResponseError (InR ErrorCodes_ParseError) "oh no" (Just J.Null))) ::
8181
TResponseMessage ('Method_CustomMethod "hello")
8282
)
8383
it "throws if neither result nor error is present" $ do

lsp/ChangeLog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
- Drop dependency on `uuid` and `random`
66
- Fix handling of `rootPath` in `intializeParams`
7+
- Update to newer `lsp-types`
78

89
## 2.6.0.0
910

lsp/src/Language/LSP/Server/Core.hs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ data LspCoreLog
7474
NewConfig J.Value
7575
| ConfigurationParseError J.Value T.Text
7676
| ConfigurationNotSupported
77-
| BadConfigurationResponse ResponseError
77+
| BadConfigurationResponse (TResponseError Method_WorkspaceConfiguration)
7878
| WrongConfigSections [J.Value]
7979
| forall m. CantRegister (SMethod m)
8080

@@ -177,7 +177,7 @@ newtype ClientMessageHandler f (t :: MessageKind) (m :: Method ClientToServer t)
177177
from the server or client
178178
-}
179179
type family Handler (f :: Type -> Type) (m :: Method from t) = (result :: Type) | result -> f t m where
180-
Handler f (m :: Method _from Request) = TRequestMessage m -> (Either ResponseError (MessageResult m) -> f ()) -> f ()
180+
Handler f (m :: Method _from Request) = TRequestMessage m -> (Either (TResponseError m) (MessageResult m) -> f ()) -> f ()
181181
Handler f (m :: Method _from Notification) = TNotificationMessage m -> f ()
182182

183183
-- | How to convert two isomorphic data structures between each other.
@@ -348,7 +348,7 @@ data ServerDefinition config = forall m a.
348348
-- the new config. Servers that want to react to config changes should provide
349349
-- a callback here, it is not sufficient to just add e.g. a @workspace/didChangeConfiguration@
350350
-- handler.
351-
, doInitialize :: LanguageContextEnv config -> TMessage Method_Initialize -> IO (Either ResponseError a)
351+
, doInitialize :: LanguageContextEnv config -> TMessage Method_Initialize -> IO (Either (TResponseError Method_Initialize) a)
352352
-- ^ Called *after* receiving the @initialize@ request and *before*
353353
-- returning the response. This callback will be invoked to offer the
354354
-- language server implementation the chance to create any processes or
@@ -383,7 +383,7 @@ data ServerDefinition config = forall m a.
383383
request with either an error, or the response params.
384384
-}
385385
newtype ServerResponseCallback (m :: Method ServerToClient Request)
386-
= ServerResponseCallback (Either ResponseError (MessageResult m) -> IO ())
386+
= ServerResponseCallback (Either (TResponseError m) (MessageResult m) -> IO ())
387387

388388
{- | Return value signals if response handler was inserted successfully
389389
Might fail if the id was already in the map
@@ -412,7 +412,7 @@ sendRequest ::
412412
MonadLsp config f =>
413413
SServerMethod m ->
414414
MessageParams m ->
415-
(Either ResponseError (MessageResult m) -> f ()) ->
415+
(Either (TResponseError m) (MessageResult m) -> f ()) ->
416416
f (LspId m)
417417
sendRequest m params resHandler = do
418418
reqId <- IdInt <$> freshLspId

lsp/src/Language/LSP/Server/Processing.hs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,9 @@ initializeRequestHandler logger ServerDefinition{..} vfs sendFunc req = do
196196
makeResponseMessage rid result = TResponseMessage "2.0" (Just rid) (Right result)
197197
makeResponseError origId err = TResponseMessage "2.0" (Just origId) (Left err)
198198

199-
initializeErrorHandler :: (ResponseError -> IO ()) -> E.SomeException -> IO (Maybe a)
199+
initializeErrorHandler :: (TResponseError Method_Initialize -> IO ()) -> E.SomeException -> IO (Maybe a)
200200
initializeErrorHandler sendResp e = do
201-
sendResp $ ResponseError (InR ErrorCodes_InternalError) msg Nothing
201+
sendResp $ TResponseError (InR ErrorCodes_InternalError) msg Nothing
202202
pure Nothing
203203
where
204204
msg = T.pack $ unwords ["Error on initialize:", show e]
@@ -518,13 +518,13 @@ handle' logger mAction m msg = do
518518
(Nothing, Just (ClientMessageHandler h)) -> Just h
519519
(Nothing, Nothing) -> Nothing
520520

521-
sendResponse :: forall m1. TRequestMessage (m1 :: Method ClientToServer Request) -> Either ResponseError (MessageResult m1) -> m ()
521+
sendResponse :: forall m1. TRequestMessage (m1 :: Method ClientToServer Request) -> Either (TResponseError m1) (MessageResult m1) -> m ()
522522
sendResponse req res = sendToClient $ FromServerRsp (req ^. L.method) $ TResponseMessage "2.0" (Just (req ^. L.id)) res
523523

524524
requestDuringShutdown :: forall m1. TRequestMessage (m1 :: Method ClientToServer Request) -> m ()
525525
requestDuringShutdown req = do
526526
logger <& MessageDuringShutdown m `WithSeverity` Warning
527-
sendResponse req (Left (ResponseError (InR ErrorCodes_InvalidRequest) "Server is shutdown" Nothing))
527+
sendResponse req (Left (TResponseError (InR ErrorCodes_InvalidRequest) "Server is shutdown" Nothing))
528528

529529
notificationDuringShutdown :: m ()
530530
notificationDuringShutdown = logger <& MessageDuringShutdown m `WithSeverity` Warning
@@ -541,7 +541,7 @@ handle' logger mAction m msg = do
541541
missingRequestHandler req = do
542542
logger <& MissingHandler False m `WithSeverity` Error
543543
let errorMsg = T.pack $ unwords ["No handler for: ", show m]
544-
err = ResponseError (InR ErrorCodes_MethodNotFound) errorMsg Nothing
544+
err = TResponseError (InR ErrorCodes_MethodNotFound) errorMsg Nothing
545545
sendResponse req (Left err)
546546

547547
progressCancelHandler :: (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) -> TMessage Method_WindowWorkDoneProgressCancel -> m ()

0 commit comments

Comments
 (0)